【问题标题】:unit testing for spring mvc controller with Integer value as @RequestParam整数值作为@RequestParam的spring mvc控制器的单元测试
【发布时间】:2017-01-09 03:03:54
【问题描述】:

我有以下控制器接受输入为@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 作为输入来编写测试类。

任何帮助将不胜感激..

【问题讨论】:

  • 您要编写 UNIT 测试还是 INTEGRATION 测试。如果是单元测试,只需像调用任何其他方法一样调用该方法。如果您想要集成测试,请使用 Spring MVC 测试支持(请参阅参考指南)。
  • 如果输入的参数是整数怎么办。它显示 .param() 需要参数作为字符串。

标签: java spring unit-testing spring-mvc


【解决方案1】:

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

mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());

【讨论】:

  • 奇怪,requestAttr() 应该也能正常工作,如果你设置正确的话。
【解决方案2】:

您可以使用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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多