Mocking REST resources with JMock and Jersey
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
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
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:
- Set up the test fixture by hosting two blog resources on local HTTP servers listening on different ports
- Use the Jersey client to HTTP GET and deserialize the JSON representation of the blogs
- 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.