我想測試一個基本的控制器:春季控制器測試失敗,儘管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