Wiremock stateful behaviour

In distributed systems architecture, testing becomes much more complex than in monolith architecture. Although only end-to-end testing gives us full confidence of system-wide implementations, we should also test services in isolation. The easiest way to obtain isolation in microservices architecture is to stub external applications.

The problem is that mocks are usually stateless – they simulate application logic with fixed actions, without any conditional behaviour. If we want to test cases like HTTP latency or data redundancy validations, where external service represents different behaviour among repeated calls, simple mocks can be insufficient.

Wiremock, mocking tool which I described already in previous posts, provides simple yet efficient feature that address those challenges, called stateful scenarios. The idea is to declare different responses for one method, and mark every one of them with tags representing scenario states. When you perform a request, then you also set your mock in certain state.

Example scenario 1 – data validation

Imagine that you want to test your application against external service. The scenario is to POST user data to external endpoint. First request should result in response with newly created user ID. Then, If you post the same user’s data again, you should see response code 400 with user already exists exception. Wiremock mapping example is:

…and second state behaviour is:

Example scenario 2 – network latency

Every developer should be aware of HTTP network issues. In second scenario, we’d like to test our application timeout policy: We will perform GET request on external service – first one should respond with 5sec delay, and the second should succeed without any latency. Example for wiremock stub is:

…and second state behaviour is:

Continue reading

If you want to continue reading and expand your knowledge in area of  REST and microservices, I recommend you these books:

  • Building Microservices – one of the most important books for me, everything you want to know about microservices is here
  • RESTful Web APIs – another great book about REST architecture. Lots of practical knowledge about designing and consuming RESTful APIs


As you can see on the code examples, we’re not faking application logic, we’re just simulate it’s states. In above scenarios, we limit ourselves to two states, but it’s basically up to us how many we’ll provide. Wiremock is pretty flexible in terms of HTTP calls simulation, so you can experiment with more composite scenarios. I can also recommend official documentation.

If you have any thoughts or questions – feel free to leave a comment!