A consumer can describe the HTTP interaction it needs before a provider is available: the request, the expected response, and the rules that make returned data acceptable. Pact DSL is the fluent builder used to declare that interaction for a Pact mock server and convert it into a Pact file. section 5.2
An interaction starts with a provider state and a readable request description, then chains the request path and HTTP method. The response chain sets status, headers, and a body. This keeps the contract focused on an API exchange rather than unrelated application business rules. section 5.2
Describe a movie-list response
For GET /movies, declare that a movie exists, request all movies, and return 200 with application/json. Build the body as an array whose movie objects have integer id and year fields plus a string name field, then finish the interaction as a V4 Pact. section 5.2
Listing 5.13 createPact function
import au.com.dius.pact.core.model.annotations.Pact
@Pact(provider = "MoviesAPI", consumer = "MoviesAndroidApp")
fun createPact(builder: PactDslWithProvider): V4Pact {
val body: DslPart = PactDslJsonArray.arrayEachLike()
.integerType("id")
.stringType("name")
.integerType("year")
.closeObject()!!
return builder
.given("a movie exists")
.uponReceiving("a request for all movies")
.path("/movies")
.method("GET")
.willRespondWith()
.status(200)
.headers(mapOf("Content-type" to "application/json"))
.body(body)
.toPact(V4Pact::class.java)
}
The complete function shows the request and response declarations in one chain, from provider state through JSON matching rules to Pact creation. section 5.2
Matchers make contracts flexible where exact values would be brittle. Type methods can generate random example values when none are supplied, while optional examples can be recorded in the Pact file. Matching can also constrain paths, headers, and query parameters, allowing providers to substitute values from their own test data. section 5.2 section 5.3.1
Use matching methods according to the part of the interaction that varies:
- Use stringType, integerType, date, or ipAddress for JSON values whose shape matters more than one literal value. section 5.3.1
- Use matchPath when a URL segment follows a regular-expression pattern, such as a movie identifier. section 5.3.1
- Use matchHeader for values such as an API token that a provider replaces during verification. section 5.3.1
- Use matchQuery with a parameter name, regular expression, and example value for variable query input. section 5.3.1
