WireMock integration for Spring-Boot- 1 min
WireMock is an awesome library for mocking HTTP endpoints in unit tests. However, it can be
quite cumbersome to integrate with Spring-Boot: when you manually manage the
WireMockServer from within the test,
there is hardly a chance to use its random base url during Bean creation. That often results in the weirdest stunts of
Spring context configuration in order to somehow inject the mock location. For example, your client under test might
RestTemplate and you decide to make it a mutable field in order to replace it in your test with an instance
that knows the WireMock’s location.
In a perfect world, you would not need to touch your existing context configuration for just injecting a mock. Consider
@MockBean annotation that allows to simply replace an already configured Bean with a mock. This works without a
hassle and involves no stunts like defining a new Bean with same type and
@Primary annotation or manually replacing
an injected instance using a setter.
This library works just like that: It sets up a WireMock server early enough, so that its base url can be injected into the Spring application properties, simply replacing an existing value.