Search code examples
javaspringspring-bootspring-mvcspring-bean

Spring Boot @MockBeans - How to use the same beans in multiple test classes


I have multiple security test classes where I am testing authorization to different REST endpoints, and I would like to mock the beans of all the repositories that ApplicationContext will spin up. I have the tests running and everything works correctly, but I'd like to not duplicate my @MockBeans in every security test class.

I've tried creating a configuration class and putting the MockBeans there, but I receive a 404 error.

The current test class is setup like this and it works, but I have to duplicate the @MockBeans() in each class:

@WebMvcTest(value = [ScriptController, SecurityConfiguration, ScriptPermissionEvaluator])
@ExtendWith(SpringExtension)
@MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
@MockBean(ChannelSubscriberRepository)])
@ActiveProfiles("test")
class ScriptControllerSecurityTest extends Specification

I'd like to setup a configuration class like this and use it inside of my test class with @ContextConfiguration(classes = MockRepositoryConfiguration) in the test class.

@Configuration
@MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
@MockBean(ChannelSubscriberRepository)])
class MockRepositoryConfiguration
{}

Solution

  • Try creating a custom meta-annotation as follows:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.Type)
    @MockBeans([@MockBean(ObjectRepository), @MockBean(ChannelRepository), 
    @MockBean(ChannelSubscriberRepository)])
    public @interface CustomMockBeans {
    }
    

    And then annotate your test class with it:

    @WebMvcTest(value = [ScriptController, SecurityConfiguration, ScriptPermissionEvaluator])
    @ExtendWith(SpringExtension)
    @CustomMockBeans
    @ActiveProfiles("test")
    class ScriptControllerSecurityTest extends Specification