【问题标题】:What is the best way to unit test REST Endpoints (Jersey)单元测试 REST 端点的最佳方法是什么(泽西岛)
【发布时间】:2014-05-20 14:22:38
【问题描述】:
我有一个 REST 控制器,它有多个响应/请求 JSON 的 GET/POST/PUT 方法。
我还没有在这个应用程序中使用 Spring。
我正在研究 REST-assured 框架,我喜欢它的外观,但我只能在我的 Web 服务器启动并运行时使用它。
有没有办法让我运行内存中的 Web 服务器或类似的东西?
是否有任何人可以提供的 REST 端点测试示例?
【问题讨论】:
标签:
java
json
unit-testing
rest
testing
【解决方案1】:
如果您使用的是 JAX-RS 2.0,您应该会找到答案here
你也可以看看example
一个集成测试示例,可以是:
public class CustomerRestServiceIT {
@Test
public void shouldCheckURIs() throws IOException {
URI uri = UriBuilder.fromUri("http://localhost/").port(8282).build();
// Create an HTTP server listening at port 8282
HttpServer server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0);
// Create a handler wrapping the JAX-RS application
HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new ApplicationConfig(), HttpHandler.class);
// Map JAX-RS handler to the server root
server.createContext(uri.getPath(), handler);
// Start the server
server.start();
Client client = ClientFactory.newClient();
// Valid URIs
assertEquals(200, client.target("http://localhost:8282/customer/agoncal").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer/1234").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer?zip=75012").request().get().getStatus());
assertEquals(200, client.target("http://localhost:8282/customer/search;firstname=John;surname=Smith").request().get().getStatus());
// Invalid URIs
assertEquals(404, client.target("http://localhost:8282/customer/AGONCAL").request().get().getStatus());
assertEquals(404, client.target("http://localhost:8282/customer/dummy/1234").request().get().getStatus());
// Stop HTTP server
server.stop(0);
}
}