Search code examples
javaweb-testing

Can @WebMvcTest have two controllers


I am Trying to test two different controller classes , Since I want to test one method each from the both classes and I will be using @WebMvcTest , My question is there a way to inject mocks into both classes , something like this may be ?

@WebMvcTest(HomeController.class , BookController.class)
public class ControllerTest{

ofcourse this gives error , so does that mean when using @WebMvcTest we can test only methods in one controller ? per class


Solution

  • @WebMvcTest accepts Class<?>[] as value() :

    public @interface WebMvcTest {
      ...
        @AliasFor("controllers")
        Class<?>[] value() default {};
      ...
    }
    

    Passing a single value (possible only because it is annotation) or an array is so legal.
    Your problem is you don't use the correct syntax to declare a literal array.
    Try :

    @WebMvcTest({HomeController.class, BookController.class})
    public class ControllerTest{
    

    Note that by annotating your test class with @WebMvcTest without valuing any param in the annotation declaration :

    @WebMvcTest
    public class ControllerTest{
    

    all Spring controllers are added in the Spring context.