Skip to content
Related Articles

Related Articles

WireMock – Verifying with JUnit Test

Improve Article
Save Article
  • Last Updated : 31 Jul, 2022
Improve Article
Save Article

In Wiremock, Verification comes after stubbing and request matching. Verification is to check with the Wiremock server as to whether a given request was received by it or not. In Wiremock, at least until it is reset the WireMock server records all requests it receives in memory. And this makes it possible to verify that a request matching a specific pattern was received, and also to fetch the requests’ details. Let’s demonstrate an example to understand how Verifying works in WireMock with JUnit Test

Prerequisites:

Note: To perform Verifying with JSON please refer to this article: WireMock – Verifying with JSON Mappings

Step By Step Implementation 

Step 1: Refer to the article How to Create a Maven Project in IntelliJ IDEA and create a Maven project in IntelliJ IDEA. 

Step 2: Add the following dependencies in your pom.xml file.

<!-- Dependency for okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.2.2</version>
</dependency>

<!-- Dependency for Wiremock-->
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.27.2</version>
    <scope>test</scope>
</dependency>

<!-- Dependency for JUnit-->
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.13-rc-2</version>
   <scope>test</scope>
</dependency>

Below is the complete code for the pom.xml file.

XML




<?xml version="1.0" encoding="UTF-8"?>
         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>org.example</groupId>
    <artifactId>wiremock-with-junit</artifactId>
    <version>1.0-SNAPSHOT</version>
  
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
  
    <dependencies>
  
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.2.2</version>
        </dependency>
  
        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
            <version>2.27.2</version>
            <scope>test</scope>
        </dependency>
  
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-rc-2</version>
            <scope>test</scope>
        </dependency>      
  
    </dependencies>
  
</project>


Step 3: Now go to the src > test > java and create a test class named WiremockWithJunit. In this class, we are going to perform the Verifying with JUnit Test in WireMock. At first, we have to configure the stub something like this.

private void configStub() {

        configureFor(“localhost”, 9090);

        // create a stub

        stubFor(get(urlEqualTo(“/gfg/article1”)).willReturn(aResponse().withBody(“Welcome to GeeksforGeeks!!”)));

    }

Then call the request in WireMock through OkHttpClient.

OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:9090/gfg/article1")
                .method("GET", null)
                .build();
Response response = client.newCall(request).execute();

And now, assert the response. 

assertEquals("Welcome to GeeksforGeeks!!", response.body().string());

And finally, verify the request count from WireMock

verify(exactly(1), getRequestedFor(urlEqualTo("/gfg/article1")));

Below is the complete code for the WiremockWithJunit.java class.

Java




import com.github.tomakehurst.wiremock.junit.WireMockRule;
import okhttp3.*;
import org.junit.Rule;
import org.junit.Test;
  
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.Assert.assertEquals;
  
public class WiremockWithJunit {
  
    @Rule
    public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(9090));
  
    // WireMock with JUnit
    @Test
    public void wiremock_with_junit_test() throws Exception {
        // stub configuration
        configStub();
  
        // call request in WireMock through OkHttpClient
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:9090/gfg/article1")
                .method("GET", null)
                .build();
  
        Response response = client.newCall(request).execute();
  
        // assert the response
        assertEquals("Welcome to GeeksforGeeks!!", response.body().string());
  
        // verify request count from wiremock
        verify(exactly(1), getRequestedFor(urlEqualTo("/gfg/article1")));
    }
  
    private void configStub() {
        configureFor("localhost", 9090);
        // create a stub
        stubFor(get(urlEqualTo("/gfg/article1")).willReturn(aResponse().withBody("Welcome to GeeksforGeeks!!")));
    }
  
}


Now, let’s run our test. And in the below image you can see our test has been passed. 

 

Now lets change the verify statement 

verify(exactly(1), getRequestedFor(urlEqualTo("/gfg/article2")));

As you can see in the below image this time our test case has failed. 

 

So you can notice that in verification we are doing nothing but getting the count i.e.the number of times the request was sent to the Wiremock server. Similarly, you can play around with it and observe the response that is coming. Similarly, you can try and test the following URL in your Postman.

Some More Concepts Related to WireMock Verifying 

Filtering Events

WireMock provides an interesting feature that you can filter the events. The results can also be filtered to include only unmatched requests via a query parameter like the following 

List<ServeEvent> serveEvents = getAllServeEvents(ServeEventQuery.ALL_UNMATCHED);

Also, the results can be filtered to include only requests matching a specific stub ID:

List<ServeEvent> serveEvents =
  getAllServeEvents(ServeEventQuery.forStubMapping(StubId));

Criteria Queries

The request journal can also be queried, taking a request pattern as the filter criteria. Try the following request

List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/api/.*")));

Removing Items from the journal By ID

An individual journal event can be removed via the Java API:

removeServeEvent(id);

Resetting the Request Journal

The request log can be reset at any time. If you’re using either of the JUnit rules this will happen automatically at the start of every test case. However, you can do it yourself via a call to the following method

WireMock.resetAllRequests()

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!