Tuesday 26 May 2020

WireMock: Simulating faults (Bad Responses)

WireMock provides Fault enum to simulate other type of errors.

 

Below table summarizes the enums provided by WireMock.

 

Enum Constant

Description

CONNECTION_RESET_BY_PEER

It causes a "Connection reset by peer" type error to be thrown by the client.

EMPTY_RESPONSE

Return a completely empty response.

MALFORMED_RESPONSE_CHUNK

Send an OK status header, then garbage, then close the connection.

RANDOM_DATA_THEN_CLOSE

Send garbage then close the connection.

 

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

}

You can download complete working application from this link.





Previous                                                    Next                                                    Home

No comments:

Post a Comment