我有以下控制器接受输入@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
作为输入编写测试类。
任何帮助将不胜感激..
答案 0 :(得分:7)
我刚刚解决了这个问题。我刚刚更改了网址。现在它在测试类中包含如下参数:
mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());
答案 1 :(得分:0)
您可以使用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
}