弹簧mvc控制器的unit testing,整数值为@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; } 

我需要一个unit testing类,我是spring mvc的初学者。 我不知道用@RequestParam编写测试类作为输入。

任何帮助将不胜感激 ..

我刚刚解决了这个问题。 我刚刚更改了url。 现在它在测试类中包含如下参数:

 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 }