Saturday 30 May 2020

WireMock, springboot integration

In this post, I am going to show how to test spring boot application using wiremock.

 

We are going to develop an Employee Rest Client, which is going to talk to Employee Rest Service to perform CRUD operations.

Employee Rest Service provide following APIs to perform CRUD operations against employee entities.

API

Method

Description

api/v1/employees

GET

Get all the Employees

api/v1/employees/{id}

GET

Get employee by id

api/v1/employees/by-name/?empName={name}

GET

Get all the employees that contain this name.

api/v1/employees

POST

Create new employee

api/v1/employees/{id}

PUT

Update Employee by id

api/v1/employees/{id}

DELETE

Delete Employee by id

 

But here the problem is ‘Employee Rest Service’ is not yet ready and take 2 more months to deliver. But one good thing here is that the contract is ready (mean the payload structure and response format of these APIs).

 

Based on the contract we developed the client application. But still ‘Employee Rest Service’ is not available. How can we test the client application now? This is where WireMock comes to rescues us. You can mock the APIs using WireMock and test your client application. Once WireMock setup is done, you can call WireMock service instead of Employee Rest Service application.

 

Dependencies used

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-contract-wiremock</artifactId>
      <version>2.2.2.RELEASE</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

Developing Employee Rest client

Step 1: Create new maven project ‘springboot-wiremock-integration’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  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>com.sample.app</groupId>
  <artifactId>springboot-wiremock-integration</artifactId>
  <version>1</version>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>


  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-contract-wiremock</artifactId>
      <version>2.2.2.RELEASE</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>
</project>

Step 3: Create package ‘com.sample.app.model’ and define Employee class.

 

Employee.java

package package com.sample.app.model;

public class Employee {

  private int id;
  private String firstName;
  private String lastName;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
  }

};

Step 4: Create package ‘com.sample.app.exception’ and define EmployeeApiException like below.

 

EmployeeApiException.java

package com.sample.app.exception;

public class EmployeeApiException extends RuntimeException {

  private static final long serialVersionUID = 119874212393098L;

  public EmployeeApiException(String msg) {
    super(msg);
  }

}

Step 5: Create package ‘com.sample.app.service’ and define EmployeeService interface like below.

 

EmployeeService.java

package com.sample.app.service;

import java.util.List;

import com.sample.app.model.Employee;

public interface EmployeeService {

  public List<Employee> emps();

  public Employee byId(int id);

  public List<Employee> containsName(String name);

  public Employee addEmployee(Employee emp);

  public Employee updateEmployee(int id, Employee emp);

  public Employee deleteEmployee(int id);

}

Step 6: Create package ‘com.sample.app.service.impl’ and define EmployeeRestClient like below.

 

EmployeeRestClient.java

package com.sample.app.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.util.UriComponentsBuilder;

import com.sample.app.exception.EmployeeApiException;
import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

@Service
public class EmployeeRestClient implements EmployeeService {

  @Autowired
  private WebClient webClient;

  @Override
  public List<Employee> emps() {

    return webClient.get().uri("api/v1/employees").retrieve().bodyToFlux(Employee.class).collectList().block();
  }

  @Override
  public Employee byId(int id) {
    try {
      return webClient.get().uri("api/v1/employees/" + id).retrieve().bodyToMono(Employee.class).block();
    } catch (WebClientResponseException e) {
      throw new EmployeeApiException(e.getMessage() + "," + e.getRawStatusCode());
    } catch (Exception e) {
      throw new EmployeeApiException(e.getMessage());
    }

  }

  @Override
  public List<Employee> containsName(String name) {
    String uriToHit = UriComponentsBuilder.fromUriString("api/v1/employees/by-name/").queryParam("empName", name)
        .buildAndExpand().toString();

    return webClient.get().uri(uriToHit).retrieve().bodyToFlux(Employee.class).collectList().block();
  }

  @Override
  public Employee addEmployee(Employee emp) {
    return webClient.post().uri("api/v1/employees").syncBody(emp).retrieve().bodyToMono(Employee.class).block();
  }

  @Override
  public Employee updateEmployee(int id, Employee emp) {
    return webClient.put().uri("api/v1/employees/" + id).syncBody(emp).retrieve().bodyToMono(Employee.class)
        .block();
  }

  @Override
  public Employee deleteEmployee(int id) {
    return webClient.delete().uri("api/v1/employees/" + id).retrieve().bodyToMono(Employee.class).block();
  }

}

Step 7: Create package ‘com.sample.app.config’ and define AppConfig like below.

 

AppConfig.java

package com.sample.app.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.TcpClient;

@Configuration
public class AppConfig {

  @Value("${server.baseuri}")
  private String baseURI;

  @Bean
  public WebClient webClient() {
    TcpClient tcpClient = TcpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
        .doOnConnected(conn -> {
          conn.addHandlerLast(new ReadTimeoutHandler(3)).addHandlerLast(new WriteTimeoutHandler(3));
        });

    WebClient webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))).baseUrl(baseURI).build();

    return webClient;
  }

}

Step 8: Define App class.

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

  public static void main(String args[]) {
    SpringApplication.run(App.class, args);
  }

}

Developing test cases using WireMock

Step 1: Create a package ‘com.sample.app.service’ under src/test/java and define EmployeeRestClientTest.java.

 

@RunWith(SpringRunner.class)

@SpringBootTest

@TestPropertySource(properties = { "server.baseuri=http://localhost:8888" })

public class EmployeeRestClientTest {

         ……

         ……

}

 

As you see the test class, I set the property server.baseuri to http://localhost:8888 (See AppConfig class for more details).

 

Step 2: Inject EmployeeRestClient via autowiring.

@Autowired

private EmployeeRestClient empRestClient;

 

Step 3: Create an instance of WireMockRule.

 

@Rule

public WireMockRule wireMockRule = new WireMockRule(WireMockConfiguration.options().port(8888).httpsPort(9999)

.notifier(new ConsoleNotifier(true)).extensions(new ResponseTemplateTransformer(true)));

 

Now you can create stubs using WireMockRule instance.

 

wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(Json.write(ALL_EMPLOYEES))));

 

Since I am also using Response templates, you need to create a folder __files in src/test/resources folder.

 

Create following json files in src/test/resources/__files folder.

 

404.json

{

  "timeStamp": "{{now}}",

  "uri": "{{request.path}}",

  "message": "Requested resource not found",

  "errorCode": 404

}

 

allEmployees.json

[

  {

    "id": 1,

    "firstName": "Ram",

    "lastName": "Ponnam"

  },

  {

    "id": 2,

    "firstName": "Lakshman",

    "lastName": "Gurram"

  }

]

 

employeeByIdTemplate.json

{

  "id": "{{request.path.[3]}}",

  "firstName": "Ram",

  "lastName": "Ponnam"

}

 

newEmployeeTemplate.json

{

  "id": "{{randomValue length=2 type='NUMERIC'}}",

  "firstName": "{{jsonPath request.body '$.firstName'}}",

  "lastName": "{{jsonPath request.body '$.lastName'}}"

}

 

queryNameTemplate.json

[

  {

    "id": 1,

    "firstName": "{{request.query.empName}}",

    "lastName": "Ponnam"

  },

  {

    "id": 2,

    "firstName": "Lakshman",

    "lastName": "{{request.query.empName}}"

  }

]

 

updateEmployeeTemplate.json

{

  "id": "{{request.path.[3]}}",

  "firstName": "{{jsonPath request.body '$.firstName'}}",

  "lastName": "{{jsonPath request.body '$.lastName'}}"

}

 

Complete Test class is given below.

 

EmployeeRestClientTest.java

package com.sample.app.service;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.delete;
import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.exactly;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.serverError;
import static com.github.tomakehurst.wiremock.client.WireMock.serviceUnavailable;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

import com.github.tomakehurst.wiremock.common.ConsoleNotifier;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.sample.app.exception.EmployeeApiException;
import com.sample.app.model.Employee;
import com.sample.app.service.impl.EmployeeRestClient;

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "server.baseuri=http://localhost:8888" })
public class EmployeeRestClientTest {
  @Autowired
  private EmployeeRestClient empRestClient;

  private List<Employee> ALL_EMPLOYEES = new ArrayList<>();

  private static int idCounter = 1;

  private static Employee buildEmployee(String firstName, String lastName) {
    Employee emp = new Employee();
    emp.setId(idCounter);
    emp.setFirstName(firstName);
    emp.setLastName(lastName);

    idCounter++;

    return emp;
  }

  @Before
  public void initializeEmployees() {
    Employee emp1 = buildEmployee("Deepak", "Moud");
    Employee emp2 = buildEmployee("Srinivasa Rao", "Gumma");
    Employee emp3 = buildEmployee("Purna Chandra", "Rao");
    Employee emp4 = buildEmployee("Madhavi Latha", "Gumma");
    Employee emp5 = buildEmployee("Raghava", "Reddy");
    Employee emp6 = buildEmployee("Ramesh Chandra", "Dokku");

    ALL_EMPLOYEES.addAll(Arrays.asList(emp1, emp2, emp3, emp4, emp5, emp6));

  }

  @Rule
  public WireMockRule wireMockRule = new WireMockRule(WireMockConfiguration.options().port(8888).httpsPort(9999)
      .notifier(new ConsoleNotifier(true)).extensions(new ResponseTemplateTransformer(true)));

  @Test
  public void allEmployeeForAnyURL() {

    wireMockRule.stubFor(get(anyUrl()).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBody(Json.write(ALL_EMPLOYEES))));

    List<Employee> resultFromService = empRestClient.emps();

    assertEquals(resultFromService.size(), 6);

  }

  @Test
  public void allEmployeeForEactURLPath() {

    wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBody(Json.write(ALL_EMPLOYEES))));

    List<Employee> resultFromService = empRestClient.emps();

    assertEquals(resultFromService.size(), 6);
    verify(exactly(1), getRequestedFor(urlPathEqualTo("/api/v1/employees")));
  }

  @Test
  public void getEmployeeById() {

    Employee emp = new Employee();
    emp.setId(Integer.MAX_VALUE);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/[1-5]")).willReturn(
        aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(Json.write(emp))));

    for (int i = 1; i < 6; i++) {

      Employee resultEmp = empRestClient.byId(1);

      assertNotNull(resultEmp);
      assertEquals(Integer.MAX_VALUE, resultEmp.getId());
      assertEquals("Chamu", resultEmp.getFirstName());
      assertEquals("Gurram", resultEmp.getLastName());

    }

  }

  @Test
  public void allEmployeeFromFile() {

    wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBodyFile("allEmployees.json")));

    List<Employee> resultFromService = empRestClient.emps();

    assertEquals(resultFromService.size(), 2);

    Employee emp = resultFromService.get(0);

    if (emp.getId() == 1) {
      assertEquals("Ram", emp.getFirstName());
      assertEquals("Ponnam", emp.getLastName());
    } else if (emp.getId() == 2) {
      assertEquals("Lakshman", emp.getFirstName());
      assertEquals("Gurram", emp.getLastName());
    }

    verify(exactly(1), getRequestedFor(urlPathEqualTo("/api/v1/employees")));
  }

  @Test
  public void getEmployeeByIdUsingResponseTemplate() {

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/3")).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBodyFile("employeeByIdTemplate.json")));

    Employee resultEmp = empRestClient.byId(3);

    assertNotNull(resultEmp);
    assertEquals(3, resultEmp.getId());
    assertEquals("Ram", resultEmp.getFirstName());
    assertEquals("Ponnam", resultEmp.getLastName());

    verify(exactly(1), getRequestedFor(urlPathMatching("/api/v1/employees/3")));

  }

  @Test(expected = EmployeeApiException.class)
  public void getEmployeeByIdNotFound() {

    int empId = 12345;

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/" + empId))
        .willReturn(aResponse().withStatus(404).withHeader("Content-Type", "application/json")));

    empRestClient.byId(12345);

    verify(exactly(1), getRequestedFor(urlPathMatching("/api/v1/employees/" + empId)));

  }

  @Test(expected = EmployeeApiException.class)
  public void getEmployeeByIdNotFoundReturnErrorPayloadFromFile() {

    int empId = 12345;

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/" + empId)).willReturn(
        aResponse().withStatus(404).withHeader("Content-Type", "application/json").withBodyFile("404.json")));

    empRestClient.byId(12345);

    verify(exactly(1), getRequestedFor(urlPathMatching("/api/v1/employees/" + empId)));

  }

  @Test
  public void getEmployeesContainsNameViaQueryParam() {
    List<Employee> employeesContainNameGurram = new ArrayList<>();

    employeesContainNameGurram.add(buildEmployee("Bala Krishna", "Gurram"));
    employeesContainNameGurram.add(buildEmployee("Gurram", "Srinu"));

    String nameSubStr = "Gurram";

    wireMockRule.stubFor(
        get(urlPathEqualTo("/api/v1/employees/by-name/")).withQueryParam("empName", equalTo(nameSubStr))
            .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")
                .withBody(Json.write(employeesContainNameGurram))));

    List<Employee> resultFromService = empRestClient.containsName(nameSubStr);

    assertEquals(resultFromService.size(), 2);

  }

  @Test
  public void getEmployeesContainsNameViaResponseTemplate() {
    String nameSubStr = "Kumar";

    wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/employees/by-name/"))
        .withQueryParam("empName", equalTo(nameSubStr)).willReturn(aResponse().withStatus(200)
            .withHeader("Content-Type", "application/json").withBodyFile("queryNameTemplate.json")));

    List<Employee> emps = empRestClient.containsName(nameSubStr);

    assertEquals(emps.size(), 2);

    for (Employee emp : emps) {
      if (emp.getId() == 1) {
        assertEquals("Kumar", emp.getFirstName());
        assertEquals("Ponnam", emp.getLastName());
      } else if (emp.getId() == 2) {
        assertEquals("Lakshman", emp.getFirstName());
        assertEquals("Kumar", emp.getLastName());
      }

    }

  }

  @Test
  public void createNewEmployee() {

    Employee emp = new Employee();
    emp.setId(123);
    emp.setFirstName("Bala");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(post(urlPathEqualTo("/api/v1/employees")).willReturn(
        aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(Json.write(emp))));

    Employee newEmployee = empRestClient.addEmployee(emp);

    assertEquals(newEmployee.getId(), 123);
    assertEquals(newEmployee.getFirstName(), "Bala");
    assertEquals(newEmployee.getLastName(), "Gurram");

    verify(exactly(1), postRequestedFor(urlPathEqualTo("/api/v1/employees")));

  }

  @Test
  public void createNewEmployeeViaResponseTemplate() {

    wireMockRule.stubFor(post(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBodyFile("newEmployeeTemplate.json")));

    Employee empPayLoad = new Employee();
    empPayLoad.setFirstName("Bala");
    empPayLoad.setLastName("Gurram");

    Employee newEmployee = empRestClient.addEmployee(empPayLoad);

    assertEquals(newEmployee.getFirstName(), "Bala");
    assertEquals(newEmployee.getLastName(), "Gurram");

    verify(exactly(1), postRequestedFor(urlPathEqualTo("/api/v1/employees")));

  }

  @Test
  public void updateEmployee() {

    int empId = 123;

    wireMockRule.stubFor(put(urlPathEqualTo("/api/v1/employees/" + empId)).willReturn(aResponse().withStatus(200)
        .withHeader("Content-Type", "application/json").withBodyFile("updateEmployeeTemplate.json")));

    Employee emp = new Employee();
    emp.setFirstName("Bala");
    emp.setLastName("Gurram");

    Employee newEmployee = empRestClient.updateEmployee(empId, emp);

    assertEquals(newEmployee.getId(), 123);
    assertEquals(newEmployee.getFirstName(), "Bala");
    assertEquals(newEmployee.getLastName(), "Gurram");

    verify(exactly(1), putRequestedFor(urlPathEqualTo("/api/v1/employees/" + empId)));
  }

  @Test
  public void deleteEmployee() {

    int empId = 123;

    Employee emp = new Employee();
    emp.setId(empId);
    emp.setFirstName("Bala");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(delete(urlPathEqualTo("/api/v1/employees/" + empId)).willReturn(
        aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(Json.write(emp))));

    Employee deletedEmployee = empRestClient.deleteEmployee(empId);

    assertEquals(deletedEmployee.getId(), 123);
    assertEquals(deletedEmployee.getFirstName(), "Bala");
    assertEquals(deletedEmployee.getLastName(), "Gurram");

    verify(exactly(1), deleteRequestedFor(urlPathEqualTo("/api/v1/employees/" + empId)));

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_500() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1")).willReturn(serverError()));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_serverError_500() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1")).willReturn(serverError().withStatus(500)));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_serviceUnavailableError_503() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1")).willReturn(serviceUnavailable()));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_fault_emptyResponse() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(
        get(urlPathMatching("/api/v1/employees/1")).willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_fault_connectionResetByPeer() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1"))
        .willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_fault_malformedResponseChunk() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1"))
        .willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK)));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void simulate_fault_randomDataThenClose() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1"))
        .willReturn(aResponse().withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

    empRestClient.byId(1);

  }

  @Test(expected = EmployeeApiException.class)
  public void injectFixedDelay() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(get(urlPathMatching("/api/v1/employees/1")).willReturn(aResponse().withFixedDelay(9000)));

    empRestClient.byId(1);
  }

  @Test(expected = EmployeeApiException.class)
  public void injectUniformRandomDelay() {

    Employee emp = new Employee();
    emp.setId(1);
    emp.setFirstName("Chamu");
    emp.setLastName("Gurram");

    wireMockRule.stubFor(
        get(urlPathMatching("/api/v1/employees/1")).willReturn(aResponse().withUniformRandomDelay(6000, 9000)));

    empRestClient.byId(1);
  }

}

Total project structure looks like below.


Run EmployeeRestClientTest.java to run test cases.

 

You can download the complete working application from below link.

https://github.com/harikrishna553/wiremock/tree/master/springboot-wiremock-integration





Previous                                                    Next                                                    Home

No comments:

Post a Comment