Search code examples
javaconsumerpact

Pact body matching - match number of nodes


I try to achieve the following:

I want to verify that a specific node in body ("entry") has between a minimum and a maximum number of direct subnodes called "content" (1 to 10 nodes). I don't care about what is in these subnodes, which value they have or how many subnodes they have.

Since I'm new to pact and don't really know how to match something like this I hope someone can help me. Thanks in advance.


Edit1:

I use a node matcher one of my collegues built like following:

return builder.given("given").uponReceiving("description").path(SERVICEPATH)
                .query(query).method(METHOD_GET).headers(ACCEPT, REQ_ACCEPT).willRespondWith().status(200)
                .matchHeader(HEADER_CONTENT_TYPE, RESP_HEADER_CONTENT_TYPE_REGEX).body(responseBody)
                .matchBody(new PactDslXmlNodeMatcher().node("entry").node("content").value(".*")).toPact();

Don't let that irritate you, that .matchBody just converts that node to the typical $. + path + '[#text]'-notation, where .value adds an regex-matcher rule to body matchers.

I also had a look at: https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-consumer-junit where maxArrayLike / minArrayLike looks promising, but I don't know how I can apply this to my case.


Edit2:

Now I have a very cool PactDslWithProvider as following:

    return builder.given("Genereller Test").uponReceiving("Feed soll Eintraege enthalten").path(SERVICEPATH)
            .query(query).method(METHOD_GET).headers(ACCEPT, REQ_ACCEPT).willRespondWith().status(200)
            .matchHeader(HEADER_CONTENT_TYPE, RESP_HEADER_CONTENT_TYPE_REGEX)
            .body(responseBody)
            .matchBody(new PactDslXmlNodeMatcher().node("feed").minMaxType(minNumberNodesInFeed, maxNumberNodesInFeed))
            .toPact();

The method "minMaxType" adds a MinMaxTypeMatcher to the body-category with the path of the node. The actual behaviour of this: It matches type, min and max of the most inner nodes of $.feed. Like: $.feed.0.title, $.feed.1.link, ..., $.feed.6.entry.0.title

But what I actually want is to verify that $.feed has a min and a max number of subnodes. How can I achieve that?


Solution

  • It sounds like you're trying to use Pact to do a functional test, rather than a contract test. Generally speaking, you shouldn't be writing tests that care about how many items there are in an array. Have a read of these two links and let me know how you go.

    Also, join us on slack.pact.io if you haven't already.