我想测试一个基本的控制器:春季控制器测试失败,尽管URL工作
@Autowired
DAOInterface db;
@RequestMapping(value = "/postdb", method = RequestMethod.GET)
@ResponseBody
public String postdb(
@RequestParam(value = "id", required = true) String id
) {
db.addEntry(id);
return "Added " + id + ".";
}
该网址的作品,当我访问它,它把它添加到数据库和我得到的字符串输出作为响应。
我想为它创建一个简单的单元测试:
@Autowired
MockMvc mockMvc;
@MockBean
DAOInterface daoInterface;
@Test
public void shouldReturnA200() throws Exception {
mockMvc.perform(get("/postdb?id=3"))
.andExpect(status().isOk());
}
而是我得到以下
MockHttpServletRequest:
HTTP Method = GET
Request URI = /postdb
Parameters = {id=[3]}
Headers = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
不知道为什么我它在工作时,我尝试访问它,但失败运行此测试时。我没有看到任何问题。可能是因为我没有使用任何头文件或正式的响应体/视图,而只是输出一个字符串?
EDIT =它的工作原理,当我加 .contextPath("/postdb"))
..不知道如果这是正确的做法,但是当我写另一个测试不包括任何要求paramters,该测试给出了200,而不是400或404 ....
错字 - 'posttodb'没有找到。应该是'postdb' –
您是否使用绝对URL进行了测试http:// localhost:8080/app-name/postdb?id = 3? – Flocke
@LeonardoAlvesMachado当我写这个问题时,这是一个错字。编辑错字。 – dfqupwndguerrillamailde