users@jersey.java.net

[Jersey] Unit testing and mocking against (Async)WebResource and its RequestBuilder

From: <olvesh_at_gmail.com>
Date: Thu, 7 Jun 2012 09:50:54 +0000 (GMT)

I have found it very difficult to unit-test (by the way of mockito)
client resource calls in jersey-client 1.12

I try to do it like this in my unit-test (my adapter only knows about
the resource, not the JerseyClient):
        
        final AsyncWebResource resourceMock =
Mockito.mock(AsyncWebResource.class);
        final AsyncWebResource.Builder builderMock =
Mockito.mock(AsyncWebResource.Builder.class);

       
Mockito.when(resourceMock.accept(MediaType.APPLICATION_JSON_TYPE)).then
Return(builderMock);
        Mockito.when(resourceMock.get(JsonNode.class)).thenReturn(new
AsyncResult<JsonNode>(new TextNode("ok")));

        ProductDAOAdapterCFP productAdapterCFP = new
ProductDAOAdapterCFP(resourceMock);

Part of the problem is that the AsyncWebResource.Builder.class is final
(and has a private default constructor).

In my opinion this design has flaws, as you have to know the concrete
implementation of the RequestBuilder to be able to use the interface.
This is imo a leaky abstraction as I have no benefit of the
RequestBuilder interface when used via an (Async)WebResource.

And it doesnt make the case better when the returned Builder
implementation also implements AsyncUniformInterface as well, so there
is no single common point to mock.

Wouldn't it be better to have a (Async)WebResource implement
RequestBuilder<SomeInterfaceCombiningUniformInterfaceAndRequestBuilder>
, and have that type declared as return-types in the (Async)WebResource
methods?

This wouldn't even break any code, although many new interfaces must be
created...


Anyway, this is my 2 cents which I found when digging into the
client-code trying to find a way to mock my client-resources. Hopefully
 I have missed some simple way of doing this..

So, does anyone have any good examples to how to mock client-resources
when unit-testing?


Regards,
Olve Hansen