Sandeep Rao
Sandeep Rao

Reputation: 1757

How to mock the WebResource Rest call

How to mock the following lines of code

WebResource jobBuilder = restClient.resource(jobBuilderUrl);
String jobXml = jobBuilder
    .accept(MediaType.APPLICATION_XML)
    .type(MediaType.APPLICATION_JSON)
    .entity(request)
    .post(String.class);

I have tried to mock it using easy mock with the following code but it is returning a NullPointerException

WebResource jobBuilder = EasyMock.createMock(WebResource.class);
expect(jobBuilder
    .accept(MediaType.APPLICATION_XML)
    .type(MediaType.APPLICATION_JSON)
    .entity(EasyMock.notNull())
    .post(String.class)).andReturn("<test></test>");
replay(jobBuilder);

Upvotes: 2

Views: 1490

Answers (2)

efelton
efelton

Reputation: 181

I was getting the NullPointerException as well. I got around it by returning a Mock Builder object from the call to accept()

ClientResponse clientResponse = createMock(ClientResponse.class);
expect(clientResponse.getStatus()).andReturn(200).anyTimes();
expect(clientResponse.getEntity(FOO.class)).andReturn(jobInfo).anyTimes();
replay(clientResponse);

Builder builder = createMock(Builder.class);
expect(builder.get(ClientResponse.class)).andReturn(clientResponse).anyTimes();
replay(builder);

WebResource jobResource = createMock(WebResource.class);
expect(jobResource.accept(MediaType.APPLICATION_JSON)).andReturn(builder).anyTimes();
replay(jobResource);

now the call in my production code

ClientResponse response = this.jobResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

FOO foo = response.getEntity(FOO.class);

does what I expect it to.

Upvotes: 0

Ryan Stewart
Ryan Stewart

Reputation: 128749

How to mock the following lines of code

Don't. There's no value in it. Instead start an embedded HTTP server and verify it receives the requests you expect it to. That's what you really care about when writing this code, so that's what you should test. This is very easy to do with the Simple Framework or Jetty.

Case in point:

jobBuilder
    .accept(MediaType.APPLICATION_XML)
    .type(MediaType.APPLICATION_JSON)
    .entity(request)
    .post(String.class);

is identical to:

jobBuilder
    .accept(MediaType.APPLICATION_XML)
    .entity(request)
    .type(MediaType.APPLICATION_JSON)
    .post(String.class);

is identical to:

jobBuilder
    .accept(MediaType.APPLICATION_XML)
    .type(MediaType.APPLICATION_JSON)
    .post(String.class, entity);

... and so on. All create the same HTTP request, but all would require different and tightly-coupled test code. That's not how you want your tests to be.

Upvotes: 1

Related Questions