Capture response time in wiremock recordings
Wiremock is a wonderful tool for mocking external dependencies for testing. I often swap out the external dependencies/services of an application with wiremock during the application load test.
Wiremock provides a nice recording/snapshotting feature to capture live flows and create stubs from them. It simplifies the effort to create stubs for load tests. I run all my test cases once, record the interactions with dependencies as stubs. These stubs can then be used to perform the load test without invoking dependencies.
I like Wiremock’s answers to imitate the actual dependency, including the response time of the dependency. It will influence the statistics (e.g. thread waiting times) of the app under test. Wiremock, however, does not record the response time. I did not find any solution on the web, so I read through wiremock documentation for extensions and came with a solution. It may not be the best or the simplest, but so far it has worked out for me.
The solution has three steps.
- Capture timestamp when the request has been received by wiremock.
- Capture timestamp when the response has been received by wiremock, from the backend system.
- Register the difference as delay in wiremock stubs.
1. Capture timestamp when the request has been received by wiremock. Wiremock provides a RequestFilter to intercept incoming requests.
The CustomRequestFilter below intercepts the request and records the timestamp as a request header. This header will be used in further steps.
2. Capture timestamp when the response has been received by wiremock from the backend system.
After the response is received, wiremock runs ResponseTransformers on it. This CustomResponseTransformer below determines when the response was received. It then retrieves the start timestamp from the header added in Step 1. Then the transformer calculates the response time or delay and adds it as a header in the response.
3. Record the difference as delay in wiremock stubs.
Wiremock invokes StubMappingTransformer extensions, to modify StubMappings before they are saved. The CustomStubMappingTransformer below retrieves the delay from the response header added in Step 2. It then modifies the StubMapping to add the delay. The new StubMapping now has our desired request, response and also response time as a delay.
The 3 extensions previously created need to be registered with wiremock. Registration can be global or per-stub base. We have to register the delay only when proxying the request to a real backend. I was using the snapshotting method, therefore, extensions were registered only with the proxy stubs. If you use the new record feature, you could enable the extensions globally and add conditional logic inside the transformers.
Do contact me, if there is a simpler solution or if you would like to discuss.