REST endpoint stub in Java

Making a REST server

Let me remind you that earlier we talked about setting up a REST server for unit tests in JUnit. We will also be using the WireMock tool today.

Information about adding WireMock to the project can be found in the previous article.

Configuring server parameters

For HTTP:

WireMockServer server = new WireMockServer(options().port(80))

For HTTPS:

WireMockServer server = new WireMockServer(options().port(80).httpsPort(443).keystorePath("<key_store>.jks").keystorePassword("<keypass>").truststorePath("<trust_store>.jks").truststorePassword("trustpass"))

To use a self-signed certificate, you only need to specify keystorePath and keystorePassword. You can generate it 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

Let’s initialize the stub:

server.stubFor(post(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(…).

Checking requests at the endpoint

For GET:

server.verify(n, getRequestedFor(urlEqualTo("/endpoints/y")));

For POST:

server.verify(n, postRequestedFor(urlEqualTo("/endpoints/y")));

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 promark33@gmail.com.

If I saved your day, you can support me :)

Leave a Reply

Your email address will not be published.