练习Springboot2.x搭建项目的时候做mock测试报出如下错误:
java.lang.AssertionError: Status
Expected :200
Actual :404
网上资料不多,查找了几个解决方法并没有解决问题
简书上有一个是这样写的:
参考:简书:糖先生要健康生活的文章:spring boot mock mvc 404错误原因
我的错误是另外一个原因:
Controller代码:
@RestController
public class UserController {
@RequestMapping("hello")
public String hello(){
return "hello world2";
}
}
Test代码:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @Author: lt
* @Date: 2019/7/10 15:31
*/
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void hello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
因为习惯问题,@RequestMapping(“hello”)的地址会不写“/”,在测试 mockMvc.perform(MockMvcRequestBuilders.get(“hello”).accept(MediaType.APPLICATION_JSON))也没有写“/”
就是这个“/”导致了404
正确写法:
mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
为了统一,建议@RequestMapping(“hello”)也写成:
@RequestMapping("/hello")