Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaWireMock – Proxying with JUnit Test

WireMock – Proxying with JUnit Test

WireMock has the power to selectively proxy requests through to other hosts. This supports a proxy setup where requests are by default proxied to another service, but where specific stubs are configured these are returned in place of the remote service’s response. 

WireMock - Proxying with JUnit Test

 

Let’s say there are 2 services, ServiceA and ServiceB, out of which 1 is available (ServiceA) and another one (ServiceB) is still under development. Now, we want to configure our Wiremock instance in such a way that all the requests coming for ServiceA should be proxied to the actual ServiceA host and all the requests to ServiceB will be served from preconfigured Wiremock responses. Let’s understand the whole concept by the following example. In this article, we will explain how Proxying works in WireMock with JUnit Test.

Note: To perform Proxying with JSON please refer to this article: WireMock – Proxying 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(urlMatching("/article/.*"))
                .willReturn(aResponse().proxiedFrom("http://www.google.com/")));
    }

Then here we call the request in WireMock through OkHttpClient two times. Once for “http://www.google.com/article/12345” and once for “http://localhost:9090/article/12345“. And finally, we capture the response from both these requests and will match the response body. 

Request for “http://www.google.com/article/12345”:

Request request1 = new Request.Builder()
                .url("http://www.google.com/article/12345")
                .method("GET", null)
                .build();

Response response1 = client.newCall(request1).execute();

Request for “http://localhost:9090/article/12345”:

Request request2 = new Request.Builder()
                .url("http://localhost:9090/article/12345")
                .method("GET", null)
                .build();
                
Response response2 = client.newCall(request2).execute();

And now, assert the response body. 

assertEquals(response1.body().string(), response2.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 for "http://www.google.com/article/12345"
        Request request1 = new Request.Builder()
                .url("http://www.google.com/article/12345")
                .method("GET", null)
                .build();
        Response response1 = client.newCall(request1).execute();
  
        // Request for "http://localhost:9090/article/12345"
        Request request2 = new Request.Builder()
                .url("http://localhost:9090/article/12345")
                .method("GET", null)
                .build();
        Response response2 = client.newCall(request2).execute();
  
        // assert the response
        assertEquals(response1.body().string(), response2.body().string());
  
    }
  
    private void configStub() {
        configureFor("localhost", 9090);
        // create a stub
        stubFor(get(urlMatching("/article/.*"))
                .willReturn(aResponse().proxiedFrom("http://www.google.com/")));
    }
  
}


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

 

Now let’s make some changes to our unit test. Instead of “http://www.google.com/article/12345“, we are modifying it to “http://www.yahoo.com/article/12345“. And you can see this time our test case has failed. 

 

Some More Concepts to Know About WireMock Proxying with JUnit Test

1. Proxy Stub Mappings

Proxy responses are defined in exactly the same manner as stubs, meaning that the same request matching criteria can be used. And this is what we have demonstrated in the above example. The standard syntax for this is as follows in Java

stubFor(get(urlMatching("/other/service/.*"))
        .willReturn(aResponse().proxiedFrom("http://otherhost.com/approot")));

2. Remove Path Prefix

The prefix of a request path can be removed before proxying the request. The standard syntax for this is as follows in Java

stubFor(get(urlEqualTo("/other/service/doc/123"))
        .willReturn(aResponse()
            .proxiedFrom("http://otherhost.com/approot")
            .withProxyUrlPrefixToRemove("/other/service")));

3. Additional Headers

It is possible to configure the proxy to add headers before forwarding the request to the destination. The standard syntax for this is as follows in Java

// Inject user agent to trigger rendering of mobile version of website
stubFor(get(urlMatching(".*"))
        .willReturn(aResponse()
            .proxiedFrom("http://otherhost.com")
            .withAdditionalRequestHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone)"));

RELATED ARTICLES

Most Popular

Recent Comments