All Downloads are FREE. Search and download functionalities are using the official Maven repository.

Download JAR files tagged by directly with all dependencies

Search JAR files by class name

tagmycode-netbeans from group com.tagmycode (version 2.3.0)

Provides the support for <a href="https://tagmycode.com">TagMyCode</a>. This plugin allows you to manage your own snippets.<br/> <br/> Features:<br/> * Add snippets: you can save your code snippets including description, language, and tags<br/> * List snippets (CRUD): snippets are stored locally and you can filter, sort, create, modify, edit or delete them directly from the IDE<br/> * Quick search: you can search your snippets and insert them directly into the document<br/> <br/> CHANGELOG:<br/> <br/> 2.3.0 (released 2020-07-26)<br/> * published plugin into Apache NetBeans Plugin Portal<br/> * filter snippets by languages<br/> <br/> 2.2.1 (released 2018-01-10)<br/> * Quick Search dialog is now resizable</br> * fixed syntax highlight for PHP and HTML</br> * if refresh token is not valid user will be automatically logged out</br> </br> 2.2.0 (released 2017-11-06)<br/> * snippets management works in offline mode<br/> * autodetect language on new snippet<br/> * added settings dialog with editor theme and font size option<br/> * added title and description to snippet view<br/> * changed open browser class<br/> * text can be dragged into table to create a new snippet<br/> * snippets can be dragged directly into editor and the code are copied<br/> * added "save as file" feature<br/> * added "clone snippet" feature<br/> * added "snippet properties" dialog<br/> * detect binary file<br/> <br/> 2.1.0 (released 2017-04-24)<br/> * moved error messages from dialog to Netbeans Notification Log<br/> * added welcome panel<br/> * about dialog shows plugin version and framework version<br/> * moved storage from JSON to SQL<br/> <br/> 2.0 (released 2016-07-11)<br/> * new user interface<br/> * list of snippets stored locally<br/> * syntax highlight powered by <a href="http://bobbylight.github.io/RSyntaxTextArea/">RSyntaxTextArea</a><br/> * snippets are synchronized with server<br/> * filter snippets<br/> * quick search feature<br/> * insert selected snippet at cursor in document<br/> <br/> 1.1.3 (released 2015-12-18)<br/> * Fix for NetBeans 8.1<br/> <br/> 1.1.2 (released 2014-10-03)<br/> * Switched authentication from OAuth 1.0a to OAuth 2<br/> * Console write also snippet title when new snippet is created (thanks to bejoy)<br/> <br/> 1.1 (released 2014-08-19)<br/> * Added "Search snippets" feature<br/> * Fixed some minor bugs<br/> <br/> 1.0 (released 2014-04-14)<br/> * First release with feature "Create snippet"<br/>

Group: com.tagmycode Artifact: tagmycode-netbeans
Show documentation Show source 
 

0 downloads
Artifact tagmycode-netbeans
Group com.tagmycode
Version 2.3.0
Last update 06. September 2020
Organization not specified
URL https://tagmycode.com
License Apache License 2.0
Dependencies amount 18
Dependencies commons-lang3, rsyntaxtextarea, guava, org-netbeans-api-annotations-common, org-openide-awt, org-netbeans-modules-settings, org-openide-dialogs, org-netbeans-modules-editor, org-netbeans-modules-keyring, org-openide-nodes, org-openide-util, org-openide-loaders, org-openide-windows, org-openide-util-ui, org-openide-text, org-netbeans-api-progress, log4j, tagmycode-plugin-framework,
There are maybe transitive dependencies!

HockeySDK from group net.hockeyapp.android (version 5.2.0)

HockeySDK-Android implements support for using HockeyApp in your Android application. The following features are currently supported: Collect crash reports:If your app crashes, a crash log is written to the device's storage. If the user starts the app again, they will be asked asked to submit the crash report to HockeyApp. This works for both beta and live apps, i.e. those submitted to Google Play or other app stores. Crash logs contain viable information for you to help resolve the issue. Furthermore, you as a developer can add additional information to the report as well. Update Alpha/Beta apps: The app will check with HockeyApp if a new version for your alpha/beta build is available. If yes, it will show a dialog to users and let them see the release notes, the version history and start the installation process right away. You can even force the installation of certain updates. User Metrics: Understand user behavior to improve your app. Track usage through daily and monthly active users. Monitor crash impacted users. Measure customer engagement through session count. Add custom tracking calls to learn which features your users are actually using. This feature requires a minimum API level of 14 (Android 4.x Ice Cream Sandwich). Feedback: Besides crash reports, collecting feedback from your users from within your app is a great option to help with improving your app. You act on and answer feedback directly from the HockeyApp backend. Authenticate: Identify and authenticate users against your registered testers with the HockeyApp backend.

Group: net.hockeyapp.android Artifact: HockeySDK
Show all versions Show documentation 
There is no JAR file uploaded. A download is not possible! Please choose another version.
0 downloads
Artifact HockeySDK
Group net.hockeyapp.android
Version 5.2.0
Last update 21. May 2019
Organization not specified
URL https://github.com/bitstadium/hockeysdk-android
License MIT
Dependencies amount 0
Dependencies No dependencies
There are maybe transitive dependencies!

osgi-tests from group org.apache.axis2 (version 1.6.3)

Group: org.apache.axis2 Artifact: osgi-tests
Show source 
 

1 downloads
Artifact osgi-tests
Group org.apache.axis2
Version 1.6.3
Last update 27. June 2015
Organization not specified
URL http://axis.apache.org/axis2/java/core/
License not specified
Dependencies amount 1
Dependencies axis2-testutils,
There are maybe transitive dependencies!

axis2-parent from group org.apache.axis2 (version 1.6.3)

Axis2 is an effort to re-design and totally re-implement both Axis/Java and (eventually) Axis/C++ on a new architecture. Evolving from the now standard "handler chain" model which Axis1 pioneered, Axis2 is developing a more flexible pipeline architecture which can yet be managed and packaged in a more organized manner. This new design acknowledges the maturing of the Web services space in terms of new protocols such as WS-ReliableMessaging, WS-Security and WS-Addressing that are built on top of the base SOAP system. At the time Axis1 was designed, while it was fully expected that other protocols such as WS-ReliableMessaging would be built on top of it, there was not a proper extension architecture defined to enable clean composition of such layers. Thus, one of the key motivations for Axis2 is to provide a clean and simple environment for like Apache Sandesha and Apache WSS4J to layer on top of the base SOAP system. Another driving force for Axis2 as well as the move away from RPC oriented Web services towards more document-oriented, message style asynchronous service interactions. The Axis2 project is centered on a new representation for SOAP messages called AXIOM (AXIs Object Model). AXIOM consists of two parts: a complete XML Infoset representation and a SOAP Infoset representation on top of that. The XML Infoset representation provides a JDOM-like simple API but is built on a deferred model via a StAX-based (Streaming API for XML) pull parsing API. A key feature of AXIOM is that it allows one to stop building the XML tree and just access the pull stream directly; thus enabling both maximum flexibility and maximum performance. This approach allows us to support multiple levels of abstraction for consuming and offering Web services: using plain AXIOM, using generated code and statically data-bound data types and so on. At the time of Axis1's design, RPC-style, synchronous, request-response interactions were the order of the day for Web services. Today service interactions are much more message -oriented and exploit many different message exchange patterns. The Axis2 engine architecture is careful to not build in any assumptions of request-response patterns to ensure that it can be used easily to support arbitrary message exchange patterns.

Group: org.apache.axis2 Artifact: axis2-parent
Show all versions 
There is no JAR file uploaded. A download is not possible! Please choose another version.
0 downloads
Artifact axis2-parent
Group org.apache.axis2
Version 1.6.3
Last update 27. June 2015
Organization not specified
URL http://axis.apache.org/axis2/java/core/
License not specified
Dependencies amount 0
Dependencies No dependencies
There are maybe transitive dependencies!

pact-jvm-consumer-junit_2.12 from group au.com.dius (version 3.6.15)

pact-jvm-consumer-junit ======================= Provides a DSL and a base test class for use with Junit to build consumer tests. ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit_2.12` * version-id = `3.5.x` ## Usage ### Using the base ConsumerPactTest To write a pact spec extend ConsumerPactTest. This base class defines the following four methods which must be overridden in your test class. * *providerName:* Returns the name of the API provider that Pact will mock * *consumerName:* Returns the name of the API consumer that we are testing. * *createFragment:* Returns the PactFragment containing the interactions that the test setup using the ConsumerPactBuilder DSL * *runTest:* The actual test run. It receives the URL to the mock server as a parameter. Here is an example: ```java import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.exampleclients.ConsumerClient; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.model.PactFragment; import org.junit.Assert; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ExampleJavaConsumerPactTest extends ConsumerPactTest { @Override protected RequestResponsePact createFragment(PactDslWithProvider builder) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); return builder .given(&quot;test state&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .headers(headers) .willRespondWith() .status(200) .headers(headers) .body(&quot;{\&quot;responsetest\&quot;: true, \&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .given(&quot;test state 2&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest second test interaction&quot;) .method(&quot;OPTIONS&quot;) .headers(headers) .path(&quot;/second&quot;) .body(&quot;&quot;) .willRespondWith() .status(200) .headers(headers) .body(&quot;&quot;) .toPact(); } @Override protected String providerName() { return &quot;test_provider&quot;; } @Override protected String consumerName() { return &quot;test_consumer&quot;; } @Override protected void runTest(MockServer mockServer, PactTestExecutionContext context) throws IOException { Assert.assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); expectedResponse.put(&quot;name&quot;, &quot;harry&quot;); assertEquals(new ConsumerClient(mockServer.getUrl()).getAsMap(&quot;/&quot;, &quot;&quot;), expectedResponse); assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); } } ``` ### Using the Pact JUnit Rule Thanks to [@warmuuh](https://github.com/warmuuh) we have a JUnit rule that simplifies running Pact consumer tests. To use it, create a test class and then add the rule: #### 1. Add the Pact Rule to your test class to represent your provider. ```java @Rule public PactProviderRule mockProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8080, this); ``` The hostname and port are optional. If left out, it will default to 127.0.0.1 and a random available port. You can get the URL and port from the pact provider rule. #### 2. Annotate a method with Pact that returns a pact fragment for the provider and consumer ```java @Pact(provider=&quot;test_provider&quot;, consumer=&quot;test_consumer&quot;) public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Pact(consumer=&quot;test_consumer&quot;) // will default to the provider name from mockProvider public RequestResponsePact createFragment(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` #### 3. Annotate your test method with PactVerification to have it run in the context of the mock server setup with the appropriate pact from step 1 and 2 ```java @Test @PactVerification(&quot;test_provider&quot;) public void runTest() { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(mockProvider.getUrl()).get(&quot;/&quot;), expectedResponse); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Test @PactVerification public void runTest() { // This will run against mockProvider Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(&quot;http://localhost:8080&quot;).get(&quot;/&quot;), expectedResponse); } ``` For an example, have a look at [ExampleJavaConsumerPactRuleTest](src/test/java/au/com/dius/pact/consumer/examples/ExampleJavaConsumerPactRuleTest.java) ### Requiring a test with multiple providers The Pact Rule can be used to test with multiple providers. Just add a rule to the test class for each provider, and then include all the providers required in the `@PactVerification` annotation. For an example, look at [PactMultiProviderTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactMultiProviderTest.java). Note that if more than one provider fails verification for the same test, you will only receive a failure for one of them. Also, to have multiple tests in the same test class, the providers must be setup with random ports (i.e. don&apos;t specify a hostname and port). Also, if the provider name is left out of any of the annotations, the first one found will be used (which may not be the first one defined). ### Requiring the mock server to run with HTTPS [versions 3.2.7/2.4.9+] From versions 3.2.7/2.4.9+ the mock server can be started running with HTTPS using a self-signed certificate instead of HTTP. To enable this set the `https` parameter to `true`. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, PactSpecVersion.V2, this); // ^^^^ ``` For an example test doing this, see [PactProviderHttpsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsTest.java). **NOTE:** The provider will start handling HTTPS requests using a self-signed certificate. Most HTTP clients will not accept connections to a self-signed server as the certificate is untrusted. You may need to enable insecure HTTPS with your client for this test to work. For an example of how to enable insecure HTTPS client connections with Apache Http Client, have a look at [InsecureHttpsRequest](src/test/java/org/apache/http/client/fluent/InsecureHttpsRequest.java). ### Requiring the mock server to run with HTTPS with a keystore [versions 3.4.1+] From versions 3.4.1+ the mock server can be started running with HTTPS using a keystore. To enable this set the `https` parameter to `true`, set the keystore path/file, and the keystore&apos;s password. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, &quot;/path/to/your/keystore.jks&quot;, &quot;your-keystore-password&quot;, PactSpecVersion.V2, this); ``` For an example test doing this, see [PactProviderHttpsKeystoreTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsKeystoreTest.java). ### Setting default expected request and response values [versions 3.5.10+] If you have a lot of tests that may share some values (like headers), you can setup default values that will be applied to all the expected requests and responses for the tests. To do this, you need to create a method that takes single parameter of the appropriate type (`PactDslRequestWithoutPath` or `PactDslResponse`) and annotate it with the default marker annotation (`@DefaultRequestValues` or `@DefaultResponseValues`). For example: ```java @DefaultRequestValues public void defaultRequestValues(PactDslRequestWithoutPath request) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); request.headers(headers); } @DefaultResponseValues public void defaultResponseValues(PactDslResponse response) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testresheader&quot;, &quot;testresheadervalue&quot;); response.headers(headers); } ``` For an example test that uses these, have a look at [PactProviderWithMultipleFragmentsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderWithMultipleFragmentsTest.java) ### Note on HTTP clients and persistent connections Some HTTP clients may keep the connection open, based on the live connections settings or if they use a connection cache. This could cause your tests to fail if the client you are testing lives longer than an individual test, as the mock server will be started and shutdown for each test. This will result in the HTTP client connection cache having invalid connections. For an example of this where the there was a failure for every second test, see [Issue #342](https://github.com/DiUS/pact-jvm/issues/342). ### Using the Pact DSL directly Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. The DSL can be used directly in this case. Example: ```java import au.com.dius.pact.consumer.ConsumerPactBuilder; import au.com.dius.pact.consumer.PactVerificationResult; import au.com.dius.pact.consumer.exampleclients.ProviderClient; import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.RequestResponsePact; 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; /** * Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. * The DSL can be used directly in this case. */ public class DirectDSLConsumerPactTest { @Test public void testPact() { RequestResponsePact pact = ConsumerPactBuilder .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request to say Hello&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .toPact(); MockProviderConfig config = MockProviderConfig.createDefault(); PactVerificationResult result = runConsumerTest(pact, config, (mockServer, context) -&gt; { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;hello&quot;, &quot;harry&quot;); try { assertEquals(new ProviderClient(mockServer.getUrl()).hello(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;), expectedResponse); } catch (IOException e) { throw new RuntimeException(e); } }); if (result instanceof PactVerificationResult.Error) { throw new RuntimeException(((PactVerificationResult.Error)result).getError()); } assertEquals(PactVerificationResult.Ok.INSTANCE, result); } } ``` ### The Pact JUnit DSL The DSL has the following pattern: ```java .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .given(&quot;a certain state on the provider&quot;) .uponReceiving(&quot;a request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .uponReceiving(&quot;another request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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 **NOTE:** If you are using Java 8, there is [an updated DSL for consumer tests](../pact-jvm-consumer-java8). 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(&quot;name&quot;) .booleanType(&quot;happy&quot;) .hexValue(&quot;hexCode&quot;) .id() .ipAddress(&quot;localAddress&quot;) .numberValue(&quot;age&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(&quot;users&quot;, 1) .id() .stringType(&quot;name&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. __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. ```java DslPart body = new PactDslJsonBody() .minArrayLike(&quot;users&quot;, 1, 2) .id() .stringType(&quot;name&quot;) .closeObject() .closeArray(); ``` This will generate the example body with 2 items in the users list. #### 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(&quot;clearedDate&quot;, &quot;mm/dd/yyyy&quot;, date) .stringType(&quot;status&quot;, &quot;STATUS&quot;) .decimalType(&quot;amount&quot;, 100.0) .closeObject() ``` This will then match a body like: ```json [ { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 } ] ``` __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. #### 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(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request for a basic JSON value&quot;) .path(&quot;/hello&quot;) .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### 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(&quot;one&quot;) .eachKeyLike(&quot;001&quot;, PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object(&quot;two&quot;) .eachKeyLike(&quot;001-A&quot;) // key like an id where the value is matched by the following example .stringType(&quot;description&quot;, &quot;Some Description&quot;) .closeObject() .closeObject() .object(&quot;three&quot;) .eachKeyMappedToAnArrayLike(&quot;001&quot;) // key like an id mapped to an array where each item is matched by the following example .id(&quot;someId&quot;, 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](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 &quot;pact.matching.wildcard&quot; set to value &quot;true&quot; when the pact file is verified.** #### Combining matching rules with AND/OR Matching rules can be combined with AND/OR. There are two methods available on the DSL for this. For example: ```java DslPart body = new PactDslJsonBody() .numberValue(&quot;valueA&quot;, 100) .and(&quot;valueB&quot;,&quot;AB&quot;, PM.includesStr(&quot;A&quot;), PM.includesStr(&quot;B&quot;)) // Must match both matching rules .or(&quot;valueC&quot;, null, PM.date(), PM.nullValue()) // will match either a valid date or a null value ``` The `and` and `or` methods take a variable number of matchers (varargs). ### 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .matchPath(&quot;/transaction/[0-9]+&quot;) // or .matchPath(&quot;/transaction/[0-9]+&quot;, &quot;/transaction/1234567890&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchHeader(&quot;testreqheader&quot;, &quot;test.*value&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .matchHeader(&quot;Location&quot;, &quot;.*/hello/[0-9]+&quot;, &quot;/hello/1234&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchQuery(&quot;a&quot;, &quot;\\d+&quot;, &quot;100&quot;) .matchQuery(&quot;b&quot;, &quot;[A-Z]&quot;, &quot;X&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) ``` ## Debugging pact failures When the test runs, Pact will start a mock provider that will listen for requests and match them against the expectations you setup in `createFragment`. If the request does not match, it will return a 500 error response. Each request received and the generated response is logged using [SLF4J](http://www.slf4j.org/). Just enable debug level logging for au.com.dius.pact.consumer.UnfilteredMockProvider. Most failures tend to be mismatched headers or bodies. ## Changing the directory pact files are written to (2.1.9+) By default, pact files are written to `target/pacts` (or `build/pacts` if you use Gradle), but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties[&apos;pact.rootDir&apos;] = &quot;$buildDir/custom-pacts-directory&quot; } ``` For maven, use the systemPropertyVariables configuration: ```xml &lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.18&lt;/version&gt; &lt;configuration&gt; &lt;systemPropertyVariables&gt; &lt;pact.rootDir&gt;some/other/directory&lt;/pact.rootDir&gt; &lt;buildDirectory&gt;${project.build.directory}&lt;/buildDirectory&gt; [...] &lt;/systemPropertyVariables&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq(&quot;-Dpact.rootDir=some/other/directory&quot;) ``` ### Using `@PactFolder` annotation [3.6.2+] You can override the directory the pacts are written in a test by adding the `@PactFolder` annotation to the test class. ## 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`. # Publishing your pact files to a pact broker If you use Gradle, you can use the [pact Gradle plugin](https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-provider-gradle#publishing-pact-files-to-a-pact-broker) to publish your pact files. # Pact Specification V3 Version 3 of the pact specification changes the format of pact files in the following ways: * Query parameters are stored in a map form and are un-encoded (see [#66](https://github.com/DiUS/pact-jvm/issues/66) and [#97](https://github.com/DiUS/pact-jvm/issues/97) for information on what this can cause). * Introduces a new message pact format for testing interactions via a message queue. * Multiple provider states can be defined with data parameters. ## Generating V2 spec pact files (3.1.0+, 2.3.0+) To have your consumer tests generate V2 format pacts, you can set the specification version to V2. If you&apos;re using the `ConsumerPactTest` base class, you can override the `getSpecificationVersion` method. For example: ```java @Override protected PactSpecVersion getSpecificationVersion() { return PactSpecVersion.V2; } ``` If you are using the `PactProviderRule`, you can pass the version into the constructor for the rule. ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, PactSpecVersion.V2, this); ``` ## Consumer test for a message consumer For testing a consumer of messages from a message queue, the `MessagePactProviderRule` rule class works in much the same way as the `PactProviderRule` class for Request-Response interactions, but will generate a V3 format message pact file. For an example, look at [ExampleMessageConsumerTest](https://github.com/DiUS/pact-jvm/blob/master/pact-jvm-consumer-junit%2Fsrc%2Ftest%2Fjava%2Fau%2Fcom%2Fdius%2Fpact%2Fconsumer%2Fv3%2FExampleMessageConsumerTest.java) # 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 all you to set an expression that will be parsed with the values returned from the provider states: For JSON bodies, use `valueFromProviderState`.&lt;br/&gt; For headers, use `headerFromProviderState`.&lt;br/&gt; For query parameters, use `queryParameterFromProviderState`.&lt;br/&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(&quot;/api/users/${id}&quot;, &quot;/api/users/100&quot;) ``` You can also just use the key instead of an expression: ```java .valueFromProviderState(&apos;userId&apos;, &apos;userId&apos;, 100) // will look value using userId as the key ```

Group: au.com.dius Artifact: pact-jvm-consumer-junit_2.12
Show all versions Show documentation Show source 
 

14 downloads
Artifact pact-jvm-consumer-junit_2.12
Group au.com.dius
Version 3.6.15
Last update 29. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies pact-jvm-consumer_2.12, junit, json, commons-lang3, guava,
There are maybe transitive dependencies!

pact-jvm-consumer-junit from group au.com.dius (version 4.0.10)

pact-jvm-consumer-junit ======================= Provides a DSL and a base test class for use with Junit to build consumer tests. ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit` * version-id = `4.0.x` ## Usage ### Using the base ConsumerPactTest To write a pact spec extend ConsumerPactTest. This base class defines the following four methods which must be overridden in your test class. * *providerName:* Returns the name of the API provider that Pact will mock * *consumerName:* Returns the name of the API consumer that we are testing. * *createFragment:* Returns the PactFragment containing the interactions that the test setup using the ConsumerPactBuilder DSL * *runTest:* The actual test run. It receives the URL to the mock server as a parameter. Here is an example: ```java import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.exampleclients.ConsumerClient; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.model.PactFragment; import org.junit.Assert; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ExampleJavaConsumerPactTest extends ConsumerPactTest { @Override protected RequestResponsePact createFragment(PactDslWithProvider builder) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); return builder .given(&quot;test state&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .headers(headers) .willRespondWith() .status(200) .headers(headers) .body(&quot;{\&quot;responsetest\&quot;: true, \&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .given(&quot;test state 2&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest second test interaction&quot;) .method(&quot;OPTIONS&quot;) .headers(headers) .path(&quot;/second&quot;) .body(&quot;&quot;) .willRespondWith() .status(200) .headers(headers) .body(&quot;&quot;) .toPact(); } @Override protected String providerName() { return &quot;test_provider&quot;; } @Override protected String consumerName() { return &quot;test_consumer&quot;; } @Override protected void runTest(MockServer mockServer, PactTestExecutionContext context) throws IOException { Assert.assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); expectedResponse.put(&quot;name&quot;, &quot;harry&quot;); assertEquals(new ConsumerClient(mockServer.getUrl()).getAsMap(&quot;/&quot;, &quot;&quot;), expectedResponse); assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); } } ``` ### Using the Pact JUnit Rule Thanks to [@warmuuh](https://github.com/warmuuh) we have a JUnit rule that simplifies running Pact consumer tests. To use it, create a test class and then add the rule: #### 1. Add the Pact Rule to your test class to represent your provider. ```java @Rule public PactProviderRule mockProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8080, this); ``` The hostname and port are optional. If left out, it will default to 127.0.0.1 and a random available port. You can get the URL and port from the pact provider rule. #### 2. Annotate a method with Pact that returns a pact fragment for the provider and consumer ```java @Pact(provider=&quot;test_provider&quot;, consumer=&quot;test_consumer&quot;) public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Pact(consumer=&quot;test_consumer&quot;) // will default to the provider name from mockProvider public RequestResponsePact createFragment(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` #### 3. Annotate your test method with PactVerification to have it run in the context of the mock server setup with the appropriate pact from step 1 and 2 ```java @Test @PactVerification(&quot;test_provider&quot;) public void runTest() { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(mockProvider.getUrl()).get(&quot;/&quot;), expectedResponse); } ``` You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Test @PactVerification public void runTest() { // This will run against mockProvider Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(&quot;http://localhost:8080&quot;).get(&quot;/&quot;), expectedResponse); } ``` For an example, have a look at [ExampleJavaConsumerPactRuleTest](src/test/java/au/com/dius/pact/consumer/examples/ExampleJavaConsumerPactRuleTest.java) ### Requiring a test with multiple providers The Pact Rule can be used to test with multiple providers. Just add a rule to the test class for each provider, and then include all the providers required in the `@PactVerification` annotation. For an example, look at [PactMultiProviderTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactMultiProviderTest.java). Note that if more than one provider fails verification for the same test, you will only receive a failure for one of them. Also, to have multiple tests in the same test class, the providers must be setup with random ports (i.e. don&apos;t specify a hostname and port). Also, if the provider name is left out of any of the annotations, the first one found will be used (which may not be the first one defined). ### Requiring the mock server to run with HTTPS The mock server can be started running with HTTPS using a self-signed certificate instead of HTTP. To enable this set the `https` parameter to `true`. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, PactSpecVersion.V2, this); // ^^^^ ``` For an example test doing this, see [PactProviderHttpsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsTest.java). **NOTE:** The provider will start handling HTTPS requests using a self-signed certificate. Most HTTP clients will not accept connections to a self-signed server as the certificate is untrusted. You may need to enable insecure HTTPS with your client for this test to work. For an example of how to enable insecure HTTPS client connections with Apache Http Client, have a look at [InsecureHttpsRequest](src/test/java/org/apache/http/client/fluent/InsecureHttpsRequest.java). ### Requiring the mock server to run with HTTPS with a keystore The mock server can be started running with HTTPS using a keystore. To enable this set the `https` parameter to `true`, set the keystore path/file, and the keystore&apos;s password. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, &quot;/path/to/your/keystore.jks&quot;, &quot;your-keystore-password&quot;, PactSpecVersion.V2, this); ``` For an example test doing this, see [PactProviderHttpsKeystoreTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsKeystoreTest.java). ### Setting default expected request and response values If you have a lot of tests that may share some values (like headers), you can setup default values that will be applied to all the expected requests and responses for the tests. To do this, you need to create a method that takes single parameter of the appropriate type (`PactDslRequestWithoutPath` or `PactDslResponse`) and annotate it with the default marker annotation (`@DefaultRequestValues` or `@DefaultResponseValues`). For example: ```java @DefaultRequestValues public void defaultRequestValues(PactDslRequestWithoutPath request) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); request.headers(headers); } @DefaultResponseValues public void defaultResponseValues(PactDslResponse response) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testresheader&quot;, &quot;testresheadervalue&quot;); response.headers(headers); } ``` For an example test that uses these, have a look at [PactProviderWithMultipleFragmentsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderWithMultipleFragmentsTest.java) ### Note on HTTP clients and persistent connections Some HTTP clients may keep the connection open, based on the live connections settings or if they use a connection cache. This could cause your tests to fail if the client you are testing lives longer than an individual test, as the mock server will be started and shutdown for each test. This will result in the HTTP client connection cache having invalid connections. For an example of this where the there was a failure for every second test, see [Issue #342](https://github.com/DiUS/pact-jvm/issues/342). ### Using the Pact DSL directly Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. The DSL can be used directly in this case. Example: ```java import au.com.dius.pact.consumer.ConsumerPactBuilder; import au.com.dius.pact.consumer.PactVerificationResult; import au.com.dius.pact.consumer.exampleclients.ProviderClient; import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.RequestResponsePact; 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; /** * Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. * The DSL can be used directly in this case. */ public class DirectDSLConsumerPactTest { @Test public void testPact() { RequestResponsePact pact = ConsumerPactBuilder .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request to say Hello&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .toPact(); MockProviderConfig config = MockProviderConfig.createDefault(); PactVerificationResult result = runConsumerTest(pact, config, (mockServer, context) -&gt; { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;hello&quot;, &quot;harry&quot;); try { assertEquals(new ProviderClient(mockServer.getUrl()).hello(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;), expectedResponse); } catch (IOException e) { throw new RuntimeException(e); } }); if (result instanceof PactVerificationResult.Error) { throw new RuntimeException(((PactVerificationResult.Error)result).getError()); } assertEquals(PactVerificationResult.Ok.INSTANCE, result); } } ``` ### The Pact JUnit DSL The DSL has the following pattern: ```java .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .given(&quot;a certain state on the provider&quot;) .uponReceiving(&quot;a request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .uponReceiving(&quot;another request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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 **NOTE:** If you are using Java 8, there is [an updated DSL for consumer tests](../pact-jvm-consumer-java8). 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(&quot;name&quot;) .booleanType(&quot;happy&quot;) .hexValue(&quot;hexCode&quot;) .id() .ipAddress(&quot;localAddress&quot;) .numberValue(&quot;age&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 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(&quot;users&quot;, 1) .id() .stringType(&quot;name&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. You can specify the number of example items to generate in the array. The default is 1. ```java DslPart body = new PactDslJsonBody() .minArrayLike(&quot;users&quot;, 1, 2) .id() .stringType(&quot;name&quot;) .closeObject() .closeArray(); ``` This will generate the example body with 2 items in the users list. #### Root level arrays that match all items 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(&quot;clearedDate&quot;, &quot;mm/dd/yyyy&quot;, date) .stringType(&quot;status&quot;, &quot;STATUS&quot;) .decimalType(&quot;amount&quot;, 100.0) .closeObject() ``` This will then match a body like: ```json [ { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 } ] ``` You can specify the number of example items to generate in the array. The default is 1. #### Matching JSON values at the root 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(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request for a basic JSON value&quot;) .path(&quot;/hello&quot;) .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### Matching any key in a map 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(&quot;one&quot;) .eachKeyLike(&quot;001&quot;, PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object(&quot;two&quot;) .eachKeyLike(&quot;001-A&quot;) // key like an id where the value is matched by the following example .stringType(&quot;description&quot;, &quot;Some Description&quot;) .closeObject() .closeObject() .object(&quot;three&quot;) .eachKeyMappedToAnArrayLike(&quot;001&quot;) // key like an id mapped to an array where each item is matched by the following example .id(&quot;someId&quot;, 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](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 &quot;pact.matching.wildcard&quot; set to value &quot;true&quot; when the pact file is verified.** #### Combining matching rules with AND/OR Matching rules can be combined with AND/OR. There are two methods available on the DSL for this. For example: ```java DslPart body = new PactDslJsonBody() .numberValue(&quot;valueA&quot;, 100) .and(&quot;valueB&quot;,&quot;AB&quot;, PM.includesStr(&quot;A&quot;), PM.includesStr(&quot;B&quot;)) // Must match both matching rules .or(&quot;valueC&quot;, null, PM.date(), PM.nullValue()) // will match either a valid date or a null value ``` The `and` and `or` methods take a variable number of matchers (varargs). ### Matching on paths 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .matchPath(&quot;/transaction/[0-9]+&quot;) // or .matchPath(&quot;/transaction/[0-9]+&quot;, &quot;/transaction/1234567890&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) ``` ### Matching on headers 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchHeader(&quot;testreqheader&quot;, &quot;test.*value&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .matchHeader(&quot;Location&quot;, &quot;.*/hello/[0-9]+&quot;, &quot;/hello/1234&quot;) ``` ### Matching on query parameters 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchQuery(&quot;a&quot;, &quot;\\d+&quot;, &quot;100&quot;) .matchQuery(&quot;b&quot;, &quot;[A-Z]&quot;, &quot;X&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) ``` ## Debugging pact failures When the test runs, Pact will start a mock provider that will listen for requests and match them against the expectations you setup in `createFragment`. If the request does not match, it will return a 500 error response. Each request received and the generated response is logged using [SLF4J](http://www.slf4j.org/). Just enable debug level logging for au.com.dius.pact.consumer.UnfilteredMockProvider. Most failures tend to be mismatched headers or bodies. ## Changing the directory pact files are written to By default, pact files are written to `target/pacts` (or `build/pacts` if you use Gradle), but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties[&apos;pact.rootDir&apos;] = &quot;$buildDir/custom-pacts-directory&quot; } ``` For maven, use the systemPropertyVariables configuration: ```xml &lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.18&lt;/version&gt; &lt;configuration&gt; &lt;systemPropertyVariables&gt; &lt;pact.rootDir&gt;some/other/directory&lt;/pact.rootDir&gt; &lt;buildDirectory&gt;${project.build.directory}&lt;/buildDirectory&gt; [...] &lt;/systemPropertyVariables&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq(&quot;-Dpact.rootDir=some/other/directory&quot;) ``` ### Using `@PactFolder` annotation You can override the directory the pacts are written in a test by adding the `@PactFolder` annotation to the test class. ## 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`. # Publishing your pact files to a pact broker If you use Gradle, you can use the [pact Gradle plugin](../../provider/pact-jvm-provider-gradle#publishing-pact-files-to-a-pact-broker) to publish your pact files. # Pact Specification V3 Version 3 of the pact specification changes the format of pact files in the following ways: * Query parameters are stored in a map form and are un-encoded (see [#66](https://github.com/DiUS/pact-jvm/issues/66) and [#97](https://github.com/DiUS/pact-jvm/issues/97) for information on what this can cause). * Introduces a new message pact format for testing interactions via a message queue. * Multiple provider states can be defined with data parameters. ## Generating V2 spec pact files To have your consumer tests generate V2 format pacts, you can set the specification version to V2. If you&apos;re using the `ConsumerPactTest` base class, you can override the `getSpecificationVersion` method. For example: ```java @Override protected PactSpecVersion getSpecificationVersion() { return PactSpecVersion.V2; } ``` If you are using the `PactProviderRule`, you can pass the version into the constructor for the rule. ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, PactSpecVersion.V2, this); ``` ## Consumer test for a message consumer For testing a consumer of messages from a message queue, the `MessagePactProviderRule` rule class works in much the same way as the `PactProviderRule` class for Request-Response interactions, but will generate a V3 format message pact file. For an example, look at [ExampleMessageConsumerTest](src/test/java/au/com/dius/pact/consumer/v3%2FExampleMessageConsumerTest.java) # 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 all you to set an expression that will be parsed with the values returned from the provider states: For JSON bodies, use `valueFromProviderState`.&lt;br/&gt; For headers, use `headerFromProviderState`.&lt;br/&gt; For query parameters, use `queryParameterFromProviderState`.&lt;br/&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(&quot;/api/users/${id}&quot;, &quot;/api/users/100&quot;) ``` You can also just use the key instead of an expression: ```java .valueFromProviderState(&apos;userId&apos;, &apos;userId&apos;, 100) // will look value using userId as the key ```

Group: au.com.dius Artifact: pact-jvm-consumer-junit
Show all versions Show documentation Show source 
 

0 downloads
Artifact pact-jvm-consumer-junit
Group au.com.dius
Version 4.0.10
Last update 18. April 2020
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 5
Dependencies pact-jvm-consumer, junit, json, commons-lang3, guava,
There are maybe transitive dependencies!

pact-jvm-consumer-junit_2.11 from group au.com.dius (version 3.5.24)

pact-jvm-consumer-junit ======================= Provides a DSL and a base test class for use with Junit to build consumer tests. ## Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit_2.12` * version-id = `3.5.x` ## Usage ### Using the base ConsumerPactTest To write a pact spec extend ConsumerPactTestMk2. This base class defines the following four methods which must be overridden in your test class. * *providerName:* Returns the name of the API provider that Pact will mock * *consumerName:* Returns the name of the API consumer that we are testing. * *createFragment:* Returns the PactFragment containing the interactions that the test setup using the ConsumerPactBuilder DSL * *runTest:* The actual test run. It receives the URL to the mock server as a parameter. Here is an example: ```java import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.exampleclients.ConsumerClient; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.model.PactFragment; import org.junit.Assert; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ExampleJavaConsumerPactTest extends ConsumerPactTestMk2 { @Override protected RequestResponsePact createFragment(PactDslWithProvider builder) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); return builder .given(&quot;test state&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .headers(headers) .willRespondWith() .status(200) .headers(headers) .body(&quot;{\&quot;responsetest\&quot;: true, \&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .given(&quot;test state 2&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest second test interaction&quot;) .method(&quot;OPTIONS&quot;) .headers(headers) .path(&quot;/second&quot;) .body(&quot;&quot;) .willRespondWith() .status(200) .headers(headers) .body(&quot;&quot;) .toPact(); } @Override protected String providerName() { return &quot;test_provider&quot;; } @Override protected String consumerName() { return &quot;test_consumer&quot;; } @Override protected void runTest(MockServer mockServer) throws IOException { Assert.assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); expectedResponse.put(&quot;name&quot;, &quot;harry&quot;); assertEquals(new ConsumerClient(mockServer.getUrl()).getAsMap(&quot;/&quot;, &quot;&quot;), expectedResponse); assertEquals(new ConsumerClient(mockServer.getUrl()).options(&quot;/second&quot;), 200); } } ``` ### Using the Pact JUnit Rule Thanks to [@warmuuh](https://github.com/warmuuh) we have a JUnit rule that simplifies running Pact consumer tests. To use it, create a test class and then add the rule: #### 1. Add the Pact Rule to your test class to represent your provider. ```java @Rule public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2(&quot;test_provider&quot;, &quot;localhost&quot;, 8080, this); ``` The hostname and port are optional. If left out, it will default to 127.0.0.1 and a random available port. You can get the URL and port from the pact provider rule. #### 2. Annotate a method with Pact that returns a pact fragment for the provider and consumer ```java @Pact(provider=&quot;test_provider&quot;, consumer=&quot;test_consumer&quot;) public RequestResponsePact createPact(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Pact(consumer=&quot;test_consumer&quot;) // will default to the provider name from mockProvider public RequestResponsePact createFragment(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toPact(); } ``` #### 3. Annotate your test method with PactVerification to have it run in the context of the mock server setup with the appropriate pact from step 1 and 2 ```java @Test @PactVerification(&quot;test_provider&quot;) public void runTest() { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(mockProvider.getUrl()).get(&quot;/&quot;), expectedResponse); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Test @PactVerification public void runTest() { // This will run against mockProvider Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(&quot;http://localhost:8080&quot;).get(&quot;/&quot;), expectedResponse); } ``` For an example, have a look at [ExampleJavaConsumerPactRuleTest](src/test/java/au/com/dius/pact/consumer/examples/ExampleJavaConsumerPactRuleTest.java) ### Requiring a test with multiple providers The Pact Rule can be used to test with multiple providers. Just add a rule to the test class for each provider, and then include all the providers required in the `@PactVerification` annotation. For an example, look at [PactMultiProviderTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactMultiProviderTest.java). Note that if more than one provider fails verification for the same test, you will only receive a failure for one of them. Also, to have multiple tests in the same test class, the providers must be setup with random ports (i.e. don&apos;t specify a hostname and port). Also, if the provider name is left out of any of the annotations, the first one found will be used (which may not be the first one defined). ### Requiring the mock server to run with HTTPS [versions 3.2.7/2.4.9+] From versions 3.2.7/2.4.9+ the mock server can be started running with HTTPS using a self-signed certificate instead of HTTP. To enable this set the `https` parameter to `true`. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, PactSpecVersion.V2, this); // ^^^^ ``` For an example test doing this, see [PactProviderHttpsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsTest.java). **NOTE:** The provider will start handling HTTPS requests using a self-signed certificate. Most HTTP clients will not accept connections to a self-signed server as the certificate is untrusted. You may need to enable insecure HTTPS with your client for this test to work. For an example of how to enable insecure HTTPS client connections with Apache Http Client, have a look at [InsecureHttpsRequest](src/test/java/org/apache/http/client/fluent/InsecureHttpsRequest.java). ### Requiring the mock server to run with HTTPS with a keystore [versions 3.4.1+] From versions 3.4.1+ the mock server can be started running with HTTPS using a keystore. To enable this set the `https` parameter to `true`, set the keystore path/file, and the keystore&apos;s password. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, &quot;/path/to/your/keystore.jks&quot;, &quot;your-keystore-password&quot;, PactSpecVersion.V2, this); ``` For an example test doing this, see [PactProviderHttpsKeystoreTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsKeystoreTest.java). ### Setting default expected request and response values [versions 3.5.10+] If you have a lot of tests that may share some values (like headers), you can setup default values that will be applied to all the expected requests and responses for the tests. To do this, you need to create a method that takes single parameter of the appropriate type (`PactDslRequestWithoutPath` or `PactDslResponse`) and annotate it with the default marker annotation (`@DefaultRequestValues` or `@DefaultResponseValues`). For example: ```java @DefaultRequestValues public void defaultRequestValues(PactDslRequestWithoutPath request) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); request.headers(headers); } @DefaultResponseValues public void defaultResponseValues(PactDslResponse response) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testresheader&quot;, &quot;testresheadervalue&quot;); response.headers(headers); } ``` For an example test that uses these, have a look at [PactProviderWithMultipleFragmentsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderWithMultipleFragmentsTest.java) ### Note on HTTP clients and persistent connections Some HTTP clients may keep the connection open, based on the live connections settings or if they use a connection cache. This could cause your tests to fail if the client you are testing lives longer than an individual test, as the mock server will be started and shutdown for each test. This will result in the HTTP client connection cache having invalid connections. For an example of this where the there was a failure for every second test, see [Issue #342](https://github.com/DiUS/pact-jvm/issues/342). ### Using the Pact DSL directly Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. The DSL can be used directly in this case. Example: ```java import au.com.dius.pact.consumer.ConsumerPactBuilder; import au.com.dius.pact.consumer.PactVerificationResult; import au.com.dius.pact.consumer.exampleclients.ProviderClient; import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.RequestResponsePact; 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; /** * Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. * The DSL can be used directly in this case. */ public class DirectDSLConsumerPactTest { @Test public void testPact() { RequestResponsePact pact = ConsumerPactBuilder .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request to say Hello&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .toPact(); MockProviderConfig config = MockProviderConfig.createDefault(); PactVerificationResult result = runConsumerTest(pact, config, mockServer -&gt; { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;hello&quot;, &quot;harry&quot;); try { assertEquals(new ProviderClient(mockServer.getUrl()).hello(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;), expectedResponse); } catch (IOException e) { throw new RuntimeException(e); } }); if (result instanceof PactVerificationResult.Error) { throw new RuntimeException(((PactVerificationResult.Error)result).getError()); } assertEquals(PactVerificationResult.Ok.INSTANCE, result); } } ``` ### The Pact JUnit DSL The DSL has the following pattern: ```java .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .given(&quot;a certain state on the provider&quot;) .uponReceiving(&quot;a request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .uponReceiving(&quot;another request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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 **NOTE:** If you are using Java 8, there is [an updated DSL for consumer tests](../pact-jvm-consumer-java8). 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(&quot;name&quot;) .booleanType(&quot;happy&quot;) .hexValue(&quot;hexCode&quot;) .id() .ipAddress(&quot;localAddress&quot;) .numberValue(&quot;age&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(&quot;users&quot;, 1) .id() .stringType(&quot;name&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. __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. ```java DslPart body = new PactDslJsonBody() .minArrayLike(&quot;users&quot;, 1, 2) .id() .stringType(&quot;name&quot;) .closeObject() .closeArray(); ``` This will generate the example body with 2 items in the users list. #### 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(&quot;clearedDate&quot;, &quot;mm/dd/yyyy&quot;, date) .stringType(&quot;status&quot;, &quot;STATUS&quot;) .decimalType(&quot;amount&quot;, 100.0) .closeObject() ``` This will then match a body like: ```json [ { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 } ] ``` __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. #### 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(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request for a basic JSON value&quot;) .path(&quot;/hello&quot;) .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### 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(&quot;one&quot;) .eachKeyLike(&quot;001&quot;, PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object(&quot;two&quot;) .eachKeyLike(&quot;001-A&quot;) // key like an id where the value is matched by the following example .stringType(&quot;description&quot;, &quot;Some Description&quot;) .closeObject() .closeObject() .object(&quot;three&quot;) .eachKeyMappedToAnArrayLike(&quot;001&quot;) // key like an id mapped to an array where each item is matched by the following example .id(&quot;someId&quot;, 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](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 &quot;pact.matching.wildcard&quot; set to value &quot;true&quot; when the pact file is verified.** #### Combining matching rules with AND/OR Matching rules can be combined with AND/OR. There are two methods available on the DSL for this. For example: ```java DslPart body = new PactDslJsonBody() .numberValue(&quot;valueA&quot;, 100) .and(&quot;valueB&quot;,&quot;AB&quot;, PM.includesStr(&quot;A&quot;), PM.includesStr(&quot;B&quot;)) // Must match both matching rules .or(&quot;valueC&quot;, null, PM.date(), PM.nullValue()) // will match either a valid date or a null value ``` The `and` and `or` methods take a variable number of matchers (varargs). ### 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .matchPath(&quot;/transaction/[0-9]+&quot;) // or .matchPath(&quot;/transaction/[0-9]+&quot;, &quot;/transaction/1234567890&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchHeader(&quot;testreqheader&quot;, &quot;test.*value&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .matchHeader(&quot;Location&quot;, &quot;.*/hello/[0-9]+&quot;, &quot;/hello/1234&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchQuery(&quot;a&quot;, &quot;\\d+&quot;, &quot;100&quot;) .matchQuery(&quot;b&quot;, &quot;[A-Z]&quot;, &quot;X&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) ``` ## Debugging pact failures When the test runs, Pact will start a mock provider that will listen for requests and match them against the expectations you setup in `createFragment`. If the request does not match, it will return a 500 error response. Each request received and the generated response is logged using [SLF4J](http://www.slf4j.org/). Just enable debug level logging for au.com.dius.pact.consumer.UnfilteredMockProvider. Most failures tend to be mismatched headers or bodies. ## Changing the directory pact files are written to (2.1.9+) By default, pact files are written to `target/pacts`, but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties[&apos;pact.rootDir&apos;] = &quot;$buildDir/pacts&quot; } ``` For maven, use the systemPropertyVariables configuration: ```xml &lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.18&lt;/version&gt; &lt;configuration&gt; &lt;systemPropertyVariables&gt; &lt;pact.rootDir&gt;some/other/directory&lt;/pact.rootDir&gt; &lt;buildDirectory&gt;${project.build.directory}&lt;/buildDirectory&gt; [...] &lt;/systemPropertyVariables&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq(&quot;-Dpact.rootDir=some/other/directory&quot;) ``` # Publishing your pact files to a pact broker If you use Gradle, you can use the [pact Gradle plugin](https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-provider-gradle#publishing-pact-files-to-a-pact-broker) to publish your pact files. # Pact Specification V3 Version 3 of the pact specification changes the format of pact files in the following ways: * Query parameters are stored in a map form and are un-encoded (see [#66](https://github.com/DiUS/pact-jvm/issues/66) and [#97](https://github.com/DiUS/pact-jvm/issues/97) for information on what this can cause). * Introduces a new message pact format for testing interactions via a message queue. * Multiple provider states can be defined with data parameters. ## Generating V2 spec pact files (3.1.0+, 2.3.0+) To have your consumer tests generate V2 format pacts, you can set the specification version to V2. If you&apos;re using the `ConsumerPactTest` base class, you can override the `getSpecificationVersion` method. For example: ```java @Override protected PactSpecVersion getSpecificationVersion() { return PactSpecVersion.V2; } ``` If you are using the `PactProviderRuleMk2`, you can pass the version into the constructor for the rule. ```java @Rule public PactProviderRuleMk2 mockTestProvider = new PactProviderRuleMk2(&quot;test_provider&quot;, PactSpecVersion.V2, this); ``` ## Consumer test for a message consumer For testing a consumer of messages from a message queue, the `MessagePactProviderRule` rule class works in much the same way as the `PactProviderRule` class for Request-Response interactions, but will generate a V3 format message pact file. For an example, look at [ExampleMessageConsumerTest](https://github.com/DiUS/pact-jvm/blob/master/pact-jvm-consumer-junit%2Fsrc%2Ftest%2Fjava%2Fau%2Fcom%2Fdius%2Fpact%2Fconsumer%2Fv3%2FExampleMessageConsumerTest.java)

Group: au.com.dius Artifact: pact-jvm-consumer-junit_2.11
Show all versions Show documentation Show source 
 

22 downloads
Artifact pact-jvm-consumer-junit_2.11
Group au.com.dius
Version 3.5.24
Last update 04. November 2018
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 12
Dependencies kotlin-stdlib-jdk8, kotlin-reflect, slf4j-api, groovy-all, kotlin-logging, scala-library, scala-logging_2.11, pact-jvm-consumer_2.11, junit, json, commons-lang3, guava,
There are maybe transitive dependencies!

pact-jvm-consumer-junit_2.10 from group au.com.dius (version 2.4.20)

pact-jvm-consumer-junit ======================= Provides a DSL and a base test class for use with Junit to build consumer tests. ##Dependency The library is available on maven central using: * group-id = `au.com.dius` * artifact-id = `pact-jvm-consumer-junit_2.11` * version-id = `3.0.x` ##Usage ### Using the base ConsumerPactTest To write a pact spec extend ConsumerPactTestMk2. This base class defines the following four methods which must be overridden in your test class. * *providerName:* Returns the name of the API provider that Pact will mock * *consumerName:* Returns the name of the API consumer that we are testing. * *createFragment:* Returns the PactFragment containing the interactions that the test setup using the ConsumerPactBuilder DSL * *runTest:* The actual test run. It receives the URL to the mock server as a parameter. Here is an example: ```java import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.consumer.exampleclients.ConsumerClient; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.model.PactFragment; import org.junit.Assert; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class ExampleJavaConsumerPactTest extends ConsumerPactTest { @Override protected PactFragment createFragment(PactDslWithProvider builder) { Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(&quot;testreqheader&quot;, &quot;testreqheadervalue&quot;); return builder .given(&quot;test state&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .headers(headers) .willRespondWith() .status(200) .headers(headers) .body(&quot;{\&quot;responsetest\&quot;: true, \&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .given(&quot;test state 2&quot;) // NOTE: Using provider states are optional, you can leave it out .uponReceiving(&quot;ExampleJavaConsumerPactTest second test interaction&quot;) .method(&quot;OPTIONS&quot;) .headers(headers) .path(&quot;/second&quot;) .body(&quot;&quot;) .willRespondWith() .status(200) .headers(headers) .body(&quot;&quot;) .toFragment(); } @Override protected String providerName() { return &quot;test_provider&quot;; } @Override protected String consumerName() { return &quot;test_consumer&quot;; } @Override protected void runTest(String url) throws IOException { Assert.assertEquals(new ConsumerClient(url).options(&quot;/second&quot;), 200); Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); expectedResponse.put(&quot;name&quot;, &quot;harry&quot;); assertEquals(new ConsumerClient(url).getAsMap(&quot;/&quot;, &quot;&quot;), expectedResponse); assertEquals(new ConsumerClient(url).options(&quot;/second&quot;), 200); } } ``` ### Using the Pact JUnit Rule Thanks to [@warmuuh](https://github.com/warmuuh) we have a JUnit rule that simplifies running Pact consumer tests. To use it, create a test class and then add the rule: #### 1. Add the Pact Rule to your test class to represent your provider. ```java @Rule public PactProviderRule mockProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8080, this); ``` The hostname and port are optional. If left out, it will default to localhost and a random available port. #### 2. Annotate a method with Pact that returns a pact fragment for the provider and consumer ```java @Pact(provider=&quot;test_provider&quot;, consumer=&quot;test_consumer&quot;) public PactFragment createFragment(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toFragment(); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Pact(consumer=&quot;test_consumer&quot;) // will default to the provider name from mockProvider public PactFragment createFragment(PactDslWithProvider builder) { return builder .given(&quot;test state&quot;) .uponReceiving(&quot;ExampleJavaConsumerPactRuleTest test interaction&quot;) .path(&quot;/&quot;) .method(&quot;GET&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;responsetest\&quot;: true}&quot;) .toFragment(); } ``` #### 3. Annotate your test method with PactVerification to have it run in the context of the mock server setup with the appropriate pact from step 1 and 2 ```java @Test @PactVerification(&quot;test_provider&quot;) public void runTest() { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(&quot;http://localhost:8080&quot;).get(&quot;/&quot;), expectedResponse); } ``` ##### Versions 3.0.2/2.2.13+ You can leave the provider name out. It will then use the provider name of the first mock provider found. I.e., ```java @Test @PactVerification public void runTest() { // This will run against mockProvider Map expectedResponse = new HashMap(); expectedResponse.put(&quot;responsetest&quot;, true); assertEquals(new ConsumerClient(&quot;http://localhost:8080&quot;).get(&quot;/&quot;), expectedResponse); } ``` For an example, have a look at [ExampleJavaConsumerPactRuleTest](src/test/java/au/com/dius/pact/consumer/examples/ExampleJavaConsumerPactRuleTest.java) ### Requiring a test with multiple providers The Pact Rule can be used to test with multiple providers. Just add a rule to the test class for each provider, and then include all the providers required in the `@PactVerification` annotation. For an example, look at [PactMultiProviderTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactMultiProviderTest.java). Note that if more than one provider fails verification for the same test, you will only receive a failure for one of them. Also, to have multiple tests in the same test class, the providers must be setup with random ports (i.e. don&apos;t specify a hostname and port). Also, if the provider name is left out of any of the annotations, the first one found will be used (which may not be the first one defined). ### Requiring the mock server to run with HTTPS [versions 3.2.7/2.4.9+] From versions 3.2.7/2.4.9+ the mock server can be started running with HTTPS using a self-signed certificate instead of HTTP. To enable this set the `https` parameter to `true`. E.g.: ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, &quot;localhost&quot;, 8443, true, PactConfig.apply(PactSpecVersion.V2), this); // ^^^^ ``` For an exmaple test doing this, see [PactProviderHttpsTest](src/test/java/au/com/dius/pact/consumer/pactproviderrule/PactProviderHttpsTest.java). **NOTE:** The provider will start handling HTTPS requests using a self-signed certificate. Most HTTP clients will not accept connections to a self-signed server as the certificate is untrusted. You may need to enable insecure HTTPS with your client for this test to work. For an example of how to enable insecure HTTPS client connections with Apache Http Client, have a look at [InsecureHttpsRequest](src/test/java/org/apache/http/client/fluent/InsecureHttpsRequest.java). ### Using the Pact DSL directly Sometimes it is not convenient to use the ConsumerPactTest as it only allows one test per test class. The DSL can be used directly in this case. Example: ```java import au.com.dius.pact.consumer.ConsumerPactBuilder; import au.com.dius.pact.consumer.ConsumerPactTest; import au.com.dius.pact.consumer.PactError; import au.com.dius.pact.consumer.TestRun; import au.com.dius.pact.consumer.VerificationResult; import au.com.dius.pact.consumer.examples.client.ProviderClient; import au.com.dius.pact.model.MockProviderConfig; import au.com.dius.pact.model.PactFragment; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class PactTest { @Test public void testPact() { PactFragment pactFragment = ConsumerPactBuilder .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request to say Hello&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .toFragment(); MockProviderConfig config = MockProviderConfig.createDefault(); VerificationResult result = pactFragment.runConsumer(config, new TestRun() { @Override public void run(MockProviderConfig config) { Map expectedResponse = new HashMap(); expectedResponse.put(&quot;hello&quot;, &quot;harry&quot;); try { assertEquals(new ProviderClient(config.url()).hello(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;), expectedResponse); } catch (IOException e) { throw new RuntimeException(e); } } }); if (result instanceof PactError) { throw new RuntimeException(((PactError)result).error()); } assertEquals(ConsumerPactTest.PACT_VERIFIED, result); } } ``` ### The Pact JUnit DSL The DSL has the following pattern: ```java .consumer(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .given(&quot;a certain state on the provider&quot;) .uponReceiving(&quot;a request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .uponReceiving(&quot;another request for something&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) . . . .toFragment() ``` 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(&quot;name&quot;) .booleanType(&quot;happy&quot;) .hexValue(&quot;hexCode&quot;) .id() .ipAddress(&quot;localAddress&quot;) .numberValue(&quot;age&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 | _\* 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(&quot;users&quot;, 1) .id() .stringType(&quot;name&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. __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. ```java DslPart body = new PactDslJsonBody() .minArrayLike(&quot;users&quot;, 1, 2) .id() .stringType(&quot;name&quot;) .closeObject() .closeArray(); ``` This will generate the example body with 2 items in the users list. #### 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(&quot;clearedDate&quot;, &quot;mm/dd/yyyy&quot;, date) .stringType(&quot;status&quot;, &quot;STATUS&quot;) .decimalType(&quot;amount&quot;, 100.0) .closeObject() ``` This will then match a body like: ```json [ { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 }, { &quot;clearedDate&quot; : &quot;07/22/2015&quot;, &quot;status&quot; : &quot;C&quot;, &quot;amount&quot; : 15.0 } ] ``` __Version 3.2.4/2.4.6+__ You can specify the number of example items to generate in the array. The default is 1. #### 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(&quot;Some Consumer&quot;) .hasPactWith(&quot;Some Provider&quot;) .uponReceiving(&quot;a request for a basic JSON value&quot;) .path(&quot;/hello&quot;) .willRespondWith() .status(200) .body(PactDslJsonRootValue.integerType()) ``` #### 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(&quot;one&quot;) .eachKeyLike(&quot;001&quot;, PactDslJsonRootValue.id(12345L)) // key like an id mapped to a matcher .closeObject() .object(&quot;two&quot;) .eachKeyLike(&quot;001-A&quot;) // key like an id where the value is matched by the following example .stringType(&quot;description&quot;, &quot;Some Description&quot;) .closeObject() .closeObject() .object(&quot;three&quot;) .eachKeyMappedToAnArrayLike(&quot;001&quot;) // key like an id mapped to an array where each item is matched by the following example .id(&quot;someId&quot;, 23456L) .closeObject() .closeArray() .closeObject(); ``` For an example, have a look at [WildcardKeysTest](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). ### 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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .matchPath(&quot;/transaction/[0-9]+&quot;) // or .matchPath(&quot;/transaction/[0-9]+&quot;, &quot;/transaction/1234567890&quot;) .method(&quot;POST&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchHeader(&quot;testreqheader&quot;, &quot;test.*value&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) .matchHeader(&quot;Location&quot;, &quot;.*/hello/[0-9]+&quot;, &quot;/hello/1234&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(&quot;test state&quot;) .uponReceiving(&quot;a test interaction&quot;) .path(&quot;/hello&quot;) .method(&quot;POST&quot;) .matchQuery(&quot;a&quot;, &quot;\\d+&quot;, &quot;100&quot;) .matchQuery(&quot;b&quot;, &quot;[A-Z]&quot;, &quot;X&quot;) .body(&quot;{\&quot;name\&quot;: \&quot;harry\&quot;}&quot;) .willRespondWith() .status(200) .body(&quot;{\&quot;hello\&quot;: \&quot;harry\&quot;}&quot;) ``` ## Debugging pact failures When the test runs, Pact will start a mock provider that will listen for requests and match them against the expectations you setup in `createFragment`. If the request does not match, it will return a 500 error response. Each request received and the generated response is logged using [SLF4J](http://www.slf4j.org/). Just enable debug level logging for au.com.dius.pact.consumer.UnfilteredMockProvider. Most failures tend to be mismatched headers or bodies. ## Changing the directory pact files are written to (2.1.9+) By default, pact files are written to `target/pacts`, but this can be overwritten with the `pact.rootDir` system property. This property needs to be set on the test JVM as most build tools will fork a new JVM to run the tests. For Gradle, add this to your build.gradle: ```groovy test { systemProperties[&apos;pact.rootDir&apos;] = &quot;$buildDir/pacts&quot; } ``` For maven, use the systemPropertyVariables configuration: ```xml &lt;project&gt; [...] &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.18&lt;/version&gt; &lt;configuration&gt; &lt;systemPropertyVariables&gt; &lt;pact.rootDir&gt;some/other/directory&lt;/pact.rootDir&gt; &lt;buildDirectory&gt;${project.build.directory}&lt;/buildDirectory&gt; [...] &lt;/systemPropertyVariables&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; [...] &lt;/project&gt; ``` For SBT: ```scala fork in Test := true, javaOptions in Test := Seq(&quot;-Dpact.rootDir=some/other/directory&quot;) ``` # Publishing your pact files to a pact broker If you use Gradle, you can use the [pact Gradle plugin](https://github.com/DiUS/pact-jvm/tree/master/pact-jvm-provider-gradle#publishing-pact-files-to-a-pact-broker) to publish your pact files. # Pact Specification V3 Version 3 of the pact specification changes the format of pact files in the following ways: * Query parameters are stored in a map form and are un-encoded (see [#66](https://github.com/DiUS/pact-jvm/issues/66) and [#97](https://github.com/DiUS/pact-jvm/issues/97) for information on what this can cause). * Introduces a new message pact format for testing interactions via a message queue. ## Generating V3 spec pact files (3.1.0+, 2.3.0+) To have your consumer tests generate V3 format pacts, you can set the specification version to V3. If you&apos;re using the `ConsumerPactTest` base class, you can override the `getSpecificationVersion` method. For example: ```java @Override protected PactSpecVersion getSpecificationVersion() { return PactSpecVersion.V3; } ``` If you are using the `PactProviderRule`, you can pass the version into the constructor for the rule. ```java @Rule public PactProviderRule mockTestProvider = new PactProviderRule(&quot;test_provider&quot;, PactSpecVersion.V3, this); ``` ## Consumer test for a message consumer For testing a consumer of messages from a message queue, the `MessagePactProviderRule` rule class works in much the same way as the `PactProviderRule` class for Request-Response interactions, but will generate a V3 format message pact file. For an example, look at [ExampleMessageConsumerTest](https://github.com/DiUS/pact-jvm/blob/master/pact-jvm-consumer-junit%2Fsrc%2Ftest%2Fjava%2Fau%2Fcom%2Fdius%2Fpact%2Fconsumer%2Fv3%2FExampleMessageConsumerTest.java)

Group: au.com.dius Artifact: pact-jvm-consumer-junit_2.10
Show all versions Show documentation Show source 
 

5 downloads
Artifact pact-jvm-consumer-junit_2.10
Group au.com.dius
Version 2.4.20
Last update 14. April 2018
Organization not specified
URL https://github.com/DiUS/pact-jvm
License Apache 2
Dependencies amount 7
Dependencies slf4j-api, scala-library, pact-jvm-consumer_2.10, junit, json, commons-lang3, guava,
There are maybe transitive dependencies!



Page 76 from 76 (items total 758)


© 2015 - 2024 Weber Informatics LLC | Privacy Policy