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

Supplementary example for decoder, and hamcrest usecase #113

Closed havenqi closed 5 years ago

havenqi commented 5 years ago

In my situation, the http body is an xml String. In order to use the easier way provided by Groovy, I manipulated it successfully in Xml Node way to avert the complex xpath processing(with your support in issue109.

  1. The decoder part (looks tedious, welcome to suggest better way)
decoder('application/xml; charset=utf-8') { byte[] bytes, DecodingContext ctx ->
                    new XmlParser().parseText(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes), "utf-8")).readLine())
                }
  1. The expectation part, "Sndt" is one of the node name in the XML, the depth is not fixed.

body hasValue("Sndt","$_Sndt"), 'application/xml; charset=utf-8'

  1. A very simple Hamcrest method, which can be further refined to a more groovy style
def hasValue(String field, String value) {
        new TypeSafeMatcher() {
            @Override
            protected boolean matchesSafely(Object o) {
                if (o.'**'.find { node ->
                    node."$field".text() == value
                }) return true
                else return false
            }

            @Override
            void describeTo(Description description) {
                description.appendText("Expected Value:").appendValue(value)
            }
            @Override
            protected void describeMismatchSafely(Object o, Description mismatchDescription) {
                mismatchDescription.appendText("was ").appendValue(o.MsgHeader."$field".text())
            }
        }
    }

I believe more examples to decoder and hamcrest usage in common use cases(like XML, Json manipulation) can be helpful to new users.