Open In App

WireMock – URL Matching with Regex

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

WireMock is a tool for mocking HTTP-based APIs that runs in the unit tests, on the desktop, or in the test environment. Read more about WireMock in the article Introduction to WireMock. In this article, we are going to discuss one of the important concepts in Wiremock, i.e how to match the URL with Regex. 

Regex Matching on the URL Path Only 

JSON Mapping

Syntax:

{
  "request": {
    "urlPathPattern": "/your/([a-z1-9]*)"
    ...
  },
  ...
}

Now let’s demonstrate this with the help of Postman. Open your Postman and send a POST request to the following URL:

http://localhost:8080/__admin/mappings

And the JSON request body is

Request Body:

{
    "request": {
        "urlPathPattern": "/gfg/([a-z1-9]*)",
        "method": "GET"
    },
    "response": {
        "status": 200,
        "body": "Welcome to GeeksforGeeks Portal!"
    }
}

Click on the Send button now and in the Response, you can see the following Response Body with the status code 201 Created.

Response Body:

{
    "id": "ed9fe262-2b79-4862-9889-39378d553a35",
    "request": {
        "urlPathPattern": "/gfg/([a-z1-9]*)",
        "method": "GET"
    },
    "response": {
        "status": 200,
        "body": "Welcome to GeeksforGeeks Portal!"
    },
    "uuid": "ed9fe262-2b79-4862-9889-39378d553a35"
}

Please refer to the below image if you are stuck somewhere

 

Now, let’s test our Stubbed API. Again open a new tab in Postman and send a GET request to the following URL

http://localhost:8080/gfg/user1345689

Note: You can put anything lies in a-z and 1-9 after /gfg/

And you are going to get the following response in the Response body.

Welcome to GeeksforGeeks Portal!

Please refer to the below image if you are stuck somewhere

 

Java 

Syntax:

urlPathMatching("/your/([a-z1-9]*)")

Now let’s demonstrate this with the help of IntelliJ IDEA as the IDE and Maven as the build tool. 

Example Project

Step 1: 

Refer to this 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. At first, we have to configure the stub something like this.

private void configStubForPostMethod() {
        configureFor("localhost", 9090);
        stubFor(post(urlPathMatching("/gfg/([a-z1-9]*)"))
                .willReturn(status(200)
                        .withBody("Welcome TestUser!")
                        .withHeader("content-type", "application/json")));
    }

The code is self-explanatory, so please refer to the code in-depth so you can understand the code easily. Now let’s create the Request Body:

RequestBody body = new FormBody.Builder()
                .add("username", "testuser")
                .build();

Then call the request in WireMock through OkHttpClient.

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

Note: Here in the URL you can put anything in the range of [a-z] and [1-9] after /gfg/.

And finally, assert the response, and you are done 

assertEquals("Welcome TestUser!", 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));
  
    // Stubbing with JUnit
    @Test
    public void stubbing_with_junit_test() throws Exception {
        // stub configuration
        configStubForPostMethod();
  
        // Create the Request Body
        RequestBody body = new FormBody.Builder()
                .add("username", "testuser")
                .build();
  
        // call request in WireMock through OkHttpClient
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:9090/gfg/testuser234125")
                .method("POST", body)
                .build();
        Response response = client.newCall(request).execute();
  
        // assert the response
        assertEquals("Welcome TestUser!", response.body().string());
    }
  
     private void configStubForPostMethod() {
        configureFor("localhost", 9090);
        stubFor(post(urlPathMatching("/gfg/([a-z1-9]*)"))
                .willReturn(status(200)
                        .withBody("Welcome TestUser!")
                        .withHeader("content-type", "application/json")));
    }
  
}


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

 

Similarly, you can also try the demonstration for the following Request Matching.

Regex Matching on URL Path and Query

JSON Mapping

Syntax:

{
  "request": {
    "urlPattern": "/your/([a-z1-9]*)\\?and=query"
    ...
  },
  ...
}

Java 

Syntax:

urlMatching("/your/([a-z]*)\\?and=query")


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

Similar Reads