Can you explain how @RunWith and @Rule work in JUnit?

@RunWith and @Rule are JUnit 4 mechanisms for customizing how tests execute - @RunWith swaps in an alternate test runner for the whole class, while @Rule injects reusable behavior around each individual test method.

Key Points

Example

@RunWith(MockitoJUnitRunner.class) auto-initializes @Mock fields without manual MockitoAnnotations.openMocks() calls, while a @Rule Timeout field enforces a maximum duration on every test in the class.

Interview Tip

A concise interview answer is

@RunWith replaces JUnit's default test runner for the whole class, commonly for Spring or Mockito integration, while @Rule wraps individual test methods with reusable behavior like temporary folders or expected-exception handling. In JUnit 5 both are superseded by the unified Extension model via @ExtendWith.

Last updated: 16 July 2026

Previous question: How do you mock a static method in JUnit? Is it possible without external libraries?

Next question: How would you test private methods in JUnit? Should you test them directly?

More JUnit interview questions

All JUnit questions