Using @MockBean in tests forces reloading of Application Context

Viewed 11581

I have several integration tests running on Spring Framework that extend the base class called BaseITCase.
Like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppCacheConfiguration.class, TestConfiguration.class}, loader = SpringBootContextLoader.class)
@Transactional
@WebMvcTest
public abstract class BaseITCase{...}
...
public class UserControllerTest extends BaseITCase {...}

The problem is that one of the test has several declarations of: @MockBean inside of it and the moment this test executed, Spring recreates context and the tests that follows this one sometimes use wrong beans(from the context created exactly for the test with @MockBean). I found out about that just by checking that beans have different hashcodes.

It becomes really critical when I use @EventListener. Because listeners for wrong context(context of the test class that has already finished execution) are invoked and I have wrong beans there.

Is there any workaround for that?

I tried to move all @MockBean declarations to basic class and it worked fine because new context is not created. But, it makes basic class too heavy. Also, I tried to make a dirty context for this test, but then the next test fails with message that context has already been closed.

2 Answers

@MockBean may cause the context to reload as explained in the previous answer.

As an alternative and if you're using spring boot 2.2+, you can use @MockInBean instead of @MockBean. It keeps your context clean and does not require your context to get reloaded.

@SpringBootTest
public class UserControllerTest extends BaseITCase {

    @MockInBean(UserController.class)
    private Foo foo;

    @Autowired
    private UserController userController;

    @Test
    public void test() {
        userController.doSomething();
        Mockito.verify(foo).hasDoneSomething();
    }
}

@Component
public class UserController {

    @Autowired
    private Foo foo;

}

disclaimer: I created this lib for this exact purpose: mock beans in spring beans and avoid lengthy context recreation.

Related