I often see mock, or stub, servers being configured in frontend projects. I see hard coded JSON files that are very likely to not match the true responses of the actual API. Here is how I automate creation of a type safe, reliable, stub server in a runnable, self contained, JAR. Packaged whenever the API is packaged.

Implementation

A fully working example is implemented here, with Maven:
https://github.com/tomasbjerre/wiremock-jaxrs-example

I have a multi module Maven setup with these modules:

  • module - Parent pom.
  • module-api - JAX-RS annotated API. Very slim API jar.
  • module-api-mock - Runnable mock-server based on Wiremock JAX-RS.

In the module-api-mock I create a test case that produces the configuration of the stub. I use a test case just because that is an easy way to get some code to run during the build.

I use Wiremock JAX-RS to automatically configure the stub. By looking at how may JAX-RS resource is annotated.

My resource looks something like this:

@Path("/")
public interface ExampleResource {
  @GET
  @Path("/get")
  @Produces(MediaType.APPLICATION_JSON)
  public ItemDTO getItem(@QueryParam("filter1") String filter1);

  @POST
  @Path("/create")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public void createItem(ItemDTO item);
}

And I configure the stub something like this:

stubFor(
   invocation(ExampleResource.class, (r) -> r.getItem("abc")) //
      .willReturn(aResponse().withStatus(SC_NOT_FOUND)));

for (final ItemDTO itemDto : MockFactory.getAllItems()) {
  stubFor(
     invocation(ExampleResource.class, (r) -> r.getItem(itemDto.getAttr1())) 
        .willReturn(aResponse().withStatus(SC_ACCEPTED), itemDto));

  stubFor(
     invocation(ExampleResource.class, (r) -> r.createItem(itemDto)) //
       .willReturn(aResponse().withStatus(SC_ACCEPTED)));
}

In this example the invocation(...) comes from Wiremock JAX-RS.

This will make Wiremock produce JSON. I then package Wiremock-standalone together with this JSON into a self contained JAR. This JAR can then be run from command line to get a reliable (type safe) mock server to use for other development, like frontend.

Something like this will give me a reliable server responding with correct headers and datastructures:

java -jar mymodule-api-mock.jar

Advantages

The stubs are created with the same language, Java, as the service is created in. Convenient if you are a Java developer. While still the result is JSON, convenient for frontend developers.

If the API changes, the stub will automatically change. The stub will always match the API. Same types and same headers (accept, content type).

What about Mockito?

You may also do this instead of something like Mockito to in the test cases.

  • Mockito will not test that datastructures serialize and deserialize.
  • Will not test that you are using annotations in a "sane" way.