Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 255
valen ezu Avatar asked Oct 30 '25 05:10

valen ezu


1 Answers

@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.

like image 170
davidxxx Avatar answered Oct 31 '25 20:10

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!