name: au.com.dius:pact-jvm-consumer_2.12
description: Pact consumer ============= Pact Consumer is used by projects that are consumers of an API. Most projects will want to use pact-consumer via one of the test framework specific projects. If your favourite framework is not implemented, this module should give you all the hooks you need. Provides a DSL for use with Java to build consumer pacts. ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer_2.11` ## DSL Usage Example in a JUnit test: ```java import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.RequestResponsePact; import org.apache.http.entity.ContentType; import org.jetbrains.annotations.NotNull; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static au.com.dius.pact.consumer.ConsumerPactRunnerKt.runConsumerTest; import static org.junit.Assert.assertEquals; public class PactTest { @Test public void testPact() { RequestResponsePact pact = ConsumerPactBuilder .consumer(&amp;quot;Some Consumer&amp;quot;) .hasPactWith(&amp;quot;Some Provider&amp;quot;) .uponReceiving(&amp;quot;a request to say Hello&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .method(&amp;quot;POST&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .toPact(); MockProviderConfig config = MockProviderConfig.createDefault(); PactVerificationResult result = runConsumerTest(pact, config, new PactTestRun() { @Override public void run(@NotNull MockServer mockServer) throws IOException { Map expectedResponse = new HashMap(); expectedResponse.put(&amp;quot;hello&amp;quot;, &amp;quot;harry&amp;quot;); assertEquals(expectedResponse, new ConsumerClient(mockServer.getUrl()).post(&amp;quot;/hello&amp;quot;, &amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;, ContentType.APPLICATION_JSON)); } }); if (result instanceof PactVerificationResult.Error) { throw new RuntimeException(((PactVerificationResult.Error)result).getError()); } assertEquals(PactVerificationResult.Ok.INSTANCE, result); } } ``` The DSL has the following pattern: ```java .consumer(&amp;quot;Some Consumer&amp;quot;) .hasPactWith(&amp;quot;Some Provider&amp;quot;) .given(&amp;quot;a certain state on the provider&amp;quot;) .uponReceiving(&amp;quot;a request for something&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .method(&amp;quot;POST&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .uponReceiving(&amp;quot;another request for something&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .method(&amp;quot;POST&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) . . . .toPact() ``` You can define as many interactions as required. Each interaction starts with `uponReceiving` followed by `willRespondWith`. The test state setup with `given` is a mechanism to describe what the state of the provider should be in before the provider is verified. It is only recorded in the consumer tests and used by the provider verification tasks. ### Building JSON bodies with PactDslJsonBody DSL The body method of the ConsumerPactBuilder can accept a PactDslJsonBody, which can construct a JSON body as well as define regex and type matchers. For example: ```java PactDslJsonBody body = new PactDslJsonBody() .stringType(&amp;quot;name&amp;quot;) .booleanType(&amp;quot;happy&amp;quot;) .hexValue(&amp;quot;hexCode&amp;quot;) .id() .ipAddress(&amp;quot;localAddress&amp;quot;) .numberValue(&amp;quot;age&amp;quot;, 100) .timestamp(); ``` #### DSL Matching methods The following matching methods are provided with the DSL. In most cases, they take an optional value parameter which will be used to generate example values (i.e. when returning a mock response). If no example value is given, a random one will be generated. | method | description | |--------|-------------| | string, stringValue | Match a string value (using string equality) | | number, numberValue | Match a number value (using Number.equals)\* | | booleanValue | Match a boolean value (using equality) | | stringType | Will match all Strings | | numberType | Will match all numbers\* | | integerType | Will match all numbers that are integers (both ints and longs)\* | | decimalType | Will match all real numbers (floating point and decimal)\* | | booleanType | Will match all boolean values (true and false) | | stringMatcher | Will match strings using the provided regular expression | | timestamp | Will match string containing timestamps. If a timestamp format is not given, will match an ISO timestamp format | | date | Will match string containing dates. If a date format is not given, will match an ISO date format | | time | Will match string containing times. If a time format is not given, will match an ISO time format | | ipAddress | Will match string containing IP4 formatted address. | | id | Will match all numbers by type | | hexValue | Will match all hexadecimal encoded strings | | uuid | Will match strings containing UUIDs | | includesStr | Will match strings containing the provided string | | equalsTo | Will match using equals | | matchUrl | Defines a matcher for URLs, given the base URL path and a sequence of path fragments. The path fragments could be strings or regular expression matchers | _\* Note:_ JSON only supports double precision floating point values. Depending on the language implementation, they may parsed as integer, floating point or decimal numbers. #### Ensuring all items in a list match an example (2.2.0+) Lots of the time you might not know the number of items that will be in a list, but you want to ensure that the list has a minimum or maximum size and that each item in the list matches a given example. You can do this with the `arrayLike`, `minArrayLike` and `maxArrayLike` functions. | function | description | |----------|-------------| | `eachLike` | Ensure that each item in the list matches the provided example | | `maxArrayLike` | Ensure that each item in the list matches the provided example and the list is no bigger than the provided max | | `minArrayLike` | Ensure that each item in the list matches the provided example and the list is no smaller than the provided min | For example: ```java DslPart body = new PactDslJsonBody() .minArrayLike(&amp;quot;users&amp;quot;) .id() .stringType(&amp;quot;name&amp;quot;) .closeObject() .closeArray(); ``` This will ensure that the users list is never empty and that each user has an identifier that is a number and a name that is a string. #### Matching JSON values at the root (Version 3.2.2/2.4.3+) For cases where you are expecting basic JSON values (strings, numbers, booleans and null) at the root level of the body and need to use matchers, you can use the `PactDslJsonRootValue` class. It has all the DSL matching methods for basic values that you can use. For example: ```java .consumer(&amp;quot;Some Consumer&amp;quot;) .hasPactWith(&amp;quot;Some Provider&amp;quot;) .uponReceiving(&amp;quot;a request for a basic JSON value&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### Root level arrays that match all items (version 2.2.11+) If the root of the body is an array, you can create PactDslJsonArray classes with the following methods: | function | description | |----------|-------------| | `arrayEachLike` | Ensure that each item in the list matches the provided example | | `arrayMinLike` | Ensure that each item in the list matches the provided example and the list is no bigger than the provided max | | `arrayMaxLike` | Ensure that each item in the list matches the provided example and the list is no smaller than the provided min | For example: ```java PactDslJsonArray.arrayEachLike() .date(&amp;quot;clearedDate&amp;quot;, &amp;quot;mm/dd/yyyy&amp;quot;, date) .stringType(&amp;quot;status&amp;quot;, &amp;quot;STATUS&amp;quot;) .decimalType(&amp;quot;amount&amp;quot;, 100.0) .closeObject() ``` This will then match a body like: ```json [ { &amp;quot;clearedDate&amp;quot; : &amp;quot;07/22/2015&amp;quot;, &amp;quot;status&amp;quot; : &amp;quot;C&amp;quot;, &amp;quot;amount&amp;quot; : 15.0 }, { &amp;quot;clearedDate&amp;quot; : &amp;quot;07/22/2015&amp;quot;, &amp;quot;status&amp;quot; : &amp;quot;C&amp;quot;, &amp;quot;amount&amp;quot; : 15.0 }, { &amp;quot;clearedDate&amp;quot; : &amp;quot;07/22/2015&amp;quot;, &amp;quot;status&amp;quot; : &amp;quot;C&amp;quot;, &amp;quot;amount&amp;quot; : 15.0 } ] ``` #### Matching arrays of arrays (version 3.2.12/2.4.14+) For the case where you have arrays of arrays (GeoJSON is an example), the following methods have been provided: | function | description | |----------|-------------| | `eachArrayLike` | Ensure that each item in the array is an array that matches the provided example | | `eachArrayWithMaxLike` | Ensure that each item in the array is an array that matches the provided example and the array is no bigger than the provided max | | `eachArrayWithMinLike` | Ensure that each item in the array is an array that matches the provided example and the array is no smaller than the provided min | For example (with GeoJSON structure): ```java new PactDslJsonBody() .stringType(&amp;quot;type&amp;quot;,&amp;quot;FeatureCollection&amp;quot;) .eachLike(&amp;quot;features&amp;quot;) .stringType(&amp;quot;type&amp;quot;,&amp;quot;Feature&amp;quot;) .object(&amp;quot;geometry&amp;quot;) .stringType(&amp;quot;type&amp;quot;,&amp;quot;Point&amp;quot;) .eachArrayLike(&amp;quot;coordinates&amp;quot;) // coordinates is an array of arrays .decimalType(-7.55717) .decimalType(49.766896) .closeArray() .closeArray() .closeObject() .object(&amp;quot;properties&amp;quot;) .stringType(&amp;quot;prop0&amp;quot;,&amp;quot;value0&amp;quot;) .closeObject() .closeObject() .closeArray() ``` This generated the following JSON: ```json { &amp;quot;features&amp;quot;: [ { &amp;quot;geometry&amp;quot;: { &amp;quot;coordinates&amp;quot;: [[-7.55717, 49.766896]], &amp;quot;type&amp;quot;: &amp;quot;Point&amp;quot; }, &amp;quot;type&amp;quot;: &amp;quot;Feature&amp;quot;, &amp;quot;properties&amp;quot;: { &amp;quot;prop0&amp;quot;: &amp;quot;value0&amp;quot; } } ], &amp;quot;type&amp;quot;: &amp;quot;FeatureCollection&amp;quot; } ``` and will be able to match all coordinates regardless of the number of coordinates. #### Matching any key in a map (3.3.1/2.5.0+) The DSL has been extended for cases where the keys in a map are IDs. For an example of this, see [#313](https://github.com/DiUS/pact-jvm/issues/313). In this case you can use the `eachKeyLike` method, which takes an example key as a parameter. For example: ```java DslPart body = new PactDslJsonBody() .object(&amp;quot;one&amp;quot;) .eachKeyLike(&amp;quot;001&amp;quot;, PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object(&amp;quot;two&amp;quot;) .eachKeyLike(&amp;quot;001-A&amp;quot;) // key like an id where the value is matched by the following example .stringType(&amp;quot;description&amp;quot;, &amp;quot;Some Description&amp;quot;) .closeObject() .closeObject() .object(&amp;quot;three&amp;quot;) .eachKeyMappedToAnArrayLike(&amp;quot;001&amp;quot;) // key like an id mapped to an array where each item is matched by the following example .id(&amp;quot;someId&amp;quot;, 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](../pact-jvm-consumer-junit/src/test/java/au/com/dius/pact/consumer/WildcardKeysTest.java). **NOTE:** The `eachKeyLike` method adds a `*` to the matching path, so the matching definition will be applied to all keys of the map if there is not a more specific matcher defined for a particular key. Having more than one `eachKeyLike` condition applied to a map will result in only one being applied when the pact is verified (probably the last). **Further Note: From version 3.5.22 onwards pacts with wildcards applied to map keys will require the Java system property &amp;quot;pact.matching.wildcard&amp;quot; set to value &amp;quot;true&amp;quot; when the pact file is verified.** ### Matching on paths (version 2.1.5+) You can use regular expressions to match incoming requests. The DSL has a `matchPath` method for this. You can provide a real path as a second value to use when generating requests, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given(&amp;quot;test state&amp;quot;) .uponReceiving(&amp;quot;a test interaction&amp;quot;) .matchPath(&amp;quot;/transaction/[0-9]+&amp;quot;) // or .matchPath(&amp;quot;/transaction/[0-9]+&amp;quot;, &amp;quot;/transaction/1234567890&amp;quot;) .method(&amp;quot;POST&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) ``` ### Matching on headers (version 2.2.2+) You can use regular expressions to match request and response headers. The DSL has a `matchHeader` method for this. You can provide an example header value to use when generating requests and responses, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given(&amp;quot;test state&amp;quot;) .uponReceiving(&amp;quot;a test interaction&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .method(&amp;quot;POST&amp;quot;) .matchHeader(&amp;quot;testreqheader&amp;quot;, &amp;quot;test.*value&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .matchHeader(&amp;quot;Location&amp;quot;, &amp;quot;.*/hello/[0-9]+&amp;quot;, &amp;quot;/hello/1234&amp;quot;) ``` ### Matching on query parameters (version 3.3.7+) You can use regular expressions to match request query parameters. The DSL has a `matchQuery` method for this. You can provide an example value to use when generating requests, and if you leave it out it will generate a random one from the regular expression. For example: ```java .given(&amp;quot;test state&amp;quot;) .uponReceiving(&amp;quot;a test interaction&amp;quot;) .path(&amp;quot;/hello&amp;quot;) .method(&amp;quot;POST&amp;quot;) .matchQuery(&amp;quot;a&amp;quot;, &amp;quot;\\d+&amp;quot;, &amp;quot;100&amp;quot;) .matchQuery(&amp;quot;b&amp;quot;, &amp;quot;[A-Z]&amp;quot;, &amp;quot;X&amp;quot;) .body(&amp;quot;{\&amp;quot;name\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) .willRespondWith() .status(200) .body(&amp;quot;{\&amp;quot;hello\&amp;quot;: \&amp;quot;harry\&amp;quot;}&amp;quot;) ``` # Forcing pact files to be overwritten (3.6.5+) By default, when the pact file is written, it will be merged with any existing pact file. To force the file to be overwritten, set the Java system property `pact.writer.overwrite` to `true`. # Having values injected from provider state callbacks (3.6.11+) You can have values from the provider state callbacks be injected into most places (paths, query parameters, headers, bodies, etc.). This works by using the V3 spec generators with provider state callbacks that return values. One example of where this would be useful is API calls that require an ID which would be auto-generated by the database on the provider side, so there is no way to know what the ID would be beforehand. The following DSL methods allow you to set an expression that will be parsed with the values returned from the provider states: For JSON bodies, use `valueFromProviderState`.&amp;lt;br/&amp;gt; For headers, use `headerFromProviderState`.&amp;lt;br/&amp;gt; For query parameters, use `queryParameterFromProviderState`.&amp;lt;br/&amp;gt; For paths, use `pathFromProviderState`. For example, assume that an API call is made to get the details of a user by ID. A provider state can be defined that specifies that the user must be exist, but the ID will be created when the user is created. So we can then define an expression for the path where the ID will be replaced with the value returned from the provider state callback. ```java .pathFromProviderState(&amp;quot;/api/users/${id}&amp;quot;, &amp;quot;/api/users/100&amp;quot;) ``` You can also just use the key instead of an expression: ```java .valueFromProviderState(&amp;apos;userId&amp;apos;, &amp;apos;userId&amp;apos;, 100) // will look value using userId as the key ```
license_spdx: Apache-2.0
version: 3.6.15
spec_version: 1.0
download_url: https://repo1.maven.org/maven2/au/com/dius/pact-jvm-consumer_2.12/3.6.15/pact-jvm-consumer_2.12-3.6.15.jar
home_url: https://github.com/DiUS/pact-jvm
news_url: https://libraries.io/maven/au.com.dius:pact-jvm-consumer_2.12/versions.atom
date: 2020-04-29
about_resource: NONE
libraries_io_url: https://libraries.io/maven/au.com.dius:pact-jvm-consumer_2.12?number=3.6.15
vcs_tool: git
vcs_repository: https://github.com/pact-foundation/pact-jvm
vcs_branch: master
