Envin
Envin

Reputation: 1523

What is the best way to unit test REST Endpoints (Jersey)

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

I was looking into the REST-assured framework and I like how that looks but I can only use it when my web server is up and running.

Is there a way for me to run a in-memory web server, or something like that? Are there any examples of REST endpoint testing that someone can provide?

Upvotes: 4

Views: 7770

Answers (1)

Danix
Danix

Reputation: 1947

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

You can take a look at the example also

An integration test example, could be:

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

Upvotes: 3

Related Questions