@WebMvcTest creating more than one Controller for some reason

你离开我真会死。 提交于 2021-01-29 06:06:34

问题


I'm trying to create a controller test with @WebMvcTest, and as I understand, when I put @WebMvcTest(ClientController.class) annotation of the test class it should not create a whole lot of beans, but just ones that this controller requires.

I'm mocking the bean this controller requires with @MockBean, but somehow it fails with an exception that there's 'No qualifying bean' of another service that does not required by this controller but by another.

So this test is failing:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ClientController.class)
public class ClientControllerTest {

    @MockBean
    ClientService clientService;

    @Test
    public void getClient() {
        assertEquals(1,1);
    }

}

I've created an empty Spring Boot project of the same version (2.0.1) and tried to create test over there. It worked perfectly.

So my problem might be because of the dependencies that my project has many, but maybe there's some common practice where to look in this situation? What can mess @WebMvcTest logic?


回答1:


I've found a workaround. Not to use @WebMvcTest and @MockBean, but to create everything by hand:

//@WebMvcTest(ClientController.class)
@RunWith(SpringRunner.class)
public class ClientControllerTest {

    private MockMvc mockMvc;
    @Mock
    ClientService clientService;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(
                new ClientController(clientService)
        ).build();
}

works with Spring 1.4.X and with Spring Boot 2.X (had different exception there and there), but still doesn't explain why @WebMvcTest doesn't work



来源:https://stackoverflow.com/questions/55078125/webmvctest-creating-more-than-one-controller-for-some-reason

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!