单元测试REST端点(Jersey)的最佳方法是什么

时间:2014-05-20 14:22:38

标签: java json unit-testing rest testing

我有一个REST控制器,它有多个GET / POST / PUT方法,都响应/请求JSON。 我还没有在这个应用程序中使用Spring。

我正在研究REST保证的框架,我喜欢它看起来如何,但我只能在我的Web服务器启动并运行时使用它。

我有办法运行内存中的Web服务器,或类似的东西吗? 是否有人可以提供的REST端点测试示例?

1 个答案:

答案 0 :(得分:3)

如果您使用的是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);
    }
}