Here is a quick example for a Consumer test and a Provider test.
Consumer
This is some sample code for the consumer. This will create a 'pact' json file in the target folder after a maven build. This json is what will get sent to the Pact Broker or can be used to validate the pacts locally instead.public class MyPactConsumerTest {
@Rule
public PactProviderRuleMk2 pactProviderRule = new PactProviderRuleMk2("<NAME_OF_PROVIDER>", "localhost", PACT_SERVER_PORT, PactSpecVersion.V2, this);
@Pact(consumer = "<NAME_OF_CONSUMER>", provider = "<NAME_OF_PROVIDER")
public RequestResponsePact doSomething(final PactDslWithProvider pactDslWithProvider) {
return pactDslWithProvider.given("<STATE>")
.uponReceiving("<DESCRIPTION")
.path("<URL>")
.method("POST")
.body(getExpectedRequestBody())
.headers("Content-Type", "<TYPE>")
.willRespondWith()
.status(HttpStatus.NO_CONTENT.value())
.toPact();
}
@Test
@PactVerification(fragment = "doSomething") <THIS IS THE METHOD NAME ABOVE>
public void testDoSomething() {
someJavaClassToCall.someMethod();
}
private DslPart getExpectedResponseBody() {
return new PactDslJsonBody().stringMatcher("dataAttribute", ".*", "");
}
}
Provider
The provider can then validate the pact json created by the consumer above. If the Pacts are published then it is necessary to validate against the Broker with the @PactBroker annotation. If you want to just validate against a pact json file then copy the file into a folder in /src/test/resources/pact (or something) and just add the @PactFolder("pact") annotation instead.
@Provider("<NAME_OF_PROVIDER>")
@PactBroker
@IgnoreNoPactsToVerify
//@PactFolder("pact") <A FOLDER CAN BE USED INSTEAD OF THE BROKER>
public class MyPactProviderTest {
@State("<STATE>")
public void methodName() {
when(mockService.mockMethod(any())).thenReturn(new Data()); <THIS RETURNS DATA THAT MATCHES THE RESPONSE BODY ABOVE>
}
}