Search code examples
spring-mvcspring-bootspring-boot-test

Avoid proliferation of @MockBeans in Spring Boot @WebMvcTest test


I have a simple controller e.g.

@Controller
public class FooController
{
    @Autowired
    private BarService barService;

    @RequestMapping(value = "/foo", method = RequestMethod.GET)
    public String displayFoo()
    {
        return "foo";
    }
}

When I want to do a @WebMvcTest, I have to create a great number of @MockBeans to prevent a NoSuchBeanDefinitionException.

@RunWith(SpringRunner.class)
@WebMvcTest
@Import(WebSecurityConfig.class)
public class FooControllerTest
{
    @MockBean ...
    @MockBean ...
    @MockBean ...
    ...
    ...
}

Does this mean that BarService is somehow creating a chain of dependencies? (it has some dependencies but some @MockBeans appear completely unrelated).

The problem is, is that each @WebMvcTest I add for different controllers also requires the same @MockBeans.

Should I be using an annotation like @TestConfiguration to specify all the @MockBeans for the DRY principal?


Solution

  • I looked at this again, and found you can pass the controller name to @WebMvcTest e.g. @WebMvcTest(FooController.class).

    Specifies the controllers to test. May be left blank if all {@code @Controller} beans should be added to the application context.