mock-server / mockserver

MockServer enables easy mocking of any system you integrate with via HTTP or HTTPS with clients written in Java, JavaScript and Ruby. MockServer also includes a proxy that introspects all proxied traffic including encrypted SSL traffic and supports Port Forwarding, Web Proxying (i.e. HTTP proxy), HTTPS Tunneling Proxying (using HTTP CONNECT) and SOCKS Proxying (i.e. dynamic port forwarding).
http://mock-server.com
Apache License 2.0
4.57k stars 1.07k forks source link

Add support for user defined body matchers #481

Closed vadim-shb closed 5 years ago

vadim-shb commented 6 years ago

Let user define how to verify the body It could look like this:

MockServer.verify(
    request()
        .withBody(
            (String body) -> {
                log.info(body);
                String author = JsonPath.read(body, "$.store.book[0].author");
                assertEquals("J. K. Rowling", author);
            }
        ),
);
jamesdbloom commented 5 years ago

You can already achieve this using stream as follows:

final MockServerClient mockServerClient = new MockServerClient("localhost", 1080);
final List<HttpRequest> matchingRequests =
    Arrays.stream(mockServerClient
        .retrieveRecordedRequests(request()))
        .filter(httpRequest -> {
            final Body body = httpRequest.getBody();
            if (body instanceof StringBody) {
                return "J. K. Rowling".equals(JsonPath.read(((StringBody) body).getValue(), "$.store.book[0].author"));
            } else {
                return false;
            }
        })
        .collect(Collectors.toList());

Making this part of the client library is current beyond the scope of MockServer mainly because it would only be possible for the Java client library or would required complex logic implemented in each client library. The current design ethos is to put as much logic as possible server side so that is it easy to support numerous client libraries in multiple languages without excessive cost. Do this server side would be extremely challenging without a very complex solution like WebSockets or serialising and deserialising code from the client which is executed server side.