The website of James Shaw, a PhD student researching numerical methods for the atmosphere at University of Reading

Mocking REST resources with JMock and Jersey

2 August 2012

To test code that interacts with a REST resource, we need an HTTP server which provides access to a fake version of that resource. After a friend of mine released a fake HTTP library, I started thinking about whether JMock could be used to mock out REST resources.

Let's work through an example application. We are writing a blog aggregator that has a single capability: to provide the most recent article from each blog in a collection blogs. The blogs are available as REST resources hosted on different HTTP servers.


JMock is a library that is normally used for mocking dependencies in unit tests. A unit test for our blog aggregator might look like this:


Jersey, the reference implementation of JAX-RS, exposes annotated POJOs as REST resources. Our blog resource looks like this: The library comes with a test framework that lets us serve resources from an HTTP server embedded in a JUnit test.

Writing the integration test

Our integration test is going to:

  1. Set up the test fixture by hosting two blog resources on local HTTP servers listening on different ports
  2. Use the Jersey client to HTTP GET and deserialize the JSON representation of the blogs
  3. Verify that the aggregator produces the expected feed

Let's take a look at the test implementation:

A working version of the blog aggregator is available on GitHub.