[英]unit testing for spring mvc controller with Integer value as @RequestParam
我有以下控制器接受輸入為@RequestParam
@RequestMapping(value = "/fetchstatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response fetchStatus(
@RequestParam(value = "userId", required = true) Integer userId) {
Response response = new Response();
try {
response.setResponse(service.fetchStatus(userId));
response = (Response) Util.getResponse(
response, ResponseCode.SUCCESS, FETCH_STATUS_SUCCESS,
Message.SUCCESS);
} catch (NullValueException e) {
e.printStackTrace();
response = (Response) Util.getResponse(
response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
} catch (Exception e) {
e.printStackTrace();
response = (Response) Util.getResponse(
response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
}
return response;
}
我需要一個單元測試類,我是spring mvc的初學者。 我不知道用@RequestParam
編寫測試類作為輸入。
任何幫助將不勝感激 ..
我剛剛解決了這個問題。 我剛剛更改了網址。 現在它在測試類中包含如下參數:
mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());
您可以使用MockMvc來測試Spring控制器。
@Test
public void testControllerWithMockMvc(){
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllerInstance).build();
mockMvc.perform(get("/fetchstatus").requestAttr("userId", 1))
.andExpect(status().isOk());
}
此外,只要您只需要測試類中的邏輯,就可以使用純JUnit來完成它
@Test
public void testControllerWithPureJUnit(){
Controller controller = new Controller();
//do some mocking if it's needed
Response response = controller.fetchStatus(1);
//asser the reponse from controller
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.