Suppose you want to test method X. It requests data from a specific endpoint Y.
In this article, we’ll talk about three things:
- how to start a REST server within a unit test;
- how to set up data transmission on Y;
- how to check the number of requests received on Y.
For information on how to do all the same in pure Java code, read this article.
Start a REST server
Connecting WireMock to the project
<dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock-jre8</artifactId> <version>2.27.2</version> <scope>test</scope> </dependency>
Configuring server parameters
Before a unit test, we must with a rule.
@Rule public WireMockRule wireMockRule = new WireMockRule(options().port(80), true)
Suppose the X method accessed the Z (Z != Y) endpoint. The test will fail if true is passed to the WireMockRule constructor.
@Rule public WireMockRule wireMockRule = new WireMockRule(options().port(80).httpsPort(443), true)
To use a self-signed certificate, you only need to specify keystorePath and keystorePassword. You can generate keystone like this:
keytool -genkey -alias wiremock -keyalg RSA -keysize 1024 -validity 365 -keypass password -keystore identity.jks -storepass password
Please note: keypass and storepass must be the same.
Making the endpoint
In the test itself or in the @Before block, we initialize the stub:
You can also make the POST endpoint. You just need to pass the method of the same name as an argument to stubFor(…), instead of get(…).
aResponse().withBody(…) supports messages of type String and byte. Besides them, json can be used as a response. To do this, you need to pass the okJson(…) method as the argument for willReturn(…).
Checking requests at the endpoint
Where n is the expected number of requests addressed to Y.
If you still have any questions, feel free to ask me in the comments under this article, or write me on email@example.com.