lantunes / fixd

An HTTP Server Fixture for Testing HTTP Clients and mocking web services, and a Java Micro Web Framework
http://bigtesting.org/fixd
Apache License 2.0
41 stars 6 forks source link

Support Content Marshalling #7

Closed lantunes closed 10 years ago

lantunes commented 10 years ago

The server should support marshalling content to be returned in the response, and unmarshalling content received from the request.

The following test demonstrates marshalling:

server.marshal("application/json")
      .with(new JSONMarshaller());

server.handle(Method.GET, "/marshal")
      .with(200, "application/json", new SimplePojo("marshalledJSON"));

Response resp = new AsyncHttpClient()
                        .prepareGet("http://localhost:8080/marshal")
                        .execute().get();

assertEquals("{\"val\":\"marshalledJSON\"}", resp.getResponseBody().trim());

The following test demonstrates unmarshalling:

server.unmarshal("application/json")
      .with(new JSONUnmarshaller());

server.handle(Method.PUT, "/unmarshal", "application/json")
    .with(new HttpRequestHandler() {
         public void handle(HttpRequest request, HttpResponse response) {
            response.setStatusCode(200);
            response.setContentType("text/plain");
            SimplePojo entity = request.getBody(SimplePojo.class);
            response.setBody(entity != null ? entity.getVal() : "error");
         }
     });

Response resp = new AsyncHttpClient()
                        .preparePut("http://localhost:8080/unmarshal")
                        .setHeader("Content-Type", "application/json")
                        .setBody("{\"val\":\"unmarshalledJSON\"}")
                        .execute().get();
assertEquals("unmarshalledJSON", resp.getResponseBody().trim());

In both cases above, a Marshaller, or Unmarshaller, is associated with a content type. When the server encounters a content type, it will check if there are any marshallers or unmarshallers associated with the content type before processing the request or the response. Only one marshaller and unmarshaller can be associated with a given content type. Note that it does not matter whether the server marshal/unmarshal methods are called before or after the call to the server handle method, so long as they are called before a request is received.