【问题标题】:possible to junit test a spring rest call?可以对春季休息电话进行junit测试吗?
【发布时间】:2012-06-23 11:37:24
【问题描述】:

是否可以测试内部包含 rest 方法的控制器?

    @RequestMapping(value = "/user", method = RequestMethod.PUT,consumes="application/json")
    public ResponseEntity<String>createNewAccount(HttpEntity<String>request) {
//do something

}

我将如何使用向该方法发送 http 标头、uri 和内容的虚假 http 请求来调用此方法?任何这样做的存根或模拟类?像

httpMockRequest.consume(uri,headers, body,method, controller class);

然后它会进入我的控制器并根据使用的 uri 和 http 方法查找请求映射,然后执行并发送来自 httpMockRequest 测试对象的 http 标头和内容?

类似的东西存在于 Spring 或 Java EE 中吗?

顺便说一句,我正在使用 Spring 3。

【问题讨论】:

    标签: java unit-testing http rest spring-3


    【解决方案1】:

    最简单的方法就是实例化控制器并直接调用控制器的方法。您的测试应该只测试控制器的实现,而不是整个流程(从 Servlet 到您的方法)。

    我通常在我的测试实现中做这样的事情:

    Controller c = new Controller();
    // configure controller c with mock services
    ResponseEntity<String> re = c.createNewAccount(new HttpEntity<String>("{\"property\":10}"));
    // check response entity (parsing json of re.getBody())
    

    对于标题,你有这个构造函数:

    HttpEntity(T body, MultiValueMap<String, String> headers)
    

    URI 本身在这里并不重要,因为它仅用于解析控制器和方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2023-01-23
      • 2015-05-04
      • 1970-01-01
      • 2013-03-23
      • 2015-03-15
      相关资源
      最近更新 更多