Given the following class definition:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ErrorHandlerTest{
@MockBean
private ErrorHandler errorHandler;
the successful injection of the @MockBean
annotated class ErrorHandler
depends on the execution order of all tests. As the class has DirtiesContext set to BEFORE_CLASS
, I would not expect side effects from other classes.
- If this Test is executed first, the mocked Bean is injected and the test succeeds.
- If any other Test is executed before this test, the mocked Bean is not injected, but the context is reused. Resulting in a failure of the test.
At first I thought that the DirtiesContext may override the mocked Bean, but as the test executes successfully standalone (or in the right order), and there isn't any indication of an actual new context. I have disregarded that thought.
If the class preceding the test is annotated with DirtiesContext.ClassMode.AFTER_CLASS
the mocked Bean is injected.
Why does using AFTER_CLASS
in the class before work, but BEFORE_CLASS
in the current class not?