Tuesday 26 May 2020

WireMock: Configure latency

Latency represents the amount of time taken to send information from one point to other. In case of http requests, latency is the summation of amount of time taken to send request from client to server plus amount of time taken to receive response from server to client.

 

Latency = time taken to send request from client to server + time taken to receive response from server to client.

 

Latency is measured in milliseconds (ms).


WireMock provides a way to simulate latency by providing below methods.

 

public ResponseDefinitionBuilder withFixedDelay(Integer milliseconds)

public ResponseDefinitionBuilder withRandomDelay(DelayDistribution distribution)

public ResponseDefinitionBuilder withUniformRandomDelay(int lowerMilliseconds, int upperMilliseconds)

public ResponseDefinitionBuilder withLogNormalRandomDelay(double medianMilliseconds, double sigma)

public ResponseDefinitionBuilder withChunkedDribbleDelay(int numberOfChunks, int totalDuration)

 

Example
@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);
}
If you are using Spring WebClient, you can specify timeouts using TcpClient.
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();

You can download the working application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment