Karan
Karan

Reputation: 15094

Testing a Jersey Client wrapper

I am trying to write a test for an API client that uses Jersey Client to make the requests.

I wanted to fake a certain server response to return a pre-captured json string.

Eg.

client().resource("/recommendations").queryParam("username", karan").get(Recommendation.class)

should return the appropriate class based on a json string I have stored in a file.

How can I fake that? Or would I have to instantiate a fake server to return the actual json, and let the jersey client to do it's work?

Thanks

Upvotes: 0

Views: 531

Answers (1)

jaco0646
jaco0646

Reputation: 17066

One popular solution is to use a testing framework like EasyMock or Mockito to create a mock Jersey client which expects specific method calls and returns predefined data (e.g. json). The mock is then injected into the API client in place of the real Jersey client.

In general, you can also avoid the frameworks by creating the mock yourself, i.e. subclassing the client and overriding methods you expect to call, to return predefined data. Then pass your mock into the API client as a constructor argument. Whether or not you justify a framework depends on how much mocking you expect to need, which is determined in part by how many external dependencies you have.

Upvotes: 1

Related Questions