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

WireMock – Stubbing with JUnit Test

One of the most important features of WireMock is Stubbing. Stubbing is the core feature of WireMock and it has the ability to return canned HTTP responses for requests matching criteria. So in this article, we are going to see how Stubbing works with JUnit Test in WireMock.  JUnit framework is a Java framework that is widely used for testing. It supports the test to run by writing and testing along. JUnit framework was initially based on the SUnit framework which is used for Unit testing but then later it was updated with Java using Selenium WebDriver. JUnit is now used as a standard when we need to perform testing in Java.

Prerequisites:

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

1. Basic Stubbing with JUnit Test 

Standard Syntax:

@Test
public void stubbingWithJunit() {
    stubFor(get(urlEqualTo("put your url as per your requirement"))
            .willReturn(aResponse()
                .withHeader("Content-Type", "text/plain")
                .withBody("put your body here")));

    assertThat(testClient.get("/some/thing").statusCode(), is(200));
    assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}

Let’s understand the above code in detail with a  proper example project. We will use IntelliJ IDEA as the IDE and Maven as the build tool. 

Example Project

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

private void configStubForPostMethod() {
        configureFor("localhost", 9090);
        stubFor(post(urlEqualTo("/testuser"))
                .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/testuser")
                .method("POST", body)
                .build();
Response response = client.newCall(request).execute();

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/testuser")
                .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(urlEqualTo("/testuser"))
                .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. 

 

2. Setting the Response Status Message

In addition to the status code, the status message can optionally also be set.

Java




@Test
public void stubWithJunitstatusMessage() {
    stubFor(get(urlEqualTo("put your url as per your requirement"))
            .willReturn(aResponse()
                .withStatus(200)
                .withStatusMessage("put your status message here")
                .withHeader("Content-Type", "text/plain")));
}


3. Sending Response Headers

In addition to matching on request headers, it’s also possible to send response headers.

Java




@Test
public void stubWithJunitResponseHeader() {
    stubFor(get(urlEqualTo("put your url as per your requirement"))
            .willReturn(aResponse()
                .withStatus(200)
                .withHeader("Cache-Control", "no-cache"),
                .withHeader("Content-Type", "text/plain")));
}


4. Saving Stubs

Stub mappings that have been created can be persisted to the mappings directory by calling the following method 

WireMock.saveAllMappings

5. Editing Stubs

Existing stub mappings can be modified, provided they have been assigned an ID.

Java




// Original Stub
wireMockServer.stubFor(get(urlEqualTo("/edit-this"))
    .withId(id)
    .willReturn(aResponse()
        .withBody("Original")));
  
assertThat(testClient.get("/edit-this").content(), is("Original"));
  
// Editing Stub
wireMockServer.editStub(get(urlEqualTo("/edit-this"))
    .withId(id)
    .willReturn(aResponse()
        .withBody("Modified")));
  
assertThat(testClient.get("/edit-this").content(), is("Modified"));


6. Removing Stubs

Stub mappings can be removed/deleted via the Java API as follows.

Java




StubMapping stubMapping = stubFor(get(urlEqualTo("/delete-me"))
  .willReturn(aResponse().withStatus(200)));
  
// Do things with the stub
  
removeStub(stubMapping);


RELATED ARTICLES

Most Popular

Recent Comments