javapactpact-jvmpact-java

how to parse the response at pact provider verfication


My scenario is that there are two interactions defined by the consumer, interation1 with state1, and interation2 with state2. After running interation1, there will be an id in the JSON response, and this id has to be used as the query parameter of interation2. At the provider side, is there a way to extract that id from the response of interation1? I am using pact provider junit by the way.


Solution

  • You are thinking about things in the wrong way.

    Provider states are designed to prevent this form of coupling. Interaction 1 should be completely independent of Interaction 2.

    From the documentation:

    Tests that depend on the outcome of previous tests are brittle and land you back in integration test hell, which is the nasty place you're trying to escape by using pacts.

    You must have control over the provider test context for Pact testing to work.

    In your case, for State 2 you might have the following description:

    a user with ID 1 exists
    

    Before that particular Interaction is tested, Pact will provide you with the opportunity to setup that state, however that should be done for your use case - e.g. your code could create the resource in the database (or an in-memory one) with that ID.

    @State("a user with ID 1 exists") // Must match the state description in the pact file
    public void setupUser1() {
      // Do what you need to for that user to exist 
    }
    

    This way, Interaction 2 may be executed without the knowledge that Interaction 1 exists at all.