Skip to content

WireMock Spring Boot drastically simplifies testing HTTP clients in Spring Boot & Junit 5 based integration tests.

License

Notifications You must be signed in to change notification settings

cheese8/wiremock-spring-boot

 
 

Repository files navigation

WireMock Spring Boot

WireMock Spring Boot library drastically simplifies WireMock configuration in a Spring Boot and JUnit 5 application.

🤩 Highlights

  • fully declarative WireMock setup
  • support for multiple WireMockServer instances - one per HTTP client as recommended in the WireMock documentation
  • automatically sets Spring environment properties
  • does not pollute Spring application context with extra beans

🤔 How to install

Add the dependency to wiremock-spring-boot:

<dependency>
    <groupId>com.maciejwalkowiak.spring</groupId>
    <artifactId>wiremock-spring-boot</artifactId>
    <version>2.1.2</version>
    <scope>test</scope>
</dependency>

✨ How to use

Use @EnableWireMock with @ConfigureWireMock with tests annotated that use SpringExtension, like @SpringBootTest:

@SpringBootTest
@EnableWireMock({
        @ConfigureWireMock(name = "user-service", property = "user-client.url")
})
class TodoControllerTests {

    @InjectWireMock("user-service")
    private WireMockServer wiremock;

    @Value("${user-client.url}")
    private String wiremockUrl; // injects the base URL of the WireMockServer instance

    @Test
    void aTest() {
        wiremock.stubFor(...);
    }
}
  • @EnableWireMock adds test context customizer and enables WireMockSpringExtension
  • @ConfigureWireMock creates a WireMockServer and passes the WireMockServer#baseUrl to a Spring environment property with a name given by property.
  • @InjectWireMock injects WireMockServer instance to a test

Note that WireMockServer instances are not added as beans to Spring application context to avoid polluting it with test-related infrastructure. Instead, instances are kept in a separate store associated with an application context.

Registering WireMock extensions

WireMock extensions can be registered independently with each @ConfigureWireMock:

@ConfigureWireMock(name = "...", property = "...", extensions = { ... })

Customizing mappings directory

By default, each WireMockServer is configured to load mapping files from a classpath directory wiremock/{server-name}/mappings.

It can be changed with setting stubLocation on @ConfigureWireMock:

@ConfigureWireMock(name = "...", property = "...", stubLocation = "my-stubs")

Sounds good? Consider ❤️ Sponsoring the project! Thank you!

🙏 Credits

I looked into and learned few concepts from following projects and resources during the development of this project:

About

WireMock Spring Boot drastically simplifies testing HTTP clients in Spring Boot & Junit 5 based integration tests.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 100.0%