Tuesday 26 May 2020

WireMock: Simulate 5xx responses

In this post, I am going to explain how to simulate server errors like 500 using WireMock.

 

WireMock provides following methods to simuate 5xx errors.

a.   serverError(): Return server error 500.

b.   serviceUnavailable() : Return server error 503.

 

Example

@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_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);

}

If you want, you can explicitly set the response status code using withStatus method.

 

Example

@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);

}

You can download the complete working application from this link.





Previous                                                    Next                                                    Home

No comments:

Post a Comment