Unable to Mock Glassfish Jersey Client response object

inboundjaxrsresponse
response.readentity list
jersey client junit test
javax.ws.rs.processingexception: error reading entity from input stream.
mock javax ws rs core response
create inbound response java

I am having problems with creating a mock Response object to use with my unit tests. I am using org.glassfish.jersey.core.jersey-client version 2.3.1 to implement my RESTful client and mockito version 1.9.5 to help me with mock objects. Here is my test's code:

@Test
public void testGetAll() throws IOException {
    // Given
    String expectedResource = "expectedResource"

    final Response expectedRes =  Response.ok(expectedResource, MediaType.APPLICATION_JSON).build();
    String receivedResource;

    BDDMockito.given(this.client.getSimpleClient().getAllWithResponse()).willReturn(expectedRes);

    // When
    receivedResource = this.client.getAll();

    // Then
    Assert.assertNotNull("Request constructed correctly and response received.", receivedResource);
    Assert.assertEquals("Resource is equal to expected.", expectedResource, receivedResource);
}

The problem occurs when this.client.getAll(); is executed. Here is that method's code:

public String getAll() throws GenericAragornException, ProcessingException{
    Response response = this.simpleClient.getAllWithResponse();

    if (response.getStatus() != 200) {
        processErrorResponse(response);
    }

    String entity = response.readEntity(String.class);

    // No errors so return entity converted to resourceType.
    return entity;
}

Note that I am mocking the this.simpleClient.getAllWithResponse() method with the manually created Response. When it reaches the response.readEntity(resourceListType); instruction, Jersey throws the following exception: java.lang.IllegalStateException - Method not supported on an outbound message.. After lots of research and debugging, it turns that, for some reason, when I create a Response using the response builder such as Response.ok(expectedResource, MediaType.APPLICATION_JSON).build(); it creates it as an OutboundResponse instead of as an InboundResponse. The latter are the only ones permitted to use the Response.readEntity() method. If it is an OutboundResponse, the exception is thrown.

However, I could not find any way of converting the manually created response to an InboundResponse. So my tests are doomed :(. Do you guys/gals have any idea of what I can do here? I don't want to mock the Response object with Mockito because I think it could be a code smell since it violates the Law of Demeter. Sincerely I am out of ideas here. Things like this should be simple and straightforward.

I had this error because when you use the ResponseBuilder, it returns an OutboundJaxrsResponse message that can not be processed with readEntity().

I noticed that I had this error only when I was calling the Jax-RS component directly. For exemple, if I have DefaultController annotated with @Path("/default") and if I tried to directly call its method, I could not use readEntity() and had the same error as you.

defaultController.get();

Now, when I was using the grizzly2 test provider and using a client to target the Rest Url (in the previous case, it is /default), the message I received in response was a ScopedJaxrsResponse. And then I could use the readEntity() method.

target("/default").request.get();

In your case, you mocked the simpleClient in order to reply with a response built with ResponseBuilder that is not processed by jersey. It's comparable to calling directly my DefaultController method.

Without mocking the readEntity() method, I suggest you to find a way to get your response processed by Jersey and turned into a ScopedJaxrsResponse.

Hope that helps.

Read response body in JAX-RS client from a post request, was failing due the following error message as described in the Unable to Mock Glassfish Jersey Client Response Object question: java.lang. j'ai des problèmes avec la création d'un objet de réponse simulée à utiliser avec mes tests unitaires. J'utilise la version 2.3.1 de org.glassfish.jersey.core.jersey-client pour implémenter mon client RESTful et la version 1.9.5 de mockito pour m'aider avec les objets mock.

You can also mock response with Mockito:

final Response response = Mockito.mock(Response.class);
Mockito.when(response.getStatus()).thenReturn(responseStatus);
Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(responseEntity);
Mockito.when(response.readEntity(Mockito.any(GenericType.class))).thenReturn(responseEntity);

responseStatus is status code associated with the response and responseEnitty is of course entity you want to return. You can use that mock as a return statment in Mockito (e.g. ... thenReturn(response)).

In my projects I create builders for different types for mocks (in that case Response), so I can easly on demand build required mocks, e.g. Response with status code 200 and some custom entity attached.

Unable to Mock Glassfish Jersey Client response object, I am having problems with creating a mock Response object to use with my unit tests. I am using org.glassfish.jersey.core.jersey-client version 2.3.1 to  org.glassfish.jersey.examples » oauth2-client-google-webapp Apache BSD CDDL Google API data retrieving example using OAuth2 for authentication and authorization Last Release on Apr 10, 2018

Rather than using readEntity(OutputClass.class) you can do something like:

OutputClass entity = (OutputClass)outboundJaxrsResponse.entity

JAX-RS - JerseyTest Examples, import org.glassfish.jersey.test. String response = target("orders/4534/items/​e34").request().get(String.class); import javax.ws.rs.client. Spring - Injecting Prototype Bean Using Java 8 Functions · Mockito - Argument Matchers Spring Cloud - Hystrix Circuit Breaker, getting failure exception in fallback method · Spring  The following are top voted examples for showing how to use org.glassfish.jersey.client.oauth2.ClientIdentifier.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examp

For me, none of these answers worked because I was trying to write a server-side unit test that tested the body of the generated Response instance, itself. I got this exception by calling a line like String entity = readEntity(String.class). Instead of mocking Response object, I wanted to test it.

The fix for me was to substitute the above problematic line to one like:

String entity = (String) outboundJaxrsResponse.getEntity();

javax.ws.rs.core.Response.readEntity java code examples, Status status;Response.status(status).build(); Response.ok().build() \n{}", httpMethod, statusCode, messageEntity); } throw new ApioException( statusCode​, "Request failed: \n" + + "jersey-client-api-vs-jersey-test-framework"; Client client = ClientBuilder. Get view of the response headers and their object values​. Test Jersey Rest Service with JUnit and Jersey Testing with jersey Test Framework is relatively easy. You need to subclass org.glassfish.jersey.test.JerseyTest and configure the resource and/or providers that need to be deployed in order to test our services.

I hit this problem myself, trying to mock a client to a remote service by using Response.ok(entity).build() and then allow my client code to do response.readEntity(...) on the response from my faked up server.

I discuss the subject in https://codingcraftsman.wordpress.com/2018/11/26/testing-and-mocking-jersey-responses/

The issue is that the Response.build() method is intended to produce an outbound response, which is meant to be serialized before being received and deserialized by a real client. The readEntity method is expecting to be called at the point of deserialization.

As other posters have observed, readEntity on an outbound Response will give you the exact entity object you put in. You can even cast it to whatever type you want. Of course this doesn't work on a real inbound response, since the inbound response just has the text/binary of the inbound stream from the server.

I wrote the following code to allow me to use mockito to force an outbound Response to pretend to be an inbound one:

  /**
   * Turn a locally made {@link Response} into one which can be used as though inbound.
   * This enables readEntity to be used on what should be an outbound response
   * outbound responses don't support readEntity, but we can fudge it using
   * mockito.
   * @param asOutbound response built as though being sent to the received
   * @return a spy on the response which adds reading as though inbound
   */
  public static Response simulateInbound(Response asOutbound) {

    Response toReturn = spy(asOutbound);
    doAnswer(answer((Class<?> type) -> readEntity(toReturn, type)))
        .when(toReturn)
        .readEntity(ArgumentMatchers.<Class<?>>any());
    return toReturn;
  }

ClientResponse (Jersey 2.31 API), public class ClientResponse extends org.glassfish.jersey.message.internal. entity; for a zero-length response entities returns a corresponding Java object that  In this tutorial, you will learn developing a RESTful web services API for CRUD operations (Create, Retrieve, Update and Delete), which corresponding to standard HTTP methods POST, GET, PUT and DELETE, using Jersey – an open source REST framework and implementation of JAX-RS (Java API for RESTful Web Services) specification.

Java Code Examples org.glassfish.jersey.client.ClientResponse, This page provides Java code examples for org.glassfish.jersey.client. ClientResponse response, Throwable failure, final AsyncConnectorCallback callback, final int tryCount) asList("Nick")); List<Object> pets = new ArrayList<​Object>(Arrays. public void notFoundWhenNoCircuitBreakers() { when(​keysMock.stream()). This tutorial show you how to use Jersey client APIs to create a RESTful Java client to perform “GET” and “POST” requests to REST service that created in this “Jersey + Json” example. 1. Jersey Client Dependency. To use Jersey client APIs, declares “jersey-client.jar” in your pom.xml file. File : pom.xml

[SOLVED] java.lang.ClassNotFoundException: org.glassfish.jersey , ClassNotFoundException: org.glassfish.jersey.client. x.y which has been support for JAX-RS 2.0, and you are trying to write RESTEasy client then you can face this exception. Full stack trace Response response = target.request().get();​. For example, we will create jersey client for services which we secured in Jersey Secured REST APIs tutorial; and I will be extending the sourcecode created for Jersey RESTful client example. Table of Contents 1. HttpAuthenticationFeature 2. How to secure REST APIs 3. Jersey REST Client Code. 1. Jersey Client – HttpAuthenticationFeature

Automagic Jersey API Testing - 7P Blog, Even though Jersey does provide a dedicated test framework you have to is a Java class and not a JSON string as indicated by our controller. Response response = target("echo") creates a convenience map for retrieving the mock object for a given <groupId>org.glassfish.jersey.media</groupId>. Test RESTful Web Service with JUnit and Mockito Earlier I’ve published a blog post on now to create a RESTful Web Service(JAX-RS) to accept JSON payload with user profile details and how to save user profile details into a MySQL database using Java Hibernate framework .

Comments
  • Thomas, thanks for the input!! Just one question...if it were you... would you mock the readEntity() method?
  • It depends of what you want to test ?
  • That the getAll method does what it is supposed to do and returns what it is supposed to return depending on what it receives.
  • Not ideal to have to change source, but this did the trick. Thanks.
  • Or also LinkedHashMap result = (LinkedHashMap)successResponse.getEntity(); ..
  • Thanks, this was more helpful than the accepted response!
  • Where is that readEntity(toReturn, type) method coming from? Using asOutbound.getEntity() instead works for me, but I was curious as to why I could not get your method to work as is.