Extending Moco API to Support Delayed Responses for Mocking Slow Endpoints
This article explains how to extend the Moco mock server with custom delay handlers so that developers can simulate API responses that take longer than five seconds, including sample usage, wrapper methods, and the full implementation of a DelayHandler class in Java.
When using the Moco API for interface simulation, the author needed to mock an endpoint whose response time exceeds 5 seconds in order to observe how the client handles such latency.
Although Moco already provides a delay feature, it only works for asynchronous requests and cannot produce a delayed response for a normal request, so the author created an extension to add this capability.
Demo Usage
HttpServer server = getServer(8088)
server.get(urlOnly("/aba")).response(delay(textRes("faun"), 5000))
server.response("haha")
MocoServer drive = run(server)
waitForKey("fan")
drive.stop()Wrapper Methods
/**
* Delayed response
* @param handler
* @param time time in ms, cannot be lower than 50ms due to a known bug
*/
static ResponseHandler delay(ResponseHandler handler, int time) {
DelayHandler.newSeq(handler, time)
}
/**
* Delayed response with default 1000ms
* @param handler
*/
static ResponseHandler delay(ResponseHandler handler) {
DelayHandler.newSeq(handler, 1000)
}ResponseHandler Implementation (DelayHandler)
package com.fun.moco.support
import com.github.dreamhead.moco.ResponseHandler
import com.github.dreamhead.moco.handler.AbstractResponseHandler
import com.github.dreamhead.moco.internal.SessionContext
import java.util.concurrent.TimeUnit
import static com.google.common.base.Preconditions.checkArgument
/**
* Extension of ResponseHandler to add delayed response capability
*/
class DelayHandler extends AbstractResponseHandler {
/** delay time */
private final int time
private final ResponseHandler handler
private DelayHandler(ResponseHandler handler, int time) {
this.time = time
this.handler = handler
}
public static ResponseHandler newSeq(final ResponseHandler handler, int time) {
checkArgument(handler != null, "responsehandler cannot be null!")
return new DelayHandler(handler, time)
}
@Override
void writeToResponse(SessionContext context) {
com.github.dreamhead.moco.util.Idles.idle(time, TimeUnit.MILLISECONDS)
handler.writeToResponse(context)
}
}Disclaimer : This is the original “FunTester” article; redistribution is prohibited without permission. For collaborations, contact [email protected] .
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.