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.
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
Most helpful comment
Should be able to do this.