Pact-jvm: Automatically create a `PactDslJsonBody` from a Java object

Created on 21 May 2018  路  7Comments  路  Source: pact-foundation/pact-jvm

Currently, to define the body of a message within a Java consumer test, we have to do the following:

new PactDslJsonBody()
  .stringType("firstName", "Zaphod")
  .stringType("lastName", "Beeblebrox"))
  .toPact();

This is quite cumbersome, especially for large objects (which are not unusual).

Is there a way to automatically create a PactDslJsonBody from a given Java object?

If not, consider this a feature request :).

Implementing a mapper that does this seems easy enough, and I'd gladly give it a try.

enhancement

Most helpful comment

Should be able to do this.

All 7 comments

Should be able to do this.

@thombergs you could use the jackson's ObjectMapper to write a json string of your object? Then it's just

@Override
    protected RequestResponsePact createFragment(PactDslWithProvider builder) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("testreqheader", "testreqheadervalue");

        return builder
            .given("test state") // NOTE: Using provider states are optional, you can leave it out
            .uponReceiving("ExampleJavaConsumerPactTest test interaction")
                .path("/")
                .method("GET")
                .headers(headers)
            .willRespondWith()
                .status(200)
                .headers(headers)
                .body(body-from-object-mapper)

Yes, didn't think of this.

@oswaldquek Actually, just providing a JSON string doesn't suffice for our use case, since we want to use the "like" matchers (i.e. we don't want to match the exact JSON, but just that the types of the JSON fields are correct).

@thombergs yeah, true that. we're using the json pact (according to the pact specification https://github.com/pact-foundation/pact-specification/tree/version-3) directly: https://github.com/alphagov/pay-publicapi/pull/177. personally i'm not a huge fan of java dsls. that might help you.
we specify the pact files relevant for that test here: https://github.com/alphagov/pay-publicapi/blob/master/src/test/java/uk/gov/pay/api/it/DirectDebitPaymentTest.java#L69

We build a lib for that. It creates calls on PactDslJsonBody from a Java Bean. Matcher are used by default. But you can configure it very flexible.
@thombergs https://github.com/remondis-it/pact-consumer-builder :)

Closing this

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DerKnecht picture DerKnecht  路  10Comments

Jejuni picture Jejuni  路  4Comments

SchulteMarkus picture SchulteMarkus  路  5Comments

uglyog picture uglyog  路  4Comments

coding-yogi picture coding-yogi  路  5Comments