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
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>wiremock-example</groupId> <artifactId>wiremock-example</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock</artifactId> <version>2.24.1</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.1.1</version> <scope>test</scope> </dependency> </dependencies> </project>
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:
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.
{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } }
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:
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. ;)
import com.github.tomakehurst.wiremock.WireMockServer; import io.restassured.response.Response; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static io.restassured.RestAssured.given; public class WireMockJUnit5Test { WireMockServer wireMockServer; @BeforeEach public void setup () { wireMockServer = new WireMockServer(8090); wireMockServer.start(); setupStub(); } @AfterEach public void teardown () { wireMockServer.stop(); } public void setupStub() { wireMockServer.stubFor(get(urlEqualTo("/an/endpoint")) .willReturn(aResponse().withHeader("Content-Type", "text/plain") .withStatus(200) .withBodyFile("json/glossary.json"))); } @Test public void testStatusCodePositive() { given(). when(). get("http://localhost:8090/an/endpoint"). then(). assertThat().statusCode(200); } @Test public void testStatusCodeNegative() { given(). when(). get("http://localhost:8090/another/endpoint"). then(). assertThat().statusCode(404); } @Test public void testResponseContents() { Response response = given().when().get("http://localhost:8090/an/endpoint"); String title = response.jsonPath().get("glossary.title"); System.out.println(title); Assert.assertEquals("example glossary", title); } }
At begining, we need to declare a Wiremock instance with below line.
WireMockServer wireMockServer;
Then, we need to start the mock server on a specific port and set up the stub for each test.
@BeforeEach public void setup () { wireMockServer = new WireMockServer(8090); wireMockServer.start(); setupStub(); }
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.
public void setupStub() { wireMockServer.stubFor(get(urlEqualTo("/an/endpoint")) .willReturn(aResponse().withHeader("Content-Type", "text/plain") .withStatus(200) .withBodyFile("json/glossary.json"))); }
And at the end of each test, we should close the mock server.
@AfterEach public void teardown () { wireMockServer.stop(); }
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
public void setupStub() { configureFor("127.0.0.1", 8089); stubFor(get(urlEqualTo("/some/thing")) .withHeader("Accept", matching("text/plain")) .willReturn(aResponse(). withStatus(503). withHeader("Content-Type", "text/html"). withBody("Service Not Available")) ); stubFor(get(urlEqualTo("/some/thing")) .withHeader("Accept", matching("application/json")) .willReturn(aResponse(). withStatus(200). withHeader("Content-Type", "application/json") .withBody("{\"serviceStatus\": \"running\"}") .withFixedDelay(2500)) ); }
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

Onur Baskirt is a Software Engineering Leader with international experience in world-class companies. Now, he is a Software Engineering Lead at Emirates Airlines in Dubai.
wireMockServer.stubFor(get(urlEqualTo(“/an/endpoint”))
error: no suitable method found for get(UrlPattern)
wireMockServer.stubFor(get(urlEqualTo(“/an/endpoint”))
Below test should work, there is a get method which hits the /an/endpoint/ url pattern.
@Test
public void testResponseContents() {
Response response = given().when().get(“http://localhost:8090/an/endpoint”);
String title = response.jsonPath().get(“glossary.title”);
System.out.println(title);
Assert.assertEquals(“example glossary”, title);
}
didn’t write the main class
how program will run