@WebMvcTest由于某种原因创建多个控制器 [英] @WebMvcTest creating more than one Controller for some reason

查看:95
本文介绍了@WebMvcTest由于某种原因创建多个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 @WebMvcTest 创建一个控制器测试,据我了解,当我在测试类的 @WebMvcTest(ClientController.class)批注中添加时它不应创建大量的bean,而应创建此控制器所需的所有bean.

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.

我正在使用 @MockBean 来模拟该控制器所需的bean,但是由于某种原因,它失败了,除了另一个没有服务的'Noqualing bean'该控制器需要,但另一个需要.

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.

因此该测试失败:

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

    @MockBean
    ClientService clientService;

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

}

我创建了一个相同版本(2.0.1)的空Spring Boot项目,并尝试在该项目上创建测试.效果很好.

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.

所以我的问题可能是因为我的项目具有许多依赖关系,但是在这种情况下也许有一些常见的做法可供参考?什么会弄乱 @WebMvcTest 逻辑?

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?

推荐答案

我找到了一种解决方法.不使用@WebMvcTest和@MockBean,而是手动创建所有内容:

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();
}

与Spring 1.4.X和Spring Boot 2.X一起使用(那里和那里有不同的异常),但是仍然不能解释为什么@WebMvcTest不起作用

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

这篇关于@WebMvcTest由于某种原因创建多个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆