Search code examples
jsonjunitjerseyresponsemockito

Convert java.ws.rs.core.Response to JSON for jUnit testing


We have to test our JavaEEServer with jUnit. For this reason we want to test our REST get-methods. We implemented these methods with the Jersey framework. For this reason, the methods return responses with the type: java.ws.rs.core.Response.

How can we convert these responses to JSON, when we want to test it from server side, so just want to call the methods directly?

Example:

@GET
@Path("getallemployees")
@Produces("application/json")
public Response getAllEmployees() {
    //here we create a generic entity (this works)
    return Response.ok(entity).build();
}

What we need for the tests:

@Test
public void testgetAllEmployees() {
    // here we initialize the mocked database content (Mockito)
    Response test = employeeResource.getAllEmployees();
    // here we want to have the Response as JSON
}

Thank you!


Solution

  • It looks like you are trying to mix unit and integration testing where you should choose one instead.

    If you are interested in specific resource implementation you should use unit testing and thus do not care about the JSON output. Just mock resource dependencies, call getAllEmployees() and confirm expectations.

    However, if you are interested in service output then you should probably launch integrated system (possibly using Jetty as a standalone container, and in-memory database if one is needed) and test response using Jersey Client:

    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target("http://example.com/rest").path("getallemployees");
    String rawResponseBody = webTarget.request(MediaType.APPLICATION_JSON).get(String.class);
    

    From my experience, raw response is used rarely. You will probably use entity class instead of String.