What is the best way for unit test REST endpoints (jersey)

I have a REST controller that has several GET / POST / PUT methods that all respond / request JSON. I do not use Spring in this application (yet).

I looked into a REST-guaranteed structure and I like how it looks, but I can only use it when starting and starting a web server.

Is there a way to run the web server in memory or something like that? Are there any REST endpoint testing examples that anyone can provide?

+4
source share
1 answer

If you are using JAX-RS 2.0, you should find your answer here.

:

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);
    }
}
+3

Source: https://habr.com/ru/post/1541285/


All Articles