WireMock JUnit 5 and Rest-Assured tutorial consists of a small demo about Wiremock and JUnit 5. We can create mocks and stubs with standalone or without. In this article, we will not go with the standalone solution. Thus, we do not need to install WireMock standalone .jar file, did the required settings and start it before test execution. We will cover this another article. In this article, we will handle all the required operations in our project.

Firstly, you need to create a maven project and name it “wiremock-example“.

Modifying Maven Pom.xml

Creating Example JSon Payload

We use WireMock for mocking and stubbing, Rest-Assured for HTTP Client Test API, and JUnit 5 as a test runner framework. Below you can see our project structure:

wiremock junit 5

As you see the above screenshot, we have a glossary.json file. In that file, I hold my stub’s body as shown below. IT should be located under: resources -> __files -> json directory.

By the way, you can validate your JSON files on http://jsonpath.com/ website. In this article, we will check the title as an example. Its json path is shown below:

wiremock rest assured

Implement First Tests and Stubs

Secondly, we create a stub and run sample tests in below code. Don’t worry, I will explain the critical parts of the code. 😉

At begining, we need to declare a Wiremock instance with below line.

Then, we need to start the mock server on a specific port and set up the stub for each test.

We need to set up our stub as follows.

  • We need to declare an endpoint url.
  • You can define your content type.
  • Define your status.
  • And point your body as “json/glossary.json” which ve prepared before by using .withBodyFile method.

And at the end of each test, we should close the mock server.

Updated Part

Setting One Endpoint with Different Conditions

As an update, we added another example where we stub an endpoint for two condition:

  • Valid Request
  • Invalid Request

As you can see, in setupStub function configure an endpoint. We call the Endpoint as /some/thing. First stub will return 503 status code  and Service Not Available response when Header is set to “Accept:text/plain“.

The other stub will return a valid json body with Http 200 status when Header is set to “Accept:application/json“. We added a fixed delay for that response for a realistic simulation.

The rest of the stuff in the project code is Rest-Assured test methods. You can get more information about rest-assured here.

Project link: https://github.com/swtestacademy/junit5-wiremock-example

Thanks for reading.
Onur Baskirt