Tuesday, 26 May 2020

WireMock: Proxying example

WireMock provides support for proxying. You can specify the proxy service to be called for specific endpoint.

 

For example, following snippet forward the request ("/api/v1/employees") to different server "http://localhost:8080"

 

wireMockRule.stubFor(post(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().proxiedFrom("http://localhost:8080")));

 

Let’s try this proxy one with an example.

 

Step 1: Download application from this link.


Import the project to IDE (Eclipse or any other).


Run App.java.

 

Open the url 'http://localhost:8080/swagger-ui.html' in browser, you will see swagger API documentation.

Hit GET /api/v1/employees to see all the employees information.

[
  {
    "id": 1,
    "firstName": "Deepak",
    "lastName": "Moud"
  },
  {
    "id": 2,
    "firstName": "Srinivasa Rao",
    "lastName": "Gumma"
  },
  {
    "id": 3,
    "firstName": "Purna Chandra",
    "lastName": "Rao"
  },
  {
    "id": 4,
    "firstName": "Madhavi Latha",
    "lastName": "Gumma"
  },
  {
    "id": 5,
    "firstName": "Raghava",
    "lastName": "Reddy"
  },
  {
    "id": 6,
    "firstName": "Ramesh Chandra",
    "lastName": "Dokku"
  }
]

Step 2: Let’s add new employee using WireMock stub.

@Test
public void createNewEmployee_selectiveProxying() {

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

  wireMockRule.stubFor(post(urlPathEqualTo("/api/v1/employees")).willReturn(aResponse().proxiedFrom("http://localhost:8080")));

  Employee newEmployee = empRestClient.addEmployee(emp);

  assertNotNull(newEmployee);

}

You can download complete test application from this link.


 

Run ‘createNewEmployee_selectiveProxying’ test case and hit the api "http://localhost:8080/api/v1/employees" in swagger again. You can observe that employee with id is added.

[
  {
    "id": 1,
    "firstName": "Deepak",
    "lastName": "Moud"
  },
  {
    "id": 2,
    "firstName": "Srinivasa Rao",
    "lastName": "Gumma"
  },
  {
    "id": 3,
    "firstName": "Purna Chandra",
    "lastName": "Rao"
  },
  {
    "id": 4,
    "firstName": "Madhavi Latha",
    "lastName": "Gumma"
  },
  {
    "id": 5,
    "firstName": "Raghava",
    "lastName": "Reddy"
  },
  {
    "id": 6,
    "firstName": "Ramesh Chandra",
    "lastName": "Dokku"
  },
  {
    "id": 7,
    "firstName": "Bala",
    "lastName": "Gurram"
  }
]




Previous                                                    Next                                                    Home

No comments:

Post a Comment