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?
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.
As Hal8k said, if you don't specify a controller like @WebMvcTest(YourController.class), it will try to load all @Controller components. And @Import(WebSecurityConfig.class) also try to inject components in WebSecurityConfig.class. 
Refer : https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With