弹簧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 }
- Eclipse Mac OS X调试错误:“本机方法中的致命错误:JDWP没有传输初始化,jvmtiError = AGENT_ERROR_TRANSPORT_INIT(197)”
- 使用Java API制作ePub
- 日期的hibernate标准
- 在数组上调用.length与保存大小变量的性能是否存在差异?
- 如何可靠地从类路径资源(jar内)加载XMLCatalog?
- 将另一个java源目录添加到gradle脚本
- 使用Mojo Jaxb2 maven插件创建Java类时生成hashCode()和equals()
- 是否可以在不重写的情况下将数据添加到文件中?
- 使用DigestInputStream计算来自同一InputStream的多个校验和