MockServer is great for simulating external APIs
MockServer allows you to easily mock APIs from external systems. It has a lot of functionalities but I want to focus on how it can help you in testing your application, both during integration tests locally or on a running server doing end-to-end testing, and how you can configure MockServer for your needs.
Running in a Docker container
For end-to-end testing you can start a mock server through docker, you can deploy it in your infrastructure on test environments to help simulate external APIs.
When using a docker engine locally, you can do it by running:
$ docker run -d --rm -p 1080:1080 mockserver/mockserver:5.15.0
Configuring expectations can be done through requests to it:
$ curl -X PUT 'localhost:1080/mockserver/expectation' \
-d '{
"httpRequest": {
"method": "GET",
"path": "/users/1"
},
"httpResponse": {
"body": "{\"firstName\": \"foo\", \"lastName\": \"bar\"}"
}
}'
Hitting the API configured gives the wanted response:
$ curl localhost:1080/users/1
{"firstName": "foo", "lastName": "bar"}
More info on running with docker can be found in the documentation.
Integration tests when building
You can add the dependency for starting a MockServer inside a test. In this case, it will be in a gradle project with Junit5.
dependencies {
...
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
testImplementation 'org.mock-server:mockserver-junit-jupiter-no-dependencies:5.14.0'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
...
}
Configuring requests could be done like so:
private final ClientAndServer clientAndServer;
...
@Test
void testMethodAndPath() throws URISyntaxException, IOException, InterruptedException {
clientAndServer
.when(request()
.withMethod("GET")
.withPath("/users"))
.respond(response()
.withStatusCode(200)
.withBody("[{\"firstName\": \"foo\", \"lastName\": \"bar\"}]"));
...
}
Configuration
Expectations can be very descriptive, you can configure the HTTP method, the path that gets hit, specify the headers of the request, the body, and more.
Here are tests with a few examples on how to do it, you can also get the code on GitHub:
You can also set the response in various ways, check the documentation for more.
Conclusion
MockServer is a good tool to use when you want to simulate the behavior of external APIs and test how your application will respond, both for sunny day and rainy day scenarios.