美文网首页
spring boot mock mvc 404错误原因

spring boot mock mvc 404错误原因

作者: 糖先生要健康生活 | 来源:发表于2018-06-08 17:01 被阅读0次

使用mockmvc 对controller进行测试的时候,测试案例执行后,报404错误。而如果启动应用,使用postman发送请求,则能够成功获得响应。

错误代码如下:

java.lang.AssertionError: Status 
Expected :200                     
Actual   :404 

Controller类的代码如下:

@RestController
public class TestController {

    @Autowired
    TestService testService;

    @PostMapping("/test")
    public String test(@RequestBody TestData testdata) {
        return testService.welcome(testData);
    }

}

测试用例代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationStarter.class)
public class ExampleTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
                .build();//初始化MockMvc对象
    }

    @Test
    public void getHello() throws Exception {
        String response = mockMvc.perform(
                post("/welcome/test") //请求url,请求方法
                        .contentType(MediaType.APPLICATION_JSON_UTF8) // 请求数据格式
        ).andExpect(MockMvcResultMatchers.status().isOk())//断言,验证执行结果
                .andDo(print())//结果处理器,打印结果到控制台
                .andReturn().getResponse().getContentAsString(); //获取响应数据
    }
}

由于404是代表没有找到对应路径,故做了以下检查。

  1. 检查被测Controller类,是否使用@RestController进行注解。(检查正确)
  2. 检查Starter类是否设置@ComponentScan(basePackages = {}) (检查正确)

最终发现,在application.properties中设置了以下属性:

server.context-path=/welcome

在测试类中,不需要将根路径写进去。将测试类中的

String response = mockMvc.perform(
                post("/welcome/test") //请求url,请求方法

修改为:

String response = mockMvc.perform(
                post("/test") //请求url,请求方法

测试案例执行通过。

相关文章

网友评论

      本文标题:spring boot mock mvc 404错误原因

      本文链接:https://www.haomeiwen.com/subject/rfmasftx.html