繁体   English   中英

测试 Web 层时 MockMvc 为空

[英]MockMvc is null when testing the Web Layer

我的应用程序中有这个 MvcTest:

@SpringBootTest
@WebMvcTest
public class BarsControllerTest {

    @Autowired
    private MockMvc mockMvc;



    @Test
    public void testBars() throws Exception {

        mockMvc.perform(get("/bars")
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.*", hasSize(1)));
    }
}

但是当我运行测试时,mockMvc 在运行测试时为空。

您不应该同时使用@WebMvcTest@SpringBootTest

如果要同时测试 web 层和其他层,请一起使用@AutoConfigureMockMvc@SpringBootTest

@SpringBootTest
@AutoConfigureMockMvc
public class BarsControllerTest {

    @Autowired
    private MockMvc mockMvc;



    @Test
    public void testBars() throws Exception {

        mockMvc.perform(get("/bars")
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.*", hasSize(1)));
    }
}

或者,如果您只想测试 web 层,您可以只使用@WebMvcTest :注意这不会加载完整的 spring 应用程序上下文(它只加载 web 层)

@WebMvcTest
public class BarsControllerTest {

    @Autowired
    private MockMvc mockMvc;



    @Test
    public void testBars() throws Exception {

        mockMvc.perform(get("/bars")
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.*", hasSize(1)));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM