2

How to generate dynamic PactDslJsonBody using json value? Is it possible Pact team can provide the auto builder to assign body dynamically?

Pact Body:

body(new PactDslJsonBody()
                .object("testsuite") 
                .stringType("webId","24255")  
                .closeObject());        

Assert Response:

"{\"testsuite\":{\"webId\":\"24255\"}}";

Based on Assert Response(as input) and create the dslbody like

String json = "{\"testsuite\":{\"webId\":\"24255\"}}"

//body(json);
body(generatePactDSLJsonBody(json));        

Assert Response:

assertEqual("{\"testsuite\":{\"webId\":\"24255\"}}",json);

I know in body we can provide json itself. but i need to generate the PactDSLJson body using Json.

J_A_X
  • 12,857
  • 1
  • 25
  • 31
Nandess
  • 25
  • 1
  • 10

2 Answers2

2

It is technically possible to auto-generate the DSL classes from a JSON document, but I do not see the benefit of your example. Most of the time the matchers are defined based on the semantics of the JSON payload, not the syntax.

For example, from your sample JSON, it would see the webId attribute as a string, and generate a string type matcher. However, it is clearly a number, not a string.

The auto-generated DSL body would accept the following JSON:

{"testsuite":{"webId":"This is not a web ID &^*&^%"}}

However, an auto-generation tool used to create a skeleton consumer test from a JSON document which could then be changed based on the semantics of the JSON would be really useful.

2

We build a library to generate the PactDslJsonBody from a Java Bean. That's not directly your use-case since you want to use JSON as input, but maybe you designed your endpoints to expose Java Beans, so you can use them for your Pacts.

You might want to have a look at https://github.com/remondis-it/pact-consumer-builder.

With this library you're able to define PactDslJsonBody mappings on a per-field or a per-type basis. In our case this reduces the boilerplate code to nearly a one-liner:

PactDslJsonBody jsonBody = ConsumerExpects.type(YOUR_BEAN_TYPE.class)
   .useTypeMapping(...)
   // Other field or type configurations
   .build(new PactDslJsonBody(), YOUR_BEAN_SAMPLE_INSTANCE);

This performs the necessary calls on the PactDslJsonBody and you can use the result for your Pact test.

Btw: The Pact Consumer Builder library works well in conjunction with a fixture generator that produces test data instances for you Java Beans. You can use our fixture generator (https://github.com/remondis-it/resample) but every other Java Bean instance generator should work, too.

UNIQUEorn
  • 420
  • 6
  • 17