cjstehno / ersatz

🤖 A simulated HTTP server for testing client code with configurable responses.
https://cjstehno.github.io/ersatz
Apache License 2.0
47 stars 5 forks source link

Simple Post Request failing. Content doesn't match #100

Closed hamza3202 closed 6 years ago

hamza3202 commented 6 years ago

This simple spec is failing for me.

       setup: "Setup mock server"
       ErsatzServer ersatz = new ErsatzServer({
            autoStart(true)
        })
        ersatz.expectations {
            post('/testPost/') { // <1>
                called(1) // <2>
                body([first:'John', last:'Doe'] as JSON, ContentType.APPLICATION_JSON)
                responder {
                    encoder(ContentType.APPLICATION_JSON, Map, Encoders.json) // <1>
                    code(200) // <3>
                    content([
                            message: "okay"
                    ], ContentType.APPLICATION_JSON) // <2>
                }
            }
        }
        expect: "request is successful"
        HTTPBuilder http = new HTTPBuilder(ersatz.httpUrl + "/testPost/")
        http.request(Method.POST, groovyx.net.http.ContentType.JSON) {
            body = [first:'John', last:'Doe']
        }

The output is

http POST /testPost/ ? 
Headers:
 - Accept: [application/json, application/javascript, text/javascript]
 - Connection: [Keep-Alive]
 - Content-Length: [29]
 - Content-Type: [application/json]
 - Host: [localhost:33874]
Character-Encoding: ISO-8859-1
Content-type: application/json
Content-Length: 29
Content:
  {"first":"John","last":"Doe"}

# Expectations

Expectation 0 (4 matchers):
  ✓ HTTP method matches <POST>
  ✓ Path matches "/testPost/"
  ✓ Header Content-Type matches A collection matching a string starting with "application/json"
  X Body (application/json) matches <{"first":"John","last":"Doe"}>
  (4 matchers: 3 matched, 1 failed)
cjstehno commented 6 years ago

Take a look at the encoder docs (http://stehno.com/ersatz/asciidoc/html5/#_encoders) - you are encoding a map but using Json in the body content of the expectation.

I can't test this now, but I suspect if you remove the 'as JSON' it will work. Please let me know either way.

Also, considering I work on HttpBuilder-NG I have to recommend you look at it (https://http-builder-ng.github.io/http-builder-ng/) as a replacement to the old unmaintained version.

hamza3202 commented 6 years ago

Thanks for the suggestion. I added decoder(ContentType.APPLICATION_JSON, Decoders.parseJson) and it worked. I got this from one of the test cases that you had written.