@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: • @RunWith(SomeRunner.class) swaps in an alternate test runner for the class, such as SpringRunner or MockitoJUnitRunner. • @Rule fields implement TestRule and wrap around each test method's execution to add reusable setup/teardown or constraints. • Common built-in rules include TemporaryFolder for disposable test directories and ExpectedException for exception assertions. • @ClassRule applies the same wrapping behavior once per class instead of once per test method. • JUnit 5 replaces both @RunWith and @Rule with a unified Extension model registered via @ExtendWith.
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."