How to Fix JSON Parameter Extraction in Moco API Mocking for POST Requests

This article explains why the default Moco example fails to extract JSON parameters from POST requests, walks through the source inspection that reveals the limitation, and provides a custom JsonExtractor implementation with Groovy helper methods to correctly match JSON payloads.

FunTester
FunTester
FunTester
How to Fix JSON Parameter Extraction in Moco API Mocking for POST Requests

When using Moco API for interface virtualization, the official example only works for GET query parameters and cannot handle POST requests with JSON bodies. The author discovered that the built‑in ParamRequestExtractor extracts values from request.getQueries(), which returns null for JSON payloads.

To solve this, a new extractor class is written. The JsonExtractor extends HttpRequestExtractor<String[]> and overrides doExtract(HttpRequest request). Inside the method, the request content is converted to a string, parsed with net.sf.json.JSONObject, and the desired field is retrieved via getString(param). The extracted value is wrapped in a String[] and returned using Guava's fromNullable. If parsing fails, an empty string array is returned.

public class JsonExtractor extends HttpRequestExtractor<String[]> {
    private final String param;
    public JsonExtractor(final String param) { this.param = param; }
    @Override
    protected Optional<String[]> doExtract(HttpRequest request) {
        try {
            String s = request.getContent().toString();
            String value = JSONObject.fromObject(s).getString(param);
            return fromNullable(new String[]{value});
        } catch (Exception e) {
            return fromNullable(new String[]{""});
        }
    }
    public static RequestExtractor<String[]> queryJson(final String param) {
        return new JsonExtractor(com.github.dreamhead.moco.util.Preconditions.checkNotNullOrEmpty(param, "参数不能为空!"));
    }
}

In Groovy test scripts, two matcher helpers are added. eqArgs(key, value) delegates to the existing eq(query(key), value) for GET parameters, while eqParams(key, value) uses the new queryJson extractor to compare JSON fields.

static RequestMatcher eqArgs(String key, String value) {
    eq query(key), value
}
static RequestMatcher eqParams(String key, String value) {
    eq queryJson(key), value
}

The author also notes two advantages of Groovy for such testing: seamless Java compatibility (most Java libraries work unchanged) and excellent IDE support, making it easy to write and run these custom matchers.

JavaBackend testingGroovyMoCoAPI mockingJSON extraction
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.