[英]unit testing for spring mvc controller with Integer value as @RequestParam
I have the following controller which accept input 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;
}
I need a unit test class for this and I am beginner with spring mvc. 我需要一个单元测试类,我是spring mvc的初学者。 I don't know writing test classes with
@RequestParam
as input. 我不知道用
@RequestParam
编写测试类作为输入。
Any help will be appreciated .. 任何帮助将不胜感激 ..
I just solved this issue. 我刚刚解决了这个问题。 I just changed the url.
我刚刚更改了网址。 Now it contains the parameter as below in test class:
现在它在测试类中包含如下参数:
mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());
You can use MockMvc for testing Spring controllers. 您可以使用MockMvc来测试Spring控制器。
@Test
public void testControllerWithMockMvc(){
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllerInstance).build();
mockMvc.perform(get("/fetchstatus").requestAttr("userId", 1))
.andExpect(status().isOk());
}
Also, it is possible to do it using pure JUnit, as long as you need to test only the logic inside your class 此外,只要您只需要测试类中的逻辑,就可以使用纯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.