Open In App

WireMock – Stub Priority with JUnit Test

Last Updated : 31 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In WireMock, Stub priority allows us to assign priorities for the request mappings. That means it’s a simple way to resolve which stub mapping should be given more precedence if a request matches 2 or more stub mappings. It is sometimes the case that you’ll want to declare two or more stub mappings that “overlap”, in that a given request would be a match for more than one of them. By default, WireMock will use the most recently added matching stub to satisfy the request. However, in some cases, it is useful to exert more control. The standard syntax is given below in Java code. Priority is set via the atPriority() in Java code.

// Catch-all case
// Priority: 5
stubFor(get(urlMatching("/api/.*")).atPriority(5)
    .willReturn(aResponse().withStatus(401)));

// Specific case
// Priority: 1 which is highest
stubFor(get(urlEqualTo("/api/specific-resource")).atPriority(1)
    .willReturn(aResponse()
            .withStatus(200)
            .withBody("Resource state")));

Let’s demonstrate an example to understand how Stub Priority works in WireMock with JUnit Test.

Prerequisites:

Note: To perform Stub Priority with JSON please refer to this article: WireMock – Stub Priority 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 Stub Priority with JUnit Test in WireMock. At first, we have to configure the stub something like this. Here, we will create 3 different stubbing with different endpoints and different priorities. 

private void configStub() {
        
  configureFor("localhost", 9090);

  // /gfg/endpoint1 with priority - 1 (Higher Priority)
  stubFor(get(urlEqualTo("/gfg/endpoint1"))
                .atPriority(1)
                .willReturn(ok()
                .withBody("Hello Endpoint 1")));


  // /gfg/endpoint2 with priority - 1 (Higher Priority)
  stubFor(get(urlEqualTo("/gfg/endpoint2"))
                .atPriority(1)
                .willReturn(ok()
                .withBody("Hello Endpoint 2")));

 // Generic mapping with priority - 5 (Lower Priority)
 stubFor(get(urlEqualTo("/gfg/.*"))
                .atPriority(5)
                .willReturn(notFound()
                .withBody("Not Found")));

}

Then call the request in WireMock through OkHttpClient.

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

And finally, assert the response, and you are done 

assertEquals("Hello Endpoint 1", response.body().string());

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 request = new Request.Builder()
                .url("http://localhost:9090/gfg/endpoint1")
                .method("GET", null)
                .build();
        Response response = client.newCall(request).execute();
  
        // assert the response
        assertEquals("Hello Endpoint 1", response.body().string());
  
    }
  
    // Stubbing with Priority
    private void configStub() {
  
        configureFor("localhost", 9090);
  
        // /gfg/endpoint1 with priority - 1 (Higher Priority)
        stubFor(get(urlEqualTo("/gfg/endpoint1"))
                .atPriority(1)
                .willReturn(ok()
                        .withBody("Hello Endpoint 1")));
  
  
        // /gfg/endpoint2 with priority - 1 (Higher Priority)
        stubFor(get(urlEqualTo("/gfg/endpoint2"))
                .atPriority(1)
                .willReturn(ok()
                        .withBody("Hello Endpoint 2")));
  
        // Generic mapping with priority - 5 (Lower Priority)
        stubFor(get(urlEqualTo("/gfg/.*"))
                .atPriority(5)
                .willReturn(notFound()
                        .withBody("Not Found")));
  
    }
  
}


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

 

Explanation

If you see closely endpoint1 and endpoint2 are also coming under the generic mapping (/gfg/.*) but though these endpoints have the priority: 1 so they are returning the corresponding response. But endpoint5 is a generic mapping so it’s returning the generic response. You can change the code and test for these endpoints. 

Conclusion

Stub Priority can also be used to define a default response in Wiremock for all the endpoints that are not having any stubs. If not configured, Wiremock will return its generic response like “No matching stubs found” etc., but stub priority allows you to configure that by creating a catch-all kind of stub with a lower priority value.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads