REST endpoint stub in JUnit

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

We will be using the WireMock tool. The current version can be viewed in the MVN repository.

Connecting WireMock to the project

Maven

<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8</artifactId>
    <version>2.27.2</version>
    <scope>test</scope>
</dependency>

Gradle

testCompile "com.github.tomakehurst:wiremock-jre8:2.27.2"

Configuring server parameters

Before a unit test, we must with a rule.

For HTTP:

@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.

For HTTPS:

@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:

WireMock.stubFor(get(urlEqualTo("/endpoints/y")).willReturn(aResponse().withBody("Hello world!")))

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

For GET:

verify(n, getRequestedFor(urlEqualTo("/endpoints/y")))

For POST:

verify(n, postRequestedFor(urlEqualTo("/endpoints/y")))

Where n is the expected number of requests addressed to Y.

Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

One thought on “REST endpoint stub in JUnit

Leave a Reply

Your email address will not be published. Required fields are marked *