Integration Testing using Wiremock
Integration tests are essential to ensure that all the different components of your application work together as expected. WireMock is a library that allows you to easily create mock HTTP servers, which can be used to simulate the behavior of external services and APIs that your application depends on. Let us see an example of creating integration tests for a Spring Boot REST application using WireMock.
Step 1: Set Up Your Project
First, you need to create a Spring Boot project. You can do this by using the Spring Initializr or by creating a new project in your preferred IDE.
Next, you need to add the WireMock dependency to your project. If you’re using Maven, add the following to your pom.xml file:
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.27.2</version>
</dependency>
If you’re using Gradle, add the following to your build.gradle file:
dependencies {
testImplementation 'com.github.tomakehurst:wiremock:2.27.2'
}
Step 2: Create a Mock Server
To create a mock server using WireMock, you need to create a JUnit test class and annotate it with @RunWith(WireMockRunner.class)
. This will set up a mock server before each test and tear it down after each test. Here’s an example of a mock server that returns a static JSON response:
@RunWith(WireMockRunner.class)
public class MockServerTest {
@Test
public void testMockServer() throws Exception {
stubFor(get(urlEqualTo("/api/endpoint"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"message\": \"Hello, World!\"}")));
URL url = new URL("http://localhost:8080/api/endpoint");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
assertThat(connection.getResponseCode(), is(200));
assertThat(connection.getHeaderField("Content-Type"), is("application/json"));
assertThat(new BufferedReader(new InputStreamReader(connection.getInputStream()))
.lines().collect(Collectors.joining()), is("{\"message\": \"Hello, World!\"}"));
}
}
The stubFor
method sets up a stub for a GET request to the URL /api/endpoint
. The willReturn
method specifies the response that should be returned when the stub is matched. In this case, it returns a response with a status code of 200, a content type of "application/json", and a body of "{"message": "Hello, World!"}".
The URL
and HttpURLConnection
classes are used to send a GET request to the mock server. The assertions at the end of the test verify that the response code, content type, and body are correct.
Step 3: Use the Mock Server in Your Integration Tests
To use the mock server in your integration tests, you can set the base URL of your REST template to the URL of the mock server. Here’s an example:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testIntegration() throws Exception {
stubFor(get(urlEqualTo("/api/endpoint"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"message\": \"Hello, World!\"}")));
ResponseEntity<String> response = restTemplate.getForEntity("/api/endpoint", String.class);
assertThat(response.getStatusCode(), is(HttpStatus.OK));
assertThat(response.getHeaders().getContentType().toString(), is("application/json"));
assertThat(response.getBody(), is("{\"message\": \"Hello, World!\"}"));
}
}
In this example, the ‘TestRestTemplate’ is autowired into the test class, and a GET request is sent to the endpoint “/api/endpoint”. The ‘stubFor’ method is used to set up a stub for the same endpoint, and the response is verified using assertions.
Note that the ‘@SpringBootTest’ annotation is used with the ‘webEnvironment’ attribute set to ‘SpringBootTest.WebEnvironment.RANDOM_PORT’. This tells Spring Boot to start the application on a random port, which allows the mock server to run on port 8080 without conflicting with the application.
Step 4: Run Your Integration Tests
To run your integration tests, you can use your IDE’s test runner or run `mvn test` or `gradle test` from the command line. The WireMock server will be started before each test and shut down after each test.
Conclusion
In this blog post, we’ve covered how to create integration tests for a Spring Boot REST application using WireMock. By using a mock server to simulate the behavior of external services and APIs, you can test your application’s behavior in a controlled environment. This can help you identify and fix issues before they impact your users.
Additionally, WireMock allows you to test edge cases and error scenarios that may be difficult to reproduce in a real environment. For example, you can use WireMock to simulate slow responses, error responses, and even network failures.
In summary, WireMock is a powerful tool for creating mock servers and testing your Spring Boot REST application’s integration with external services and APIs. By creating integration tests with WireMock, you can ensure that your application is functioning correctly and handling all possible scenarios.
Thanks for your attention! Happy Learning!