diff --git a/reference/html/README.html b/reference/html/README.html new file mode 100644 index 0000000000..3dfbe5ed6d --- /dev/null +++ b/reference/html/README.html @@ -0,0 +1,673 @@ + + + + + + + +Spring Cloud Contract + + + + + + + + + + +
+
+
+
+
+Gitter +
+
+
+
+codecov +
+
+
+
+CircleCI +
+
+
+
+
+

Spring Cloud Contract

+
+
+

You always need confidence when pushing new features into a new application or service in +a distributed system. To that end, this project provides support for Consumer-driven +Contracts and service schemas in Spring applications, covering a range of options for +writing tests, publishing them as assets, and asserting that a contract is kept by +producers and consumers — for both HTTP and message-based interactions.

+
+
+

Spring Cloud Contract workshops

+
+

If you prefer to learn about the project by doing some tutorials, you can check out the +workshops under +this link.

+
+
+
+
+
+

Documentation

+
+
+

You can read more about Spring Cloud Contract Verifier by reading the +{documentation_url}[docs]

+
+
+
+
+

Contributing

+
+
+

Spring Cloud is released under the non-restrictive Apache 2.0 license, +and follows a very standard Github development process, using Github +tracker for issues and merging pull requests into master. If you want +to contribute even something trivial please do not hesitate, but +follow the guidelines below.

+
+
+

Sign the Contributor License Agreement

+
+

Before we accept a non-trivial patch or pull request we will need you to sign the +Contributor License Agreement. +Signing the contributor’s agreement does not grant anyone commit rights to the main +repository, but it does mean that we can accept your contributions, and you will get an +author credit if we do. Active contributors might be asked to join the core team, and +given the ability to merge pull requests.

+
+
+
+

Code of Conduct

+
+

This project adheres to the Contributor Covenant code of +conduct. By participating, you are expected to uphold this code. Please report +unacceptable behavior to spring-code-of-conduct@pivotal.io.

+
+
+
+

Code Conventions and Housekeeping

+
+

None of these is essential for a pull request, but they will all help. They can also be +added after the original pull request but before a merge.

+
+
+
    +
  • +

    Use the Spring Framework code format conventions. If you use Eclipse +you can import formatter settings using the +eclipse-code-formatter.xml file from the +Spring +Cloud Build project. If using IntelliJ, you can use the +Eclipse Code Formatter +Plugin to import the same file.

    +
  • +
  • +

    Make sure all new .java files to have a simple Javadoc class comment with at least an +@author tag identifying you, and preferably at least a paragraph on what the class is +for.

    +
  • +
  • +

    Add the ASF license header comment to all new .java files (copy from existing files +in the project)

    +
  • +
  • +

    Add yourself as an @author to the .java files that you modify substantially (more +than cosmetic changes).

    +
  • +
  • +

    Add some Javadocs and, if you change the namespace, some XSD doc elements.

    +
  • +
  • +

    A few unit tests would help a lot as well — someone has to do it.

    +
  • +
  • +

    If no-one else is using your branch, please rebase it against the current master (or +other target branch in the main project).

    +
  • +
  • +

    When writing a commit message please follow these conventions, +if you are fixing an existing issue please add Fixes gh-XXXX at the end of the commit +message (where XXXX is the issue number).

    +
  • +
+
+
+
+

Checkstyle

+
+

Spring Cloud Build comes with a set of checkstyle rules. You can find them in the spring-cloud-build-tools module. The most notable files under the module are:

+
+
+
spring-cloud-build-tools/
+
+
└── src
+    ├── checkstyle
+    │   └── checkstyle-suppressions.xml (3)
+    └── main
+        └── resources
+            ├── checkstyle-header.txt (2)
+            └── checkstyle.xml (1)
+
+
+
+ + + + + + + + + + + + + +
1Default Checkstyle rules
2File header setup
3Default suppression rules
+
+
+

Checkstyle configuration

+
+

Checkstyle rules are disabled by default. To add checkstyle to your project just define the following properties and plugins.

+
+
+
pom.xml
+
+
<properties>
+<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError> (1)
+        <maven-checkstyle-plugin.failsOnViolation>true
+        </maven-checkstyle-plugin.failsOnViolation> (2)
+        <maven-checkstyle-plugin.includeTestSourceDirectory>true
+        </maven-checkstyle-plugin.includeTestSourceDirectory> (3)
+</properties>
+
+<build>
+        <plugins>
+            <plugin> (4)
+                <groupId>io.spring.javaformat</groupId>
+                <artifactId>spring-javaformat-maven-plugin</artifactId>
+            </plugin>
+            <plugin> (5)
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+            </plugin>
+        </plugins>
+
+    <reporting>
+        <plugins>
+            <plugin> (5)
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </reporting>
+</build>
+
+
+
+ + + + + + + + + + + + + + + + + + + + + +
1Fails the build upon Checkstyle errors
2Fails the build upon Checkstyle violations
3Checkstyle analyzes also the test sources
4Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules
5Add checkstyle plugin to your build and reporting phases
+
+
+

If you need to suppress some rules (e.g. line length needs to be longer), then it’s enough for you to define a file under ${project.root}/src/checkstyle/checkstyle-suppressions.xml with your suppressions. Example:

+
+
+
projectRoot/src/checkstyle/checkstyle-suppresions.xml
+
+
<?xml version="1.0"?>
+<!DOCTYPE suppressions PUBLIC
+		"-//Puppy Crawl//DTD Suppressions 1.1//EN"
+		"https://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
+<suppressions>
+	<suppress files=".*ConfigServerApplication\.java" checks="HideUtilityClassConstructor"/>
+	<suppress files=".*ConfigClientWatch\.java" checks="LineLengthCheck"/>
+</suppressions>
+
+
+
+

It’s advisable to copy the ${spring-cloud-build.rootFolder}/.editorconfig and ${spring-cloud-build.rootFolder}/.springformat to your project. That way, some default formatting rules will be applied. You can do so by running this script:

+
+
+
+
$ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig
+$ touch .springformat
+
+
+
+
+
+

IDE setup

+
+

Intellij IDEA

+
+

In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. +The following files can be found in the Spring Cloud Build project.

+
+
+
spring-cloud-build-tools/
+
+
└── src
+    ├── checkstyle
+    │   └── checkstyle-suppressions.xml (3)
+    └── main
+        └── resources
+            ├── checkstyle-header.txt (2)
+            ├── checkstyle.xml (1)
+            └── intellij
+                ├── Intellij_Project_Defaults.xml (4)
+                └── Intellij_Spring_Boot_Java_Conventions.xml (5)
+
+
+
+ + + + + + + + + + + + + + + + + + + + + +
1Default Checkstyle rules
2File header setup
3Default suppression rules
4Project defaults for Intellij that apply most of Checkstyle rules
5Project style conventions for Intellij that apply most of Checkstyle rules
+
+
+
+Code style +
+
Figure 1. Code style
+
+
+

Go to FileSettingsEditorCode style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file.

+
+
+
+Code style +
+
Figure 2. Inspection profiles
+
+
+

Go to FileSettingsEditorInspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file.

+
+
+
Checkstyle
+

To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions

+
+
+
+Checkstyle +
+
+
+

Go to FileSettingsOther settingsCheckstyle. There click on the + icon in the Configuration file section. There, you’ll have to define where the checkstyle rules should be picked from. In the image above, we’ve picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build’s GitHub repository (e.g. for the checkstyle.xml : https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml). We need to provide the following variables:

+
+
+ +
+
+ + + + + +
+ + +Remember to set the Scan Scope to All sources since we apply checkstyle rules for production and test sources. +
+
+
+
+
+
+
+

How to build it

+
+
+ + + + + +
+ + +You need to have all the necessary Groovy plugins + installed for your IDE to properly resolve the sources. For example in + Intellij IDEA having both Eclipse Groovy Compiler Plugin & GMavenPlus Intellij Plugin + results in properly imported project. +
+
+
+ + + + + +
+ + +Spring Cloud Contract builds Docker images. Remember to +have Docker installed. +
+
+
+ + + + + +
+ + +If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed. +
+
+
+

Project structure

+
+

Here you can find the Spring Cloud Contract folder structure

+
+
+
+
├── config
+├── docker
+├── samples
+├── scripts
+├── specs
+├── spring-cloud-contract-dependencies
+├── spring-cloud-contract-shade
+├── spring-cloud-contract-starters
+├── spring-cloud-contract-stub-runner
+├── spring-cloud-contract-stub-runner-boot
+├── spring-cloud-contract-tools
+├── spring-cloud-contract-verifier
+├── spring-cloud-contract-wiremock
+└── tests
+
+
+
+
    +
  • +

    config - folder contains setup for Spring Cloud Release Tools automated release process

    +
  • +
  • +

    docker - folder contains docker images

    +
  • +
  • +

    samples - folder contains test samples together with standalone ones used also to build documentation

    +
  • +
  • +

    scripts - contains scripts to build and test Spring Cloud Contract with Maven, Gradle and standalone projects

    +
  • +
  • +

    specs - contains specifications for the Contract DSL.

    +
  • +
  • +

    spring-cloud-contract-dependencies - contains Spring Cloud Contract BOM

    +
  • +
  • +

    spring-cloud-contract-shade - shaded dependencies used by the plugins

    +
  • +
  • +

    spring-cloud-contract-starters - contains Spring Cloud Contract Starters

    +
  • +
  • +

    spring-cloud-contract-spec - contains specification modules (contains concept of a Contract)

    +
  • +
  • +

    spring-cloud-contract-stub-runner - contains Stub Runner related modules

    +
  • +
  • +

    spring-cloud-contract-stub-runner-boot - contains Stub Runner Boot app

    +
  • +
  • +

    spring-cloud-contract-tools - Gradle and Maven plugin for Spring Cloud Contract Verifier

    +
  • +
  • +

    spring-cloud-contract-verifier - core of the Spring Cloud Contract Verifier functionality

    +
  • +
  • +

    spring-cloud-contract-wiremock - all WireMock related functionality

    +
  • +
  • +

    tests - integration tests for different messaging technologies

    +
  • +
+
+
+
+

Commands

+
+

To build the core functionality together with Maven Plugin you can run

+
+
+
+
./mvnw clean install -P integration
+
+
+
+

Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the +standalone samples in proper order (both for Maven and Gradle).

+
+
+

To build the Gradle Plugin only

+
+
+
+
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
+./gradlew clean build
+
+
+
+
+

Helpful scripts

+
+

We’re providing a couple of helpful scripts to build the project.

+
+
+

To build the project in parallel (by default uses 4 cores but you can change it)

+
+
+
+
./scripts/parallelBuild.sh
+
+
+
+

and with 8 cores

+
+
+
+
CORES=8 ./scripts/parallelBuild.sh
+
+
+
+

To build the project without any integration tests (by default uses 1 core)

+
+
+
+
./scripts/noIntegration.sh
+
+
+
+

and with 8 cores

+
+
+
+
CORES=8 ./scripts/noIntegration.sh
+
+
+
+

To generate the documentation (both the root one and the maven plugin one)

+
+
+
+
./scripts/generateDocs.sh
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/building.html b/reference/html/building.html new file mode 100644 index 0000000000..1b9649c385 --- /dev/null +++ b/reference/html/building.html @@ -0,0 +1,304 @@ + + + + + + + +How to build it + + + + + + + + + + +
+
+

How to build it

+
+
+ + + + + +
+ + +You need to have all the necessary Groovy plugins + installed for your IDE to properly resolve the sources. For example in + Intellij IDEA having both Eclipse Groovy Compiler Plugin & GMavenPlus Intellij Plugin + results in properly imported project. +
+
+
+ + + + + +
+ + +Spring Cloud Contract builds Docker images. Remember to +have Docker installed. +
+
+
+ + + + + +
+ + +If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed. +
+
+
+

Project structure

+
+

Here you can find the Spring Cloud Contract folder structure

+
+
+
+
├── config
+├── docker
+├── samples
+├── scripts
+├── specs
+├── spring-cloud-contract-dependencies
+├── spring-cloud-contract-shade
+├── spring-cloud-contract-starters
+├── spring-cloud-contract-stub-runner
+├── spring-cloud-contract-stub-runner-boot
+├── spring-cloud-contract-tools
+├── spring-cloud-contract-verifier
+├── spring-cloud-contract-wiremock
+└── tests
+
+
+
+
    +
  • +

    config - folder contains setup for Spring Cloud Release Tools automated release process

    +
  • +
  • +

    docker - folder contains docker images

    +
  • +
  • +

    samples - folder contains test samples together with standalone ones used also to build documentation

    +
  • +
  • +

    scripts - contains scripts to build and test Spring Cloud Contract with Maven, Gradle and standalone projects

    +
  • +
  • +

    specs - contains specifications for the Contract DSL.

    +
  • +
  • +

    spring-cloud-contract-dependencies - contains Spring Cloud Contract BOM

    +
  • +
  • +

    spring-cloud-contract-shade - shaded dependencies used by the plugins

    +
  • +
  • +

    spring-cloud-contract-starters - contains Spring Cloud Contract Starters

    +
  • +
  • +

    spring-cloud-contract-spec - contains specification modules (contains concept of a Contract)

    +
  • +
  • +

    spring-cloud-contract-stub-runner - contains Stub Runner related modules

    +
  • +
  • +

    spring-cloud-contract-stub-runner-boot - contains Stub Runner Boot app

    +
  • +
  • +

    spring-cloud-contract-tools - Gradle and Maven plugin for Spring Cloud Contract Verifier

    +
  • +
  • +

    spring-cloud-contract-verifier - core of the Spring Cloud Contract Verifier functionality

    +
  • +
  • +

    spring-cloud-contract-wiremock - all WireMock related functionality

    +
  • +
  • +

    tests - integration tests for different messaging technologies

    +
  • +
+
+
+
+

Commands

+
+

To build the core functionality together with Maven Plugin you can run

+
+
+
+
./mvnw clean install -P integration
+
+
+
+

Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the +standalone samples in proper order (both for Maven and Gradle).

+
+
+

To build the Gradle Plugin only

+
+
+
+
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
+./gradlew clean build
+
+
+
+
+

Helpful scripts

+
+

We’re providing a couple of helpful scripts to build the project.

+
+
+

To build the project in parallel (by default uses 4 cores but you can change it)

+
+
+
+
./scripts/parallelBuild.sh
+
+
+
+

and with 8 cores

+
+
+
+
CORES=8 ./scripts/parallelBuild.sh
+
+
+
+

To build the project without any integration tests (by default uses 1 core)

+
+
+
+
./scripts/noIntegration.sh
+
+
+
+

and with 8 cores

+
+
+
+
CORES=8 ./scripts/noIntegration.sh
+
+
+
+

To generate the documentation (both the root one and the maven plugin one)

+
+
+
+
./scripts/generateDocs.sh
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/css/spring.css b/reference/html/css/spring.css new file mode 100644 index 0000000000..40821db3cd --- /dev/null +++ b/reference/html/css/spring.css @@ -0,0 +1 @@ +@import url("https://fonts.googleapis.com/css?family=Karla:400,700|Montserrat:400,700");/*! normalize.css v2.1.2 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden],template{display:none}script{display:none !important}html,body{font-size:100%}html{font-family:Karla, sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}body{background:white;color:#000;padding:0;margin:0;font-size:16px;font-family:Karla, sans-serif;font-weight:normal;font-style:normal;line-height:1.6em;position:relative;cursor:auto}a:hover{cursor:pointer}img,object,embed{max-width:100%;height:auto}object,embed{height:100%}img{-ms-interpolation-mode:bicubic}#map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none !important}.left{float:left !important}.right{float:right !important}.text-left{text-align:left !important}.text-right{text-align:right !important}.text-center{text-align:center !important}.text-justify{text-align:justify !important}.hide{display:none}.antialiased{-webkit-font-smoothing:antialiased}img{display:inline-block;vertical-align:middle}textarea{height:auto;min-height:50px}select{width:100%}object,svg{display:inline-block;vertical-align:middle}.center{margin-left:auto;margin-right:auto}.spread{width:100%}p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{line-height:1.6}.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#0b0a0a;font-weight:bold;margin-top:0;margin-bottom:0.8em}div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}a{color:#097dff;line-height:inherit;text-decoration:none}a:hover,a:focus{color:#016be2;text-decoration:underline}a img{border:none}p{font-family:inherit;font-weight:normal;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}p aside{font-size:0.875em;line-height:1.35;font-style:italic}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:Montserrat, sans-serif;font-weight:400;font-style:normal;color:#000;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:0.5em;line-height:1.0125em}h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#867c74;line-height:0}h1{font-size:2.125em}h2{font-size:1.6875em}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}h4{font-size:1.125em}h5{font-size:1.125em}h6{font-size:1em}hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}em,i{font-style:italic;line-height:inherit}strong,b{font-weight:bold;line-height:inherit}small{font-size:60%;line-height:inherit}code{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-weight:normal;color:#3d3d3c;word-break:break-word}ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}ul,ol{margin-left:1.5em}ul.no-bullet,ol.no-bullet{margin-left:1.5em}ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}ul.square{list-style-type:square}ul.circle{list-style-type:circle}ul.disc{list-style-type:disc}ul.no-bullet{list-style:none}ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}dl dt{margin-bottom:0.3125em;font-weight:bold}dl dd{margin-bottom:1.25em}abbr,acronym{text-transform:uppercase;font-size:90%;color:#000;border-bottom:1px dotted #dddddd;cursor:help}abbr{text-transform:none}blockquote{margin:0 0 1.25em;padding:0.5625em 1.25em 0 1.1875em;border-left:1px solid #dddddd}blockquote cite{display:block;font-size:0.9375em;color:rgba(0,0,0,0.6)}blockquote cite:before{content:"\2014 \0020"}blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,0.6)}blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,0.85)}.vcard{display:inline-block;margin:0 0 1.25em 0;border:1px solid #dddddd;padding:0.625em 0.75em}.vcard li{margin:0;display:block}.vcard .fn{font-weight:bold;font-size:0.9375em}.vevent .summary{font-weight:bold}.vevent abbr{cursor:auto;text-decoration:none;font-weight:bold;border:none;padding:0 0.0625em}#tocbot{padding:0 0 1rem 0;line-height:1.5rem;padding-left:25px}.mobile-toc{padding:0 0 1rem 0;line-height:1.5rem}.mobile-toc li a{display:block;padding:.3rem 0}#tocbot ol li{list-style:none;padding:0;margin:0}#tocbot ol{margin:0;padding:0;padding-left:0.6rem}#tocbot .toc-link{display:block;padding-top:4px;padding-bottom:4px;outline:none}table{background:white;margin-bottom:1.25em;border:solid 1px #cacaca;border-spacing:0}table thead,table tfoot{background:#f7f8f7;font-weight:bold}table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:0.5em 0.625em 0.625em;font-size:inherit;color:#000;text-align:left}table tr th,table tr td{padding:0.5625em 0.625em;font-size:inherit;color:#000}table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}body{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;tab-size:4}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-0.05em}.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}.clearfix:after,.float-group:after{clear:both}*:not(pre)>code{font-size:0.8525em;font-style:normal !important;letter-spacing:0;padding:0.1em 0.3em 0.2em;background-color:rgba(0,0,0,0.05);border-radius:4px;text-rendering:optimizeSpeed}pre,pre>code{line-height:1.85;color:rgba(0,0,0,0.9);font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-weight:normal;text-rendering:optimizeSpeed;word-break:normal}pre{overflow:auto}em em{font-style:normal}strong strong{font-weight:normal}.keyseq{color:#6b625c}kbd{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;display:inline-block;color:#000;font-size:0.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 0.1em white inset;box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 0.1em white inset;margin:0 0.15em;padding:0.2em 0.5em;vertical-align:middle;position:relative;top:-0.1em;white-space:nowrap}.keyseq kbd:first-child{margin-left:0}.keyseq kbd:last-child{margin-right:0}.menuseq,.menu{color:#191715}b.button:before,b.button:after{position:relative;top:-1px;font-weight:normal}b.button:before{content:"[";padding:0 3px 0 2px}b.button:after{content:"]";padding:0 2px 0 3px}p a>code:hover{color:rgba(0,0,0,0.9)}#toc{border-bottom:1px solid #ddddd8;padding-bottom:0.5em}#toc>ul{margin-left:0.125em}#toc ul.sectlevel0>li>a{font-style:italic}#toc ul.sectlevel0 ul.sectlevel1{margin:0.5em 0}#toc ul{list-style-type:none}#toc li{line-height:1.3334}#toc a{text-decoration:none}#toc a:active{text-decoration:underline}#toctitle{color:#0b0a0a;font-size:1.2em;display:none}body.toc2{padding-top:90px;text-rendering:optimizeLegibility}#content #toc{border-style:solid;border-width:1px;border-color:#d7d7d7;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;-webkit-border-radius:4px;border-radius:4px}#content #toc>:first-child{margin-top:0}#content #toc>:last-child{margin-bottom:0}#footer{padding-bottom:2rem}#footer #footer-text{padding:2rem 0;border-top:1px solid #efefed}#footer-text{color:rgba(0,0,0,0.6);line-height:1.44}.sect1{padding-bottom:0.625em}.sect1+.sect1{border-top:1px solid #efefed}#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;margin-top:0.1rem;display:block;visibility:hidden;text-align:center;font-weight:normal;color:rgba(0,0,0,0.2)}#content h1>a.anchor:hover,h2>a.anchor:hover,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4>a.anchor:hover,h5>a.anchor:hover,h6>a.anchor:hover{color:#097dff;text-decoration:none}#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\0023";font-size:0.85em;display:block;padding-top:0.1em}#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#000;text-decoration:none}#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#262321}.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:Karla, sans-serif;font-size:1rem}table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0;padding:0.6rem 0}table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}.admonitionblock>table td.icon{text-align:center;vertical-align:top;padding-top:0.8em;width:80px}.admonitionblock>table td.icon img{max-width:initial}.admonitionblock>table td.icon .title{font-weight:bold;font-family:Montserrat, sans-serif;text-transform:uppercase}.admonitionblock>table td.content{padding-left:0em;padding-right:1.25em;border-left:1px solid #ddddd8}.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}.exampleblock>.content{border-style:solid;border-width:0;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;border-radius:4px}.exampleblock>.content>:first-child{margin-top:0}.exampleblock>.content>:last-child{margin-bottom:0}.sidebarblock{border-style:solid;border-width:0;border-color:#d7d7d7;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;border-radius:4px;overflow:scroll}.sidebarblock>:first-child{margin-top:0}.sidebarblock>:last-child{margin-bottom:0}.sidebarblock>.content>.title{color:#0b0a0a;margin-top:0;text-align:center}.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#282c33;color:#e6e1dc;border-radius:4px}.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#282c33;color:#e6e1dc}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class],.listingblock pre:not(.highlight){padding:1em 1.5rem;font-size:0.8125em}.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto}.literalblock.output pre{color:whitesmoke;background-color:rgba(0,0,0,0.9)}.listingblock{white-space:nowrap}.listingblock pre.highlightjs{padding:0.2rem 0}.listingblock pre.highlightjs>code{padding:1em 1.5rem;border-radius:4px}.listingblock>.content{position:relative}.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:0.8em;font-weight:bold;top:0.425rem;right:0.5rem;line-height:1;text-transform:uppercase;color:#999}.listingblock code[data-lang]:before{display:block}.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:0.5em;color:#999}.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}table.pyhltable td.code{padding-left:.75em;padding-right:0}pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}pre.pygments .lineno{display:block;margin-right:.25em}table.pyhltable .linenodiv{background:none !important;padding-right:0 !important}.quoteblock{margin:0 1em 1.25em 1.5em;display:block;text-align:left;padding-left:20px}.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,0.85);line-height:1.75;letter-spacing:0}.quoteblock blockquote{margin:0;padding:0;border:0;position:relative}.quoteblock blockquote:before{content:"\201c";font-size:2.75em;font-weight:bold;line-height:0.6em;margin-left:0em;margin-right:1rem;margin-top:0.8rem;color:rgba(0,0,0,0.1);position:absolute;top:0;left:-30px}.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}.quoteblock .attribution{margin-right:0.5ex}.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:0.5em 0;border-left:3px solid rgba(0,0,0,0.6)}.quoteblock .quoteblock blockquote{padding:0 0 0 0.75em}.quoteblock .quoteblock blockquote:before{display:none}.verseblock{margin:0 1em 1.25em 0;background-color:#f1f1f1;padding:1rem 1.4rem;border-radius:4px}.verseblock pre{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-size:0.9rem;color:rgba(0,0,0,0.85);font-weight:300;text-rendering:optimizeLegibility}.verseblock pre strong{font-weight:400}.verseblock .attribution{margin-top:1.25rem;margin-left:0.5ex}.quoteblock .attribution,.verseblock .attribution{font-size:0.9375em;line-height:1.45;font-style:italic}.quoteblock .attribution br,.verseblock .attribution br{display:none}.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-0.025em;color:rgba(0,0,0,0.6)}.quoteblock.abstract{margin:0 0 1.25em 0;display:block}.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}table.tableblock{max-width:100%;border-collapse:separate;overflow-x:scroll}table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}table.tableblock,th.tableblock,td.tableblock{border:0 solid #cacaca;background:white}table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}table.frame-all{border-width:1px}table.frame-sides{border-width:0 1px}table.frame-topbot{border-width:1px 0}th.halign-left,td.halign-left{text-align:left}th.halign-right,td.halign-right{text-align:right}th.halign-center,td.halign-center{text-align:center}th.valign-top,td.valign-top{vertical-align:top}th.valign-bottom,td.valign-bottom{vertical-align:bottom}th.valign-middle,td.valign-middle{vertical-align:middle}table thead th,table tfoot th{font-weight:bold}tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:#34302d;font-weight:bold}p.tableblock>code:only-child{background:none;padding:0}p.tableblock{font-size:1em}td>div.verse{white-space:pre}ol{margin-left:1.75em}ul li ol{margin-left:1.5em}dl dd{margin-left:1.125em}dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:0.625em}ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}ul.unstyled,ol.unnumbered,ul.checklist{margin-left:0.625em}ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:0.85em}ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}ul.inline{margin:0 auto 0.625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}ul.inline>li>*{display:block}.unstyled dl dt{font-weight:normal;font-style:normal}ol.arabic{list-style-type:decimal}ol.decimal{list-style-type:decimal-leading-zero}ol.loweralpha{list-style-type:lower-alpha}ol.upperalpha{list-style-type:upper-alpha}ol.lowerroman{list-style-type:lower-roman}ol.upperroman{list-style-type:upper-roman}ol.lowergreek{list-style-type:lower-greek}.hdlist>table,.colist>table{border:0;background:none}.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}td.hdlist1,td.hdlist2{vertical-align:top;padding:0 0.625em}td.hdlist1{font-weight:bold;padding-bottom:1.25em}.literalblock+.colist,.listingblock+.colist{margin-top:-0.5em}.colist>table tr>td:first-of-type{padding:0 0.75em;line-height:1}.colist>table tr>td:first-of-type img{max-width:initial}.colist>table tr>td:last-of-type{padding:0.25em 0}.thumb,.th{line-height:0;display:inline-block;border:solid 4px white;-webkit-box-shadow:0 0 0 1px #dddddd;box-shadow:0 0 0 1px #dddddd}.imageblock.left,.imageblock[style*="float: left"]{margin:0.25em 0.625em 1.25em 0}.imageblock.right,.imageblock[style*="float: right"]{margin:0.25em 0 1.25em 0.625em}.imageblock>.title{margin-bottom:0}.imageblock.thumb,.imageblock.th{border-width:6px}.imageblock.thumb>.title,.imageblock.th>.title{padding:0 0.125em}.image.left,.image.right{margin-top:0.25em;margin-bottom:0.25em;display:inline-block;line-height:0}.image.left{margin-right:0.625em}.image.right{margin-left:0.625em}a.image{text-decoration:none;display:inline-block}a.image object{pointer-events:none}sup.footnote,sup.footnoteref{font-size:0.875em;position:static;vertical-align:super}sup.footnote a,sup.footnoteref a{text-decoration:none}sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}#footnotes{padding-top:0.75em;padding-bottom:0.75em;margin-bottom:0.625em}#footnotes hr{width:20%;min-width:6.25em;margin:-0.25em 0 0.75em 0;border-width:1px 0 0 0}#footnotes .footnote{padding:0 0.375em 0 0.225em;line-height:1.3334;font-size:0.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:0.2em}#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}#footnotes .footnote:last-of-type{margin-bottom:0}#content #footnotes{margin-top:-0.625em;margin-bottom:0;padding:0.75em 0}.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}.gist .file-data>table td.line-data{width:99%}div.unbreakable{page-break-inside:avoid}.big{font-size:larger}.small{font-size:smaller}.underline{text-decoration:underline}.overline{text-decoration:overline}.line-through{text-decoration:line-through}.aqua{color:#00bfbf}.aqua-background{background-color:#00fafa}.black{color:black}.black-background{background-color:black}.blue{color:#0000bf}.blue-background{background-color:#0000fa}.fuchsia{color:#bf00bf}.fuchsia-background{background-color:#fa00fa}.gray{color:#606060}.gray-background{background-color:#7d7d7d}.green{color:#006000}.green-background{background-color:#007d00}.lime{color:#00bf00}.lime-background{background-color:#00fa00}.maroon{color:#600000}.maroon-background{background-color:#7d0000}.navy{color:#000060}.navy-background{background-color:#00007d}.olive{color:#606000}.olive-background{background-color:#7d7d00}.purple{color:#600060}.purple-background{background-color:#7d007d}.red{color:#bf0000}.red-background{background-color:#fa0000}.silver{color:#909090}.silver-background{background-color:#bcbcbc}.teal{color:#006060}.teal-background{background-color:#007d7d}.white{color:#bfbfbf}.white-background{background-color:#fafafa}.yellow{color:#bfbf00}.yellow-background{background-color:#fafa00}span.icon>.fa{cursor:default}.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;cursor:default}.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#3f6a22}.admonitionblock td.icon .icon-tip:before{content:"\f0eb";color:#0077b9}.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#d88400}.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}.conum[data-value]{display:inline-block;color:#000 !important;background-color:#ffe157;-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:0.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans", "DejaVu Sans", sans-serif;font-style:normal;font-weight:bold}.conum[data-value] *{color:#fff !important}.conum[data-value]+b{display:none}.conum[data-value]:after{content:attr(data-value)}pre .conum[data-value]{position:relative;top:0;color:#000 !important;background-color:#ffe157;font-size:12px}b.conum *{color:inherit !important}.conum:not([data-value]):empty{display:none}.admonitionblock{background-color:#ecf1e8;padding:0.8em 0;margin:30px 0;width:auto;border-radius:4px;overflow-x:scroll}.admonitionblock.important{border-left:0px solid #e20000;background-color:#f9ebeb}.admonitionblock.warning{border-left:0px solid #d88400;background-color:#fff9e4}.admonitionblock.tip{border-left:0px solid #0077b9;background-color:#e9f1f6}.admonitionblock.caution{border-left:0px solid #e20000;background-color:#f9ebeb}.admonitionblock .exampleblock>.content{border:0 none;background-color:#fff}#toc a:hover{text-decoration:underline}.admonitionblock>table{margin-bottom:0}.admonitionblock>table td.content{border-left:none}@media print{#tocbot a.toc-link.node-name--H4{display:none}}.is-collapsible{max-height:1000px;overflow:hidden;transition:all 200ms ease-in-out}.is-collapsed{max-height:0}div.back-action,#toc.toc2 div.back-action{padding:0.8rem 0 0 0}div.back-action a,#toc.toc2 div.back-action a{position:relative;display:inline-block;padding:0.6rem 1.2rem;padding-left:35px}div.back-action a span,#toc.toc2 div.back-action a span{position:absolute;left:5px;top:5px;display:block;color:#333;height:26px;width:26px;border-radius:13px}div.back-action a i,#toc.toc2 div.back-action a i{position:absolute;top:5px;left:5px}div.back-action a:hover span,#toc.toc2 div.back-action a:hover span{color:#000}#tocbot.desktop-toc{padding-top:0.8rem}#header-spring{position:absolute;text-rendering:optimizeLegibility;top:0;left:0;right:0;height:90px;margin:0 1rem;padding:0 1rem;border-bottom:1px solid #ddddd8;border-top:3px solid #6BB344}#header-spring h1{margin:0;padding:0;font-size:22px;text-align:left;line-height:86px;padding-left:0.6rem}#header-spring h1 svg{width:200px}#header-spring h1 svg .st0{fill:#6BB344}#header-spring h1 svg .st2{fill:#444}body.book #header-spring{position:relative;top:auto;left:auto;right:auto;margin:0}body.book #header>h1:only-child{border:0 none;padding-bottom:1.2rem;font-size:1.8rem}body.book #header,body.book #content,body.book #footnotes,body.book #footer{margin:0 auto}body.toc2 #header-spring{position:absolute;left:0;right:0;top:0}body.toc2 #header>h1:only-child{font-size:2.2rem}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{margin:0 auto}body.toc2 #content{padding-top:2rem}#header,#content,#footnotes,#footer{width:100%;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:0.9375em;padding-right:0.9375em}#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}#header:after,#content:after,#footnotes:after,#footer:after{clear:both}#content{margin-top:1.25em}#content:before{content:none}#header>h1:first-child{margin-top:2.55rem;margin-bottom:0.5em;margin-bottom:0.5em}#header>h1:first-child+#toc{margin-top:8px;border-top:0 none}#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:0;padding-bottom:2.25em;padding-left:0.25em;color:rgba(0,0,0,0.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}#header .details span:first-child{margin-left:-0.125em}#header .details span.email a{color:rgba(0,0,0,0.85)}#header .details br{display:none}#header .details br+span:before{content:"\00a0\2013\00a0"}#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,0.85)}#header .details br+span#revremark:before{content:"\00a0|\00a0"}#header #revnumber{text-transform:capitalize}#header #revnumber:after{content:"\00a0"}#content>h1:first-child:not([class]){color:rgba(0,0,0,0.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1.5rem;margin-bottom:1.25rem}h1{font-size:2.2rem;letter-spacing:-1px}h1,h2,h3,h4,h5,h6{font-weight:normal;font-family:Montserrat, Arial, Helvetica, sans-serif}h1:focus,h2:focus,h3:focus,h4:focus,h5:focus,h6:focus{box-shadow:none;outline:none}h2,h3,h4,h5,h6{padding:.8rem 0 .4rem}h1{font-size:1.75em}h2{font-size:1.6rem;letter-spacing:-1px}h3{font-size:1.5rem}h4{font-size:1.4rem}h5{font-size:1.3rem}h6{font-size:1.2rem}pre.highlight{background:#232323;color:#e6e1dc;border-radius:4px}pre.highlight code{color:#e6e1dc}pre.highlight a,#toc.toc2 a{color:#000;font-size:1rem}pre.highlight ul.sectlevel1,#toc.toc2 ul.sectlevel1{padding-left:0.2rem}pre.highlight ul.sectlevel1 li,#toc.toc2 ul.sectlevel1 li{line-height:1.4rem}::selection{background-color:#d1ff79}.literalblock pre::selection,.listingblock pre[class="highlight"]::selection,.highlight::selection,pre::selection,.highlight code::selection,.highlight code span::selection{background:rgba(255,255,255,0.2) !important}body.book #header{margin-bottom:2rem}body.toc2 #header{margin-bottom:0}.desktop-toc{display:none}.admonitionblock td.icon{display:none}.admonitionblock>table td.content{padding-left:1.25em}@media only screen and (min-width: 768px){#toctitle{font-size:1.375em}.sect1{padding-bottom:1.25em}.mobile-toc{display:none}.desktop-toc{display:block}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:0.90625em}.admonitionblock td.icon{display:table-cell}.admonitionblock>table td.content{padding-left:0}body.toc2{padding-right:0}body.toc2 #toc.toc2{position:absolute;margin-top:0 !important;width:15em;top:0;border-top-width:0 !important;border-bottom-width:0 !important;margin-left:-15.9375em;z-index:1000;padding:0 1em 1.25em 0em;overflow:auto}body.toc2 #toc.toc2 #toctitle{margin-top:0;margin-bottom:0.8rem;font-size:1.2em}body.toc2 #toc.toc2>ul{font-size:0.9em;margin-bottom:0}body.toc2 #toc.toc2 ul ul{margin-left:0;padding-left:1em}body.toc2 #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:0.5em;margin-bottom:0.5em}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{padding-left:15.9375em;max-width:none}body.book #header-spring h1{max-width:1400px;margin:0 auto}body.book #header,body.book #content,body.book #footnotes,body.book #footer{max-width:1400px}body.is-position-fixed #toc.toc2{position:fixed;height:100%}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}h1{font-size:1.75em}h2{font-size:1.6em}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.5em}h4{font-size:1.4em}h5{font-size:1.2em}h6{font-size:1.2em}#tocbot a.toc-link.node-name--H1{font-style:italic}#tocbot ol{margin:0;padding:0;padding-left:0.6rem}#tocbot ol li{list-style:none;padding:0 0;margin:0;display:block}#tocbot{z-index:999}#tocbot .toc-link{position:relative;display:block;z-index:999;padding-right:5px;padding-top:4px;padding-bottom:4px}#tocbot .is-active-link{padding-right:3px;border-right:3px solid #6BB344}}@media only screen and (min-width: 768px){#tocbot>ul.toc-list{margin-bottom:0.5em;margin-left:0.125em}#tocbot ul.sectlevel0,#tocbot a.toc-link.node-name--H1+ul{padding-left:0}#tocbot a.toc-link{height:100%}.is-collapsible{max-height:3000px;overflow:hidden}.is-collapsed{max-height:0}.is-active-link{font-weight:700}}@media only screen and (min-width: 768px){body.toc2 #header,body.toc2 #content,body.toc2 #footer{background-repeat:repeat-y;background-position:14em 0;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQwIDc5LjE2MDQ1MSwgMjAxNy8wNS8wNi0wMTowODoyMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTggKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDE0NUNENzNGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDE0NUNENzRGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpEMTQ1Q0Q3MUYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpEMTQ1Q0Q3MkYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjmGxxYAAAAGUExURd3d2AAAAJlCnKAAAAAMSURBVHjaYmAACDAAAAIAAU9tWeEAAAAASUVORK5CYII=)}}@media only screen and (min-width: 1280px){body.toc2{padding-right:0}body.toc2 #toc.toc2{width:25em;left:auto;margin-left:-26.9375em}body.toc2 #toc.toc2 #toctitle{font-size:1.375em}body.toc2 #toc.toc2>ul{font-size:0.95em}body.toc2 #toc.toc2 ul ul{padding-left:1.25em}body.toc2 body.toc2.toc-right{padding-left:0;padding-right:20em}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{padding-left:26.9375em;max-width:1400px}body.toc2 #header-spring h1{margin:0 auto;max-width:1400px}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:0.8125em}body.toc2 #header,body.toc2 #content,body.toc2 #footer{background-repeat:repeat-y;background-position:24em 0;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQwIDc5LjE2MDQ1MSwgMjAxNy8wNS8wNi0wMTowODoyMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTggKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDE0NUNENzNGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDE0NUNENzRGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpEMTQ1Q0Q3MUYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpEMTQ1Q0Q3MkYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjmGxxYAAAAGUExURd3d2AAAAJlCnKAAAAAMSURBVHjaYmAACDAAAAIAAU9tWeEAAAAASUVORK5CYII=)}} diff --git a/reference/html/favicon.ico b/reference/html/favicon.ico new file mode 100644 index 0000000000..1a4956e647 Binary files /dev/null and b/reference/html/favicon.ico differ diff --git a/reference/html/images/Deps.png b/reference/html/images/Deps.png new file mode 100644 index 0000000000..1426814308 Binary files /dev/null and b/reference/html/images/Deps.png differ diff --git a/reference/html/images/Stubs1.png b/reference/html/images/Stubs1.png new file mode 100644 index 0000000000..ebadfdb910 Binary files /dev/null and b/reference/html/images/Stubs1.png differ diff --git a/reference/html/images/Stubs2.png b/reference/html/images/Stubs2.png new file mode 100644 index 0000000000..e4bad24987 Binary files /dev/null and b/reference/html/images/Stubs2.png differ diff --git a/reference/html/index.html b/reference/html/index.html new file mode 100644 index 0000000000..3ba3a37584 --- /dev/null +++ b/reference/html/index.html @@ -0,0 +1,15095 @@ + + + + + + + +Spring Cloud Contract + + + + + + + + + + +
+
+
+
+

Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant

+
+
+

{spring-cloud-version}

+
+
+
+
+

1. Spring Cloud Contract

+
+
+

You need confidence when pushing new features to a new application or service in a +distributed system. This project provides support for Consumer Driven Contracts and +service schemas in Spring applications (for both HTTP and message-based interactions), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers.

+
+
+
+
+

2. Spring Cloud Contract Verifier Introduction

+
+
+

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

+
+
+

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

+
+
+
    +
  • +

    JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.

    +
  • +
  • +

    Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.

    +
  • +
  • +

    Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

    +
  • +
+
+
+

2.1. History

+
+

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

+
+
+

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

+
+
+
+

2.2. Why a Contract Verifier?

+
+

Assume that we have a system consisting of multiple microservices:

+
+
+
+Microservices Architecture +
+
+
+

2.2.1. Testing issues

+
+

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

+
+
+
    +
  • +

    Deploy all microservices and perform end-to-end tests.

    +
  • +
  • +

    Mock other microservices in unit/integration tests.

    +
  • +
+
+
+

Both have their advantages but also a lot of disadvantages.

+
+
+

Deploy all microservices and perform end to end tests

+
+
+

Advantages:

+
+
+
    +
  • +

    Simulates production.

    +
  • +
  • +

    Tests real communication between services.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.

    +
  • +
  • +

    The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).

    +
  • +
  • +

    They take a long time to run.

    +
  • +
  • +

    The feedback comes very late in the process.

    +
  • +
  • +

    They are extremely hard to debug.

    +
  • +
+
+
+

Mock other microservices in unit/integration tests

+
+
+

Advantages:

+
+
+
    +
  • +

    They provide very fast feedback.

    +
  • +
  • +

    They have no infrastructure requirements.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    The implementor of the service creates stubs that might have nothing to do with +reality.

    +
  • +
  • +

    You can go to production with passing tests and failing production.

    +
  • +
+
+
+

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

+
+
+
+Stubbed Services +
+
+
+

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

+
+
+
+
+

2.3. Purposes

+
+

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

+
+
+
    +
  • +

    To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.

    +
  • +
  • +

    To promote ATDD method and Microservices architectural style.

    +
  • +
  • +

    To provide a way to publish changes in contracts that are immediately visible on both +sides.

    +
  • +
  • +

    To generate boilerplate test code to be used on the server side.

    +
  • +
+
+
+ + + + + +
+ + +Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. +
+
+
+
+

2.4. How It Works

+
+

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

+
+
+

2.4.1. A Three-second Tour

+
+

This very brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find a somewhat longer tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    +
    +
    +
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

+
+
+
+
+

2.4.2. A Three-minute Tour

+
+

This brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find an even more brief tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

+
+
+
+
package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}
+
+
+
+

The same contract expressed in YAML would look like the following example:

+
+
+
+
request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8
+
+
+
+

In the case of messaging, you can define:

+
+
+
    +
  • +

    The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).

    +
  • +
  • +

    The methods that should be called after the message is received.

    +
  • +
  • +

    The methods that, when called, should trigger a message.

    +
  • +
+
+
+

The following example shows a Camel messaging contract expressed in Groovy DSL:

+
+
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+

The following example shows the same contract expressed in YAML:

+
+
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

+
+
+

The following example shows a sample auto-generated test for an HTTP contract:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

+
+
+

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

+
+
+

Here is an example of a test generated in WEBTESTCLIENT test mode:

+
+
+
+
[source,java,indent=0]
+
+
+
+
+
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}
+
+
+
+

Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin +testFramework property to either JUNIT5, TESTNG or Spock.

+
+
+ + + + + +
+ + +You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. +
+
+
+

The following example shows an auto-generated test in Spock for a messaging stub contract:

+
+
+
+
[source,groovy,indent=0]
+
+
+
+
+
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+
+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

+
+
+

Docker Project

+
+
+

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To get started, add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    +
    +
    +
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+
+
+

2.4.3. Defining the Contract

+
+

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

+
+
+

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+
+

2.4.4. Client Side

+
+

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

+
+
+
+

2.4.5. Server Side

+
+

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

+
+
+

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

+
+
+

The autogenerated test looks, more or less, like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+
+
+

2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)

+
+

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

+
+
+

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

+
+
+

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

+
+
+

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

+
+ +
+ + + + + +
+ + +In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository. +
+
+
+

2.5.1. Technical note

+
+

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
repositories {
+	mavenCentral()
+	mavenLocal()
+	maven { url "https://repo.spring.io/snapshot" }
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/release" }
+}
+
+
+
+
+

2.5.2. Consumer side (Loan Issuance)

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

+
+
+
    +
  1. +

    Start doing TDD by writing a test for your feature.

    +
  2. +
  3. +

    Write the missing implementation.

    +
  4. +
  5. +

    Clone the Fraud Detection service repository locally.

    +
  6. +
  7. +

    Define the contract locally in the repo of Fraud Detection service.

    +
  8. +
  9. +

    Add the Spring Cloud Contract Verifier plugin.

    +
  10. +
  11. +

    Run the integration tests.

    +
  12. +
  13. +

    File a pull request.

    +
  14. +
  15. +

    Create an initial implementation.

    +
  16. +
  17. +

    Take over the pull request.

    +
  18. +
  19. +

    Write the missing implementation.

    +
  20. +
  21. +

    Deploy your app.

    +
  22. +
  23. +

    Work online.

    +
  24. +
+
+
+

Start doing TDD by writing a test for your feature.

+
+
+
+
@Test
+public void shouldBeRejectedDueToAbnormalLoanAmount() {
+	// given:
+	LoanApplication application = new LoanApplication(new Client("1234567890"),
+			99999);
+	// when:
+	LoanApplicationResult loanApplication = service.loanApplication(application);
+	// then:
+	assertThat(loanApplication.getLoanApplicationStatus())
+			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
+	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
+}
+
+
+
+

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

+
+
+

Write the missing implementation.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

+
+
+

If you start the test at this point, it breaks, because no service currently runs on port +8080.

+
+
+

Clone the Fraud Detection service repository locally.

+
+
+

You can start by playing around with the server side contract. To do so, you must first +clone it.

+
+
+
+
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
+
+
+
+

Define the contract locally in the repo of Fraud Detection service.

+
+
+

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

+
+
+ + + + + +
+ + +Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder. +
+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the Contract DSL section for more information. We highly recommend using the map notation!

+
+
+ + + + + +
+ + +You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON. +
+
+
+

The previously shown contract is an agreement between two sides that:

+
+
+
    +
  • +

    if an HTTP request is sent with all of

    +
    +
      +
    • +

      a PUT method on the /fraudcheck endpoint,

      +
    • +
    • +

      a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json,

      +
    • +
    +
    +
  • +
  • +

    then an HTTP response is sent to the consumer that

    +
    +
      +
    • +

      has status 200,

      +
    • +
    • +

      contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json.

      +
    • +
    +
    +
  • +
+
+
+

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

+
+
+

Add the Spring Cloud Contract Verifier plugin.

+
+
+

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

+
+
+
    +
  • +

    generate and run tests

    +
  • +
  • +

    produce and install stubs

    +
  • +
+
+
+

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

+
+
+
+
$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests
+
+
+
+

In the logs, you see something like this:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

The following line is extremely important:

+
+
+
+
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

It confirms that the stubs of the http-server have been installed in the local +repository.

+
+
+

Run the integration tests.

+
+
+

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

+
+
+

Add the Spring Cloud Contract BOM:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release-train.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

Now, when you run your tests, you see something like this:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

+
+
+

File a pull request.

+
+
+

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

+
+
+

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

+
+
+
+

2.5.3. Producer side (Fraud Detection server)

+
+

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

+
+
+

Create an initial implementation.

+
+
+

As a reminder, you can see the initial implementation here:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

Take over the pull request.

+
+
+
+
$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
+
+
+
+

You must add the dependencies needed by the autogenerated tests:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+ + + + + +
+ + +This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name. +
+
+
+

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

+
+
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class FraudBase {
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
+				new FraudStatsController(stubbedStatsProvider()));
+	}
+
+	private StatsProvider stubbedStatsProvider() {
+		return fraudType -> {
+			switch (fraudType) {
+			case DRUNKS:
+				return 100;
+			case ALL:
+				return 200;
+			}
+			return 0;
+		};
+	}
+
+	public void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

Now, if you run the ./mvnw clean install, you get something like this:

+
+
+
+
Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
+
+
+
+

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

+
+
+

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

+
+
+

Write the missing implementation.

+
+
+

Because you know the expected input and expected output, you can write the missing +implementation:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+if (amountGreaterThanThreshold(fraudCheck)) {
+	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
+}
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

+
+
+

Deploy your app.

+
+
+

Once you finish your work, you can deploy your change. First, merge the branch:

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master
+
+
+
+

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

+
+
+
+

2.5.4. Consumer Side (Loan Issuance) Final Step

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

+
+
+

Merge branch to master.

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+
+
+
+

Work online.

+
+
+

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

+
+
+
+
stubrunner:
+  ids: 'com.example:http-server-dsl:+:stubs:8080'
+  repositoryRoot: https://repo.spring.io/libs-snapshot
+
+
+
+

That’s it!

+
+
+
+
+

2.6. Dependencies

+
+

The best way to add dependencies is to use the proper starter dependency.

+
+
+

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

+
+
+
+ +
+

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

+
+
+

2.7.1. Spring Cloud Contract video

+
+

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

+
+
+
+ +
+
+
+ +
+
+

2.8. Samples

+
+

You can find some samples at +samples.

+
+
+
+
+
+

3. Spring Cloud Contract FAQ

+
+
+

3.1. Why use Spring Cloud Contract Verifier and not X ?

+
+

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

+
+
+
    +
  • +

    Possibility to do CDC with messaging

    +
  • +
  • +

    Clear and easy to use, statically typed DSL

    +
  • +
  • +

    Possibility to copy paste your current JSON file to the contract and only edit its elements

    +
  • +
  • +

    Automatic generation of tests from the defined Contract

    +
  • +
  • +

    Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory

    +
  • +
  • +

    Spring Cloud integration - no discovery service is needed for integration tests

    +
  • +
  • +

    Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality

    +
  • +
  • +

    Via Docker adds support for any language & framework used

    +
  • +
+
+
+
+

3.2. I don’t want to write a contract in Groovy!

+
+

No problem. You can write a contract in YAML!

+
+
+
+

3.3. What is this value(consumer(), producer()) ?

+
+

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

and JSON response

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

+
+
+

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}
+
+
+
+

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}
+
+
+
+

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

+
+
+

Either via the value method

+
+
+
+
value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

or using the $() method

+
+
+
+
$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

You can read more about this in the Contract DSL section.

+
+
+

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

+
+
+ + + + + +
+ + +If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated. +
+
+
+

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

+
+
+

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
+
+
+
+ + + + + +
+ + +Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies. +
+
+
+
+

3.4. How to do Stubs versioning?

+
+

3.4.1. API Versioning

+
+

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

+
+
+
    +
  • +

    use Hypermedia, links and do not version your API by any means

    +
  • +
  • +

    pass versions through headers / urls

    +
  • +
+
+
+

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

+
+
+

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

+
+
+
+

3.4.2. JAR versioning

+
+

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

+
+
+

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

+
+
+
+
1.0.0.20161020-201521-RELEASE
+
+
+
+

In that case your generated stub jar will look like this.

+
+
+
+
1.0.0.20161020-201521-RELEASE-stubs.jar
+
+
+
+

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
+
+
+
+
+

3.4.3. Dev or prod stubs

+
+

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

+
+
+

Example of tests using development version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

Example of tests using production version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
+
+
+
+

You can pass those values also via properties from your deployment pipeline.

+
+
+
+
+

3.5. Common repo with contracts

+
+

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

+
+
+

3.5.1. Repo structure

+
+

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

+
+
+
+
├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml
+
+
+
+

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

+
+
+

Example of a pom.xml inside the server folder.

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.2.0.M4</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>
+
+
+
+

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

+
+
+

The pom.xml in the root folder can look like this:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>
+
+
+
+

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

+
+
+
+
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
+

3.5.2. Workflow

+
+

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

+
+
+
+

3.5.3. Consumer

+
+

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

+
+
+ + + + + +
+ + +You need to have Maven installed locally +
+
+
+
+

3.5.4. Producer

+
+

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>
+
+
+
+

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from https://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

+
+
+

The rest of the flow looks the same.

+
+
+
+

3.5.5. How can I define messaging contracts per topic not per producer?

+
+

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

+
+
+
For Maven Project
+
+

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

+
+
+
+
<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>
+
+
+
+
+
For Gradle Project
+
+
    +
  • +

    Add a custom configuration for the common-repo dependency:

    +
  • +
+
+
+
+
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
+
+
+
+
    +
  • +

    Add the common-repo dependency to your classpath:

    +
  • +
+
+
+
+
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
+
+
+
+
    +
  • +

    Download the dependency to an appropriate folder:

    +
  • +
+
+
+
+
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
+
+
+
+
    +
  • +

    Unzip JAR:

    +
  • +
+
+
+
+
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
+
+
+
+
    +
  • +

    Cleanup unused contracts:

    +
  • +
+
+
+
+
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
+
+
+
+
    +
  • +

    Create task dependencies:

    +
  • +
+
+
+
+
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
+
+
+
+
    +
  • +

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

    +
  • +
+
+
+
+
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}
+
+
+
+
+
+
+

3.6. Do I need a Binary Storage? Can’t I use Git?

+
+

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

+
+
+

The repository would have to the following setup +(which you can checkout here):

+
+
+
+
.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json
+
+
+
+

Under META-INF folder:

+
+
+
    +
  • +

    we group applications via groupId (e.g. com.example)

    +
  • +
  • +

    then each application is represented via the artifactId (e.g. beer-api-producer-git)

    +
  • +
  • +

    next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    +
    +
      +
    • +

      + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT

        +
      • +
      • +

        if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called latest or + we will pick that folder

        +
      • +
      +
      +
    • +
    • +

      release - to find the latest release version of your stubs. That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called release we will pick that folder

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    finally, there are two folders:

    +
    +
      +
    • +

      contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.

      +
    • +
    • +

      mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

      +
    • +
    +
    +
  • +
+
+
+

3.6.1. Protocol convention

+
+

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

+
+
+

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

+
+
+
+
git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+
+
+
+
+

3.6.2. Producer

+
+

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

+
+
+ + + + + +
+ + +You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass, the stubs will be committed in the cloned repository

    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
+

3.6.3. Producer with contracts stored locally

+
+

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<!-- In the default configuration, we want to use the contracts stored locally -->
+	<configuration>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*messaging.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
+			</baseClassMapping>
+			<baseClassMapping>
+				<contractPackageRegex>.*rest.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+		<basePackageForTests>com.example</basePackageForTests>
+	</configuration>
+	<executions>
+		<execution>
+			<phase>package</phase>
+			<goals>
+				<!-- By default we will not push the stubs back to SCM,
+				you have to explicitly add it as a goal -->
+				<goal>pushStubsToScm</goal>
+			</goals>
+			<configuration>
+				<!-- We want to pick contracts from a Git repository -->
+				<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
+				</contractsRepositoryUrl>
+				<!-- Example of URL via git protocol -->
+				<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- Example of URL via http protocol -->
+				<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- We reuse the contract dependency section to set up the path
+				to the folder that contains the contract definitions. In our case the
+				path will be /groupId/artifactId/version/contracts -->
+				<contractDependency>
+					<groupId>${project.groupId}</groupId>
+					<artifactId>${project.artifactId}</artifactId>
+					<version>${project.version}</version>
+				</contractDependency>
+				<!-- The mode can't be classpath -->
+				<contractsMode>LOCAL</contractsMode>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		// Base package for generated tests
+	basePackageForTests = "com.example"
+	baseClassMappings {
+		baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
+		baseClassMapping(".*rest.*", "com.example.BeerRestBase")
+	}
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publishStubsToScm {
+	// We want to modify the default set up of the plugin when publish stubs to scm is called
+	customize {
+		// We want to pick contracts from a Git repository
+		contractDependency {
+			stringNotation = "${project.group}:${project.name}:${project.version}"
+		}
+		/*
+		We reuse the contract dependency section to set up the path
+		to the folder that contains the contract definitions. In our case the
+		path will be /groupId/artifactId/version/contracts
+		 */
+		contractRepository {
+			repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
+		}
+		// The mode can't be classpath
+		contractsMode = "LOCAL"
+	}
+}
+
+publish.dependsOn("publishStubsToScm")
+publishToMavenLocal.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Contracts from the default src/test/resources/contracts directory will be picked

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass

    +
    +
      +
    • +

      Git project will be cloned to a temporary directory

      +
    • +
    • +

      The stubs and contracts will be committed in the cloned repository

      +
    • +
    +
    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
Keeping contracts with the producer and stubs in an external repository
+
+

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

+
+
+

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

+
+
+
+
+

3.6.4. Consumer

+
+

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

+
+
+
+
@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/

    +
  • +
  • +

    Stub servers will be started and fed with mappings

    +
  • +
  • +

    Messaging definitions will be read and used in the messaging tests

    +
  • +
+
+
+
+
+

3.7. Can I use the Pact Broker?

+
+

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

+
+
+

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the Pact Converter section.

+
+
+ + + + + +
+ + +Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met. +
+
+
+

3.7.1. Pact Consumer

+
+

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

+
+
+
+

3.7.2. Producer

+
+

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into tests and stubs

    +
  • +
  • +

    The JAR with the stubs gets automatically created as usual

    +
  • +
+
+
+
+

3.7.3. Pact Consumer (Producer Contract approach)

+
+

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

+
+
+

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

+
+
+
Maven
+
+
<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+
Gradle
+
+
dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}
+
+
+
+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into stub definitions

    +
  • +
  • +

    The stub servers will be started and fed with stubs

    +
  • +
+
+
+

For more information about Pact support you can go to +the Using the Pact Stub Downloader section.

+
+
+
+
+

3.8. How can I debug the request/response being sent by the generated tests client?

+
+

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

+
+
+
+
logging.level.org.apache.http.wire=DEBUG
+
+
+
+

3.8.1. How can I debug the mapping/request/response being sent by WireMock?

+
+

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

+
+
+

To turn off this feature just bump WireMock logging to ERROR

+
+
+
+
logging.level.com.github.tomakehurst.wiremock=ERROR
+
+
+
+
+

3.8.2. How can I see what got registered in the HTTP server stub?

+
+

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

+
+
+
+

3.8.3. Can I reference text from file?

+
+

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

+
+
+
+
+
+
+

4. Spring Cloud Contract Verifier Setup

+
+
+

You can set up Spring Cloud Contract Verifier in the following ways:

+
+ +
+

4.1. Gradle Project

+
+

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

4.1.1. Prerequisites

+
+

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

+
+
+ + + + + +
+ + +If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information +
+
+
+
+

4.1.2. Add Gradle Plugin with Dependencies

+
+

To add a Gradle plugin with dependencies, use code similar to this:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}
+
+
+
+
+

4.1.3. Gradle and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}
+
+
+
+

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

4.1.4. Snapshot Versions for Gradle

+
+

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+}
+
+
+
+
+

4.1.5. Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

+
+
+

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

4.1.6. Run the Plugin

+
+

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

+
+
+
+

4.1.7. Default Setup

+
+

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

+
+
+
+
contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}
+
+
+
+
+

4.1.8. Configure Plugin

+
+

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

+
+
+
+
contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}
+
+
+
+
+

4.1.9. Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    +
  • +
  • +

    staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.

    +
  • +
  • +

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.

    +
  • +
  • +

    contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.

    +
  • +
  • +

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

The following properties are used when you want to specify the location of the JAR +containing the contracts:

+
+
+
    +
  • +

    contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.

    +
  • +
  • +

    contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.

    +
  • +
  • +

    contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

4.1.10. Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

+
+
+
+

4.1.11. Different Base Classes for Contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    Provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
packageWithBaseClasses = 'com.example.base'
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
baseClassForTests = "com.example.FooBase"
+baseClassMappings {
+	baseClassMapping('.*/com/.*', 'com.example.ComBase')
+	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
+}
+
+
+
+

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

4.1.12. Invoking Generated Tests

+
+

To ensure that the provider side is compliant with defined contracts, you need to invoke:

+
+
+
+
./gradlew generateContractTests test
+
+
+
+
+

4.1.13. Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

+
+
+
+
$ ./gradlew pushStubsToScm
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

+
+
+
+

4.1.14. Spring Cloud Contract Verifier on the Consumer Side

+
+

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

+
+
+
+
./gradlew generateClientStubs
+
+
+
+ + + + + +
+ + +The stubsOutputDir option has to be set for stub generation to work. +
+
+
+

When present, JSON stubs can be used in automated tests of consuming a service.

+
+
+
+
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}
+
+
+
+

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

+
+
+
+
+

4.2. Maven Project

+
+

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

4.2.1. Add maven plugin

+
+

Add the Spring Cloud Contract BOM in a fashion similar to this:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+ +
+
+

4.2.2. Maven and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

4.2.3. Snapshot versions for Maven

+
+

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

+
+
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
+

4.2.4. Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

4.2.5. Run plugin

+
+

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

+
+
+
+

4.2.6. Configure plugin

+
+

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>
+
+
+
+
+

4.2.7. Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.

    +
  • +
  • +

    baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

If you want to download your contract definitions from a Maven repository, you can use +the following options:

+
+
+
    +
  • +

    contractDependency: The contract dependency that contains all the packaged contracts.

    +
  • +
  • +

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.

    +
  • +
  • +

    contractsMode: Picks the mode in which stubs will be found and registered

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
  • +

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.

    +
  • +
  • +

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    +
  • +
+
+
+

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

4.2.8. Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}
+
+
+
+

You can also setup the whole context if necessary.

+
+
+
+
import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}
+
+
+
+

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}
+
+
+
+

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

+
+
+
+

4.2.9. Different base classes for contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<packageWithBaseClasses>hello</packageWithBaseClasses>
+	</configuration>
+</plugin>
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<baseClassForTests>com.example.FooBase</baseClassForTests>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*com.*</contractPackageRegex>
+				<baseClassFQN>com.example.TestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+</plugin>
+
+
+
+

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

4.2.10. Invoking generated tests

+
+

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

+
+
+

For Groovy Spock code, use the following:

+
+
+
+
<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>
+
+
+
+

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

+
+
+
+

4.2.11. Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

+
+
+
+

4.2.12. Maven Plugin and STS

+
+

If you see the following exception while using STS:

+
+
+
+STS Exception +
+
+
+

When you click on the error marker you should see something like this:

+
+
+
+
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
+
+
+
+

In order to fix this issue, provide the following section in your pom.xml:

+
+
+
+
<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>
+
+
+
+
+

4.2.13. Maven Plugin with Spock Tests

+
+

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

+
+
+

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

+
+
+
+
+
+
+
+

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

+
+
+
+
+
+
+
+
+
+

4.3. Stubs and Transitive Dependencies

+
+

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

+
+
+
+
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...
+
+
+
+

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

+
+
+
    +
  • +

    Mark all application dependencies as optional

    +
  • +
  • +

    Create a separate artifactid for the stubs

    +
  • +
  • +

    Exclude dependencies on the consumer side

    +
  • +
+
+
+

Mark all application dependencies as optional

+
+
+

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

+
+
+

Create a separate artifactid for the stubs

+
+
+

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

+
+
+

Exclude dependencies on the consumer side

+
+
+

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

+
+
+
+

4.4. Scenarios

+
+

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

+
+
+
+
my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy
+
+
+
+

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

+
+
+
    +
  1. +

    login marked as Started pointing to…​

    +
  2. +
  3. +

    showCart marked as Step1 pointing to…​

    +
  4. +
  5. +

    logout marked as Step2 which will close the scenario.

    +
  6. +
+
+
+

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

+
+
+

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

+
+
+
+

4.5. Docker Project

+
+

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

+
+
+ + + + + +
+ + +The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones. +
+
+
+

4.5.1. Short intro to Maven, JARs and Binary storage

+
+

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

+
+
+

Part of the following definitions were taken from the Maven Glossary

+
+
+
    +
  • +

    Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.

    +
  • +
  • +

    Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.

    +
  • +
  • +

    JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.

    +
  • +
  • +

    GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.

    +
  • +
  • +

    Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.

    +
  • +
  • +

    Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

    +
  • +
+
+
+
+

4.5.2. How it works

+
+

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

+
+
+

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

+
+
+
    +
  • +

    generate the contract tests

    +
  • +
  • +

    execute the tests against the provided URL

    +
  • +
  • +

    generate the WireMock stubs

    +
  • +
  • +

    (optional - turned on by default) publish the stubs to a Artifact Manager

    +
  • +
+
+
+
Environment Variables
+
+

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

+
+
+
    +
  • +

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    +
  • +
  • +

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    +
  • +
  • +

    PROJECT_NAME - artifact id. Defaults to example

    +
  • +
  • +

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    +
  • +
  • +

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    +
  • +
  • +

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    +
  • +
  • +

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    +
  • +
+
+
+

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

+
+
+
    +
  • +

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    +
  • +
  • +

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    +
  • +
  • +

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    +
  • +
+
+
+

These environment variables are used when tests are executed:

+
+
+
    +
  • +

    APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)

    +
  • +
  • +

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    +
  • +
  • +

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    +
  • +
+
+
+
+
+

4.5.3. Example of usage

+
+

Let’s take a look at a simple MVC application

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

The contracts are available under /contracts folder.

+
+
+
+

4.5.4. Server side (nodejs)

+
+

Since we want to run tests, we could just execute:

+
+
+
+
$ npm test
+
+
+
+

however, for learning purposes, let’s split it into pieces:

+
+
+
+
# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"
+
+
+
+

What will happen is that via bash scripts:

+
+
+
    +
  • +

    infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.

    +
  • +
  • +

    due to those constraints the contracts also represent the +stateful situation

    +
    +
      +
    • +

      first request is a POST that causes data to get inserted to the database

      +
    • +
    • +

      second request is a GET that returns a list of data with 1 previously inserted element

      +
    • +
    +
    +
  • +
  • +

    the NodeJS application will be started (on port 3000)

    +
  • +
  • +

    contract tests will be generated via Docker and tests +will be executed against the running application

    +
    +
      +
    • +

      the contracts will be taken from /contracts folder.

      +
    • +
    • +

      the output of the test execution is available under +node_modules/spring-cloud-contract/output.

      +
    • +
    +
    +
  • +
  • +

    the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    +
  • +
+
+
+

To see how the client side looks like check out the Stub Runner Docker section.

+
+
+
+
+
+
+

5. Spring Cloud Contract Verifier Messaging

+
+
+

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

+
+
+

5.1. Integrations

+
+

You can use one of the following four integration configurations:

+
+
+
    +
  • +

    Apache Camel

    +
  • +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

+
+
+ + + + + +
+ + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here: +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+
+

5.2. Manual Integration Testing

+
+

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

+
+
+

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

+
+
+
+
@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
+
+
+
+ + + + + +
+ + +If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation. +
+
+
+
+

5.3. Publisher-Side Test Generation

+
+

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5, TestNG or Spock tests.

+
+
+

There are 3 main scenarios that we should take into consideration:

+
+
+
    +
  • +

    Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).

    +
  • +
  • +

    Scenario 2: The input message triggers an output message.

    +
  • +
  • +

    Scenario 3: The input message is consumed and there is no output message.

    +
  • +
+
+
+ + + + + +
+ + +The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms). +
+
+
+

5.3.1. Scenario 1: No Input Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					triggeredBy('bookReturnedTriggered()')
+				}
+				outputMessage {
+					sentTo('activemq:output')
+					body('''{ "bookName" : "foo" }''')
+					headers {
+						header('BOOK-NAME', 'foo')
+						messagingContentType(applicationJson())
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  triggeredBy: bookReturnedTriggered
+outputMessage:
+  sentTo: activemq:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+    contentType: application/json
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// when:
+\t\t\tbookReturnedTriggered();
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+\t\t\tassertThat(response.getHeader("contentType")).isNotNull();
+\t\t\tassertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					'''\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\twhen:
+\t\t\tbookReturnedTriggered()
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+\t\t\tresponse.getHeader("contentType") != null
+\t\t\tresponse.getHeader("contentType").toString() == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+'''
+
+
+
+
+

5.3.2. Scenario 2: Output Triggered by Input

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:input')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+				}
+				outputMessage {
+					sentTo('jms:output')
+					body([
+							bookName: 'foo'
+					])
+					headers {
+						header('BOOK-NAME', 'foo')
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:input
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+outputMessage:
+  sentTo: jms:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input");
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input")
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+"""
+
+
+
+
+

5.3.3. Scenario 3: No Output Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

The following JUnit test is created:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete");
+\t\t\tbookWasDeleted();
+
+\t}
+
+}
+
+"""
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete")
+\t\t\tbookWasDeleted()
+
+\t\tthen:
+\t\t\tnoExceptionThrown()
+\t}
+
+}
+"""
+
+
+
+
+
+

5.4. Consumer Stub Generation

+
+

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

+
+
+

For more information, see Stub Runner for Messaging section.

+
+
+
Maven
+
+
<dependencies>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
+	</dependency>
+
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+		<scope>test</scope>
+	</dependency>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-stream-test-support</artifactId>
+		<scope>test</scope>
+	</dependency>
+</dependencies>
+
+<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>Hoxton.BUILD-SNAPSHOT</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+
+
+

6. Spring Cloud Contract Stub Runner

+
+
+

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

+
+
+

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

+
+
+

6.1. Snapshot versions

+
+

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+
+
+
+
+

6.2. Publishing Stubs as JARs

+
+

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

+
+
+ + + + + +
+ + +For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. +
+
+
+
Maven
+
+
<!-- First disable the default jar setup in the properties section -->
+<!-- we don't want the verifier to do a jar for us -->
+<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+
+<!-- Next add the assembly plugin to your build -->
+<!-- we want the assembly plugin to generate the JAR -->
+<plugin>
+	<groupId>org.apache.maven.plugins</groupId>
+	<artifactId>maven-assembly-plugin</artifactId>
+	<executions>
+		<execution>
+			<id>stub</id>
+			<phase>prepare-package</phase>
+			<goals>
+				<goal>single</goal>
+			</goals>
+			<inherited>false</inherited>
+			<configuration>
+				<attach>true</attach>
+				<descriptors>
+					${basedir}/src/assembly/stub.xml
+				</descriptors>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>src/main/java</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/classes</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+

6.3. Stub Runner Core

+
+

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts.

+
+
+

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined.

+
+
+

6.3.1. Retrieving stubs

+
+

You can pick the following options of acquiring stubs

+
+
+
    +
  • +

    Aether based solution that downloads JARs with stubs from Artifactory / Nexus

    +
  • +
  • +

    Classpath scanning solution that searches classpath via pattern to retrieve stubs

    +
  • +
  • +

    Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    +
  • +
+
+
+

The latter example is described in the Custom Stub Runner section.

+
+
+
Stub downloading
+
+

You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options

+
+
+
    +
  • +

    StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath

    +
  • +
  • +

    StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)

    +
  • +
  • +

    StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

    +
  • +
+
+
+

Example:

+
+
+
+
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+
+
+
+
+
Classpath scanning
+
+

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example:

+
+
+
+
@AutoConfigureStubRunner(ids = {
+    "com.example:beer-api-producer:+:stubs:8095",
+    "com.example.foo:bar:1.0.0:superstubs:8096"
+})
+
+
+
+

If you’ve added the dependencies to your classpath

+
+
+
Maven
+
+
<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>beer-api-producer-restdocs</artifactId>
+    <classifier>stubs</classifier>
+    <version>0.0.1-SNAPSHOT</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+<dependency>
+    <groupId>com.example.foo</groupId>
+    <artifactId>bar</artifactId>
+    <classifier>superstubs</classifier>
+    <version>1.0.0</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
+    transitive = false
+}
+testCompile("com.example.foo:bar:1.0.0:superstubs") {
+    transitive = false
+}
+
+
+
+

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

+
+
+
    +
  • +

    /META-INF/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /contracts/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /mappings/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
+
+
+

and com.example.foo:bar

+
+
+
    +
  • +

    /META-INF/com.example.foo/bar/*/.*

    +
  • +
  • +

    /contracts/com.example.foo/bar/*/.*

    +
  • +
  • +

    /mappings/com.example.foo/bar/*/.*

    +
  • +
+
+
+ + + + + +
+ + +As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs. +
+
+
+

The producer would setup the contracts like this:

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                └── com.example
+                    └── beer-api-producer-restdocs
+                        └── nested
+                            └── contract3.groovy
+
+
+
+

To achieve proper stub packaging.

+
+
+

Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar.

+
+
+
+
└── META-INF
+    └── com.example
+        └── beer-api-producer-restdocs
+            └── 2.0.0
+                ├── contracts
+                │   └── nested
+                │       └── contract2.groovy
+                └── mappings
+                    └── mapping.json
+
+
+
+

By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts.

+
+
+
+
Configuring HTTP Server Stubs
+
+

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub.

+
+
+

Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

+
+
+
WireMockHttpServerStubConfigurer implementation
+
+
@CompileStatic
+static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+	@Override
+	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+			int httpsPort = SocketUtils.findAvailableTcpPort()
+			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+			return httpStubConfiguration
+					.httpsPort(httpsPort)
+		}
+		return httpStubConfiguration
+	}
+}
+
+
+
+

You can then reuse it via the annotation

+
+
+
+
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+
+
+
+

Whenever an https port is found, it will take precedence over the http one.

+
+
+
+
+

6.3.2. Running stubs

+
+
Running using main app
+
+

You can set the following options to the main class:

+
+
+
+
-c, --classifier                Suffix for the jar containing stubs (e.
+                                  g. 'stubs' if the stub jar would
+                                  have a 'stubs' classifier for stubs:
+                                  foobar-stubs ). Defaults to 'stubs'
+                                  (default: stubs)
+--maxPort, --maxp <Integer>     Maximum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  15000 (default: 15000)
+--minPort, --minp <Integer>     Minimum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  10000 (default: 10000)
+-p, --password                  Password to user when connecting to
+                                  repository
+--phost, --proxyHost            Proxy host to use for repository
+                                  requests
+--pport, --proxyPort [Integer]  Proxy port to use for repository
+                                  requests
+-r, --root                      Location of a Jar containing server
+                                  where you keep your stubs (e.g. http:
+                                  //nexus.
+                                  net/content/repositories/repository)
+-s, --stubs                     Comma separated list of Ivy
+                                  representation of jars with stubs.
+                                  Eg. groupid:artifactid1,groupid2:
+                                  artifactid2:classifier
+--sm, --stubsMode               Stubs mode to be used. Acceptable values
+                                  [CLASSPATH, LOCAL, REMOTE]
+-u, --username                  Username to user when connecting to
+                                  repository
+
+
+
+
+
HTTP Stubs
+
+

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

+
+
+

Example:

+
+
+
+
{
+    "request": {
+        "method": "GET",
+        "url": "/ping"
+    },
+    "response": {
+        "status": 200,
+        "body": "pong",
+        "headers": {
+            "Content-Type": "text/plain"
+        }
+    }
+}
+
+
+
+
+
Viewing registered mappings
+
+

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

+
+
+

You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this

+
+
+
+
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
+mappingsOutputFolder = "target/outputmappings/")
+
+
+
+

and for the JUnit approach like this:

+
+
+
+
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
+			.repoRoot("https://some_url")
+			.downloadStub("a.b.c", "loanIssuance")
+			.downloadStub("a.b.c:fraudDetectionServer")
+			.withMappingsOutputFolder("target/outputmappings")
+
+
+
+

Then if you check out the folder target/outputmappings you would see the following structure

+
+
+
+
.
+├── fraudDetectionServer_13705
+└── loanIssuance_12255
+
+
+
+

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server:

+
+
+
+
[{
+  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
+  "request" : {
+    "url" : "/name",
+    "method" : "GET"
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "fraudDetectionServer"
+  },
+  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
+},
+...
+]
+
+
+
+
+
Messaging Stubs
+
+

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

+
+
+
+
+
+

6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

+
+

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

+
+
+
    +
  • +

    download them

    +
  • +
  • +

    cache them locally

    +
  • +
  • +

    unzip them to a temporary folder

    +
  • +
  • +

    start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port

    +
  • +
  • +

    feed the WireMock server with all JSON files that are valid WireMock definitions

    +
  • +
  • +

    can also send messages (remember to pass an implementation of MessageVerifier interface)

    +
  • +
+
+
+

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information.

+
+
+

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+
+import org.springframework.cloud.contract.spec.Contract;
+
+/**
+ * Contract for finding registered stubs.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubFinder extends StubTrigger {
+
+	/**
+	 * For the given groupId and artifactId tries to find the matching URL of the running
+	 * stub.
+	 * @param groupId - might be null. In that case a search only via artifactId takes
+	 * place
+	 * @param artifactId - artifact id of the stub
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
+
+	/**
+	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
+	 * tries to find the matching URL of the running stub. You can also pass only
+	 * {@code artifactId}.
+	 * @param ivyNotation - Ivy representation of the Maven artifact
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
+
+	/**
+	 * @return all running stubs
+	 */
+	RunningStubs findAllRunningStubs();
+
+	/**
+	 * @return the list of Contracts
+	 */
+	Map<StubConfiguration, Collection<Contract>> getContracts();
+
+}
+
+
+
+

Example of usage in Spock tests:

+
+
+
+
@ClassRule
+@Shared
+StubRunnerRule rule = new StubRunnerRule()
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule")
+
+
+def 'should start WireMock servers'() {
+	expect: 'WireMocks are running'
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+		rule.findStubUrl('loanIssuance') != null
+		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+	and:
+		rule.findAllRunningStubs().isPresent('loanIssuance')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+	and: 'Stubs were registered'
+		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+}
+
+def 'should output mappings to output folder'() {
+	when:
+		def url = rule.findStubUrl('fraudDetectionServer')
+	then:
+		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
+}
+
+
+
+

Example of usage in JUnit tests:

+
+
+
+
	@Test
+	public void should_start_wiremock_servers() throws Exception {
+		// expect: 'WireMocks are running'
+		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
+		then(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isNotNull();
+		// and:
+		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs",
+				"fraudDetectionServer")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isTrue();
+		// and: 'Stubs were registered'
+		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
+				.isEqualTo("loanIssuance");
+		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
+				.isEqualTo("fraudDetectionServer");
+	}
+
+	private String httpGet(String url) throws Exception {
+		try (InputStream stream = URI.create(url).toURL().openStream()) {
+			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
+		}
+	}
+
+}
+
+
+
+

JUnit 5 Extension example:

+
+
+
+
// Visible for Junit
+@RegisterExtension
+static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
+		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule");
+
+@BeforeAll
+@AfterAll
+static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+private static String repoRoot() {
+	try {
+		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
+				.toURI().toString();
+	}
+	catch (Exception e) {
+		return "";
+	}
+}
+
+
+
+

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

+
+
+ + + + + +
+ + +To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown. +
+
+
+

6.4.1. Maven settings

+
+

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

+
+
+
+

6.4.2. Providing fixed ports

+
+

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

+
+
+
+

6.4.3. Fluent API

+
+

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.withPort(12345).downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

You can see that for this example the following test is valid:

+
+
+
+
then(rule.findStubUrl("loanIssuance"))
+		.isEqualTo(URI.create("http://localhost:12345").toURL());
+then(rule.findStubUrl("fraudDetectionServer"))
+		.isEqualTo(URI.create("http://localhost:12346").toURL());
+
+
+
+
+

6.4.4. Stub Runner with Spring

+
+

Sets up Spring configuration of the Stub Runner project.

+
+
+

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs.

+
+
+

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
+		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
+		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
+@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+@ActiveProfiles("test")
+class StubRunnerConfigurationSpec extends Specification {
+
+	@Autowired
+	StubFinder stubFinder
+	@Autowired
+	Environment environment
+	@StubRunnerPort("fraudDetectionServer")
+	int fraudDetectionServerPort
+	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+	int fraudDetectionServerPortWithGroupId
+	@Value('${foo}')
+	Integer foo
+
+	@BeforeClass
+	@AfterClass
+	void setupProps() {
+		System.clearProperty("stubrunner.repository.root")
+		System.clearProperty("stubrunner.classifier")
+	}
+
+	def 'should start WireMock servers'() {
+		expect: 'WireMocks are running'
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+		and:
+			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+		and: 'Stubs were registered'
+			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+		and: 'Fraud Detection is an HTTPS endpoint'
+			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
+	}
+
+	def 'should throw an exception when stub is not found'() {
+		when:
+			stubFinder.findStubUrl('nonExistingService')
+		then:
+			thrown(StubNotFoundException)
+		when:
+			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
+		then:
+			thrown(StubNotFoundException)
+	}
+
+	def 'should register started servers as environment variables'() {
+		expect:
+			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
+			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
+	}
+
+	def 'should be able to interpolate a running stub in the passed test property'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			environment.getProperty("foo", Integer) == fraudPort
+			environment.getProperty("fooWithGroup", Integer) == fraudPort
+			foo == fraudPort
+	}
+
+	@Issue("#573")
+	def 'should be able to retrieve the port of a running stub via an annotation'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			fraudDetectionServerPort == fraudPort
+			fraudDetectionServerPortWithGroupId == fraudPort
+	}
+
+	def 'should dump all mappings to a file'() {
+		when:
+			def url = stubFinder.findStubUrl("fraudDetectionServer")
+		then:
+			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
+	}
+
+	@Configuration
+	@EnableAutoConfiguration
+	static class Config {}
+
+	@CompileStatic
+	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+		@Override
+		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+				int httpsPort = SocketUtils.findAvailableTcpPort()
+				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+				return httpStubConfiguration
+						.httpsPort(httpsPort)
+			}
+			return httpStubConfiguration
+		}
+	}
+}
+
+
+
+

for the following configuration file:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids:
+    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
+    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
+    - org.springframework.cloud.contract.verifier.stubs:bootService
+  stubs-mode: remote
+
+
+
+

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation.

+
+
+
+
@AutoConfigureStubRunner(
+		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
+				"org.springframework.cloud.contract.verifier.stubs:bootService"],
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		repositoryRoot = "classpath:m2repo/repository/")
+
+
+
+

Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar.

+
+
+
    +
  • +

    stubrunner.runningstubs.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.bar.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.bar.port

    +
  • +
+
+
+

Which you can reference in your code.

+
+
+

You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar.

+
+
+
+
@StubRunnerPort("foo")
+int fooPort;
+@StubRunnerPort("com.example:bar")
+int barPort;
+
+
+
+
+
+

6.5. Stub Runner Spring Cloud

+
+

Stub Runner can integrate with Spring Cloud.

+
+
+

For real life examples you can check the

+
+ +
+

6.5.1. Stubbing Service Discovery

+
+

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

+
+
+
    +
  • +

    DiscoveryClient

    +
  • +
  • +

    Ribbon ServerList

    +
  • +
+
+
+

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

+
+
+

For example this test will pass

+
+
+
+
def 'should make service discovery work'() {
+	expect: 'WireMocks are running'
+		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+	and: 'Stubs can be reached via load service discovery'
+		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
+		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
+}
+
+
+
+

for the following configuration file

+
+
+
+
stubrunner:
+  idsToServiceIds:
+    ivyNotation: someValueInsideYourCode
+    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer
+
+
+
+
Test profiles and service discovery
+
+

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features.

+
+
+

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka)

+
+
+
+
    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
+    static {
+        System.setProperty("eureka.client.enabled", "false");
+        System.setProperty("spring.cloud.config.failFast", "false");
+    }
+
+
+
+
+
+

6.5.2. Additional Configuration

+
+

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

+
+
+ + + + + +
+ + +By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones. +
+
+
+

The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables

+
+
+
    +
  • +

    maven.repo.local - path to the custom maven local repository location

    +
  • +
  • +

    org.apache.maven.user-settings - path to custom maven user settings location

    +
  • +
  • +

    org.apache.maven.global-settings - path to maven global settings location

    +
  • +
+
+
+
+
+

6.6. Stub Runner Boot Application

+
+

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers.

+
+
+

One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information.

+
+
+

6.6.1. How to use it?

+
+
Stub Runner Server
+
+

Just add the

+
+
+
+
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
+
+
+
+

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

+
+
+

For the properties check the Stub Runner Spring section.

+
+
+
+
Stub Runner Server Fat Jar
+
+

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

+
+
+
+
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
+
+
+
+
+
Spring Cloud CLI
+
+

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner.

+
+
+

In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally)

+
+
+
stubrunner.yml
+
+
stubrunner:
+  stubsMode: LOCAL
+  ids:
+    - com.example:beer-api-producer:+:9876
+
+
+
+

and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750.

+
+
+
+
+

6.6.2. Endpoints

+
+
HTTP
+
+
    +
  • +

    GET /stubs - returns a list of all running stubs in ivy:integer notation

    +
  • +
  • +

    GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
Messaging
+
+

For Messaging

+
+
+
    +
  • +

    GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation

    +
  • +
  • +

    POST /triggers/{label} - executes a trigger with label

    +
  • +
  • +

    POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
+

6.6.3. Example

+
+
+
@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
+@ActiveProfiles("test")
+class StubRunnerBootSpec extends Specification {
+
+	@Autowired
+	StubRunning stubRunning
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
+				new TriggerController(stubRunning))
+	}
+
+	def 'should return a list of running stub servers in "full ivy:port" notation'() {
+		when:
+			String response = RestAssuredMockMvc.get('/stubs').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
+	}
+
+	def 'should return a port on which a [#stubId] stub is running'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
+		then:
+			response.statusCode == 200
+			Integer.valueOf(response.body.asString()) > 0
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService',
+					   'bootService']
+	}
+
+	def 'should return 404 when missing stub was called'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
+		then:
+			response.statusCode == 404
+	}
+
+	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
+		when:
+			String response = RestAssuredMockMvc.get('/triggers').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
+	}
+
+	def 'should trigger a messaging label'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger('delete_book')
+	}
+
+	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger(stubId, 'delete_book')
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
+	}
+
+	def 'should throw exception when trigger is missing'() {
+		when:
+			RestAssuredMockMvc.post("/triggers/missing_label")
+		then:
+			Exception e = thrown(Exception)
+			e.message.contains("Exception occurred while trying to return [missing_label] label.")
+			e.message.contains("Available labels are")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
+	}
+
+}
+
+
+
+
+

6.6.4. Stub Runner Boot with Service Discovery

+
+

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios.

+
+
+

The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running.

+
+
+
+
@SpringBootApplication
+@EnableStubRunnerServer
+@EnableEurekaClient
+@AutoConfigureStubRunner
+public class StubRunnerBootEurekaExample {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
+	}
+
+}
+
+
+
+

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

+
+
+

Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties

+
+
+
+
* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
+* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
+* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
+* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
+* cloud.contract.verifier.stubs:bootService (3)
+* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
+* someNameThatShouldMapFraudDetectionServer (4)
+*
+* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
+* behaviour where the discovery service is stubbed. That's why the stub registration will
+* be picked (3) - we provide a list of stubs to download (4) - we provide a list of
+
+
+
+

That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot.

+
+
+
+
+

6.7. Stubs Per Consumer

+
+

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

+
+
+ + + + + +
+ + +This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it. +
+
+
+

Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer.

+
+
+

Consumer foo-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       foo: "foo"
+    }
+}
+
+
+
+

Consumer bar-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       bar: "bar"
+    }
+}
+
+
+
+

You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature.

+
+
+

On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered.

+
+
+

On the foo producer side the contracts would look like this

+
+
+
+
.
+└── contracts
+    ├── bar-consumer
+    │   ├── bookReturnedForBar.groovy
+    │   └── shouldCallBar.groovy
+    └── foo-consumer
+        ├── bookReturnedForFoo.groovy
+        └── shouldCallFoo.groovy
+
+
+
+

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

Or set the consumer name explicitly

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		consumerName = "foo-consumer",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

You can check out issue 224 for more +information about the reasons behind this change.

+
+
+
+

6.8. Common

+
+

This section briefly describes common properties, including:

+
+ +
+

6.8.1. Common Properties for JUnit and Spring

+
+

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

+
+
+

6.8.2. Stub Runner Stubs IDs

+
+

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

+
+
+
+
groupId:artifactId:version:classifier:port
+
+
+
+

Note that version, classifier and port are optional.

+
+
+
    +
  • +

    If you do not provide the port, a random one will be picked.

    +
  • +
  • +

    If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).

    +
  • +
  • +

    If you do not provide the version, then the + will be passed and the latest one is +downloaded.

    +
  • +
+
+
+

port means the port of the WireMock server.

+
+
+ + + + + +
+ + +Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here. +
+
+
+
+
+

6.9. Stub Runner Docker

+
+

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

+
+
+

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here Docker Project.

+
+
+

6.9.1. How to use it

+
+

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

+
+
+
+

6.9.2. Example of client side usage in a non JVM project

+
+

We’d like to use the stubs created in this Server side (nodejs) step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

Let’s run the Stub Runner Boot application with the stubs.

+
+
+
+
# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
+
+
+
+

What’s happening is that

+
+
+
    +
  • +

    a standalone Stub Runner application got started

    +
  • +
  • +

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    +
  • +
  • +

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    +
  • +
  • +

    after a while Stub Runner will be running on port 8083

    +
  • +
  • +

    and the stubs will be running at port 9876

    +
  • +
+
+
+

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

+
+
+
+
# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
+
+
+
+ + + + + +
+ + +If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" +
+
+
+
+
+
+
+

7. Stub Runner for Messaging

+
+
+

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

+
+
+
    +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Apache Camel

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

It also provides entry points to integrate with any other solution on the market.

+
+
+ + + + + +
+ + +If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP. +
+
+
+

7.1. Stub triggering

+
+

To trigger a message, use the StubTrigger interface:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Contract for triggering stub messages.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubTrigger {
+
+	/**
+	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
+	 * You can use only {@code artifactId} too.
+	 *
+	 * Feature related to messaging.
+	 * @param ivyNotation ivy notation of a stub
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String ivyNotation, String labelName);
+
+	/**
+	 * Triggers an event by a given label.
+	 *
+	 * Feature related to messaging.
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String labelName);
+
+	/**
+	 * Triggers all possible events.
+	 *
+	 * Feature related to messaging.
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger();
+
+	/**
+	 * Feature related to messaging.
+	 * @return a mapping of ivy notation of a dependency to all the labels it has.
+	 */
+	Map<String, Collection<String>> labels();
+
+}
+
+
+
+

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

+
+
+

StubTrigger gives you the following options to trigger a message:

+
+ +
+

7.1.1. Trigger by Label

+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+
+

7.1.2. Trigger by Group and Artifact Ids

+
+
+
stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')
+
+
+
+
+

7.1.3. Trigger by Artifact Ids

+
+
+
stubFinder.trigger('streamService', 'return_book_1')
+
+
+
+
+

7.1.4. Trigger All Messages

+
+
+
stubFinder.trigger()
+
+
+
+
+
+

7.2. Stub Runner Camel

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes.

+
+
+

7.2.1. Adding it to the project

+
+

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.2.2. Disabling the functionality

+
+

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

+
+
+
+

7.2.3. Examples

+
+
Stubs structure
+
+

Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application.

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── camelService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── camelService-0.0.1-SNAPSHOT.pom
+                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

And the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Let’s consider the following contracts (let' number it with 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and number 2

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('jms:input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
+
Scenario 1 (no input message)
+
+

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])
+
+
+
+
+
+
+

7.3. Stub Runner Integration

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes.

+
+
+

7.3.1. Adding the Runner to the Project

+
+

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.3.2. Disabling the functionality

+
+

If you need to disable this functionality, set the +stubrunner.integration.enabled=false property.

+
+
+

Assume that you have the following Maven repository with deployed stubs for the +integrationService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── integrationService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
+                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and the following Spring Integration Route:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			 xmlns:beans="http://www.springframework.org/schema/beans"
+			 xmlns="http://www.springframework.org/schema/integration"
+			 xsi:schemaLocation="http://www.springframework.org/schema/beans
+			https://www.springframework.org/schema/beans/spring-beans.xsd
+			http://www.springframework.org/schema/integration
+			http://www.springframework.org/schema/integration/spring-integration.xsd">
+
+
+	<!-- REQUIRED FOR TESTING -->
+	<bridge input-channel="output"
+			output-channel="outputTest"/>
+
+	<channel id="outputTest">
+		<queue/>
+	</channel>
+
+</beans:beans>
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message would pass the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the input destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

7.4. Stub Runner Stream

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes.

+
+
+ + + + + +
+ + +If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support. +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+

7.4.1. Adding the Runner to the Project

+
+

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.4.2. Disabling the functionality

+
+

If you need to disable this functionality, set the stubrunner.stream.enabled=false +property.

+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +streamService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── streamService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── streamService-0.0.1-SNAPSHOT.pom
+                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input { triggeredBy('bookReturnedTriggered()') }
+	outputMessage {
+		sentTo('returnBook')
+		body('''{ "bookName" : "foo" }''')
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('bookStorage')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders { header('sample', 'header') }
+	}
+	outputMessage {
+		sentTo('returnBook')
+		body([
+				bookName: 'foo'
+		])
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner.repositoryRoot: classpath:m2repo/repository/
+stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
+stubrunner.stubs-mode: remote
+spring:
+  cloud:
+    stream:
+      bindings:
+        output:
+          destination: returnBook
+        input:
+          destination: bookStorage
+
+server:
+  port: 0
+
+debug: true
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to a channel whose destination is +returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the bookStorage +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')
+
+
+
+

To listen to the output of the message sent to returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

7.5. Stub Runner Spring AMQP

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes.

+
+
+

The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application.

+
+
+

On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context.

+
+
+

As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners.

+
+
+

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header.

+
+
+

7.5.1. Adding the Runner to the Project

+
+

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner.

+
+
+ + + + + +
+ + +If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties. +
+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application.

+
+
+
+
└── .m2
+    └── repository
+        └── com
+            └── example
+                └── spring-cloud-contract-amqp-test
+                    ├── 0.4.0-SNAPSHOT
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
+                    │   └── maven-metadata-local.xml
+                    └── maven-metadata-local.xml
+
+
+
+

Further assume that the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── contracts
+    └── shouldProduceValidPersonData.groovy
+
+
+
+

Consider the following contract:

+
+
+
+
Contract.make {
+	// Human readable description
+	description 'Should produce valid person data'
+	// Label by means of which the output message can be triggered
+	label 'contract-test.person.created.event'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('createPerson()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo 'contract-test.exchange'
+		headers {
+			header('contentType': 'application/json')
+			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
+		}
+		// the body of the output message
+		body([
+				id  : $(consumer(9), producer(regex("[0-9]+"))),
+				name: "me"
+		])
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
+  stubs-mode: remote
+  amqp:
+    enabled: true
+server:
+  port: 0
+
+
+
+
Triggering the message
+
+

To trigger a message using the contract above, use the StubTrigger interface as +follows:

+
+
+
+
stubTrigger.trigger("contract-test.person.created.event")
+
+
+
+

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange.

+
+
+
+
@Bean
+public Binding binding() {
+	return BindingBuilder.bind(new Queue("test.queue"))
+			.to(new DirectExchange("contract-test.exchange")).with("#");
+}
+
+
+
+

The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message.

+
+
+
+
@Bean
+public SimpleMessageListenerContainer simpleMessageListenerContainer(
+		ConnectionFactory connectionFactory,
+		MessageListenerAdapter listenerAdapter) {
+	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
+	container.setConnectionFactory(connectionFactory);
+	container.setQueueNames("test.queue");
+	container.setMessageListener(listenerAdapter);
+
+	return container;
+}
+
+
+
+

Also, the following annotated listener matches and is invoked:

+
+
+
+
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
+		exchange = @Exchange(value = "contract-test.exchange",
+				ignoreDeclarationExceptions = "true")))
+public void handlePerson(Person person) {
+	this.person = person;
+}
+
+
+
+ + + + + +
+ + +The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer. +
+
+
+
+
Spring AMQP Test Configuration
+
+

In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory.

+
+
+

To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false

+
+
+
+
stubrunner:
+  amqp:
+    mockConnection: false
+
+
+
+
+
+
+
+
+

8. Contract DSL

+
+
+

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

+
+
+

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

+
+
+ + + + + +
+ + +Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }. +
+
+
+ + + + + +
+ + +Spring Cloud Contract supports defining multiple contracts in a single file. +
+
+
+

The following is a complete example of a Groovy contract definition:

+
+
+
+
+
+
+
+

The following is a complete example of a YAML contract definition:

+
+
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+ + + + + +
+ + +You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert +
+
+
+

8.1. Limitations

+
+ + + + + +
+ + +Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. +
+
+
+ + + + + +
+ + +The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration. +
+
+
+ + + + + +
+ + +Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation. +
+
+
+
+

8.2. Common Top-Level elements

+
+

The following sections describe the most common top-level elements:

+
+ +
+

8.2.1. Description

+
+

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

+
+
+
Groovy DSL
+
+
			org.springframework.cloud.contract.spec.Contract.make {
+				description('''
+given:
+	An input
+when:
+	Sth happens
+then:
+	Output
+''')
+			}
+
+
+
+
YAML
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+
+

8.2.2. Name

+
+

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

+
+
+ + + + + +
+ + +You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. +
+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	name("some_special_name")
+}
+
+
+
+
YAML
+
+
name: some name
+
+
+
+
+

8.2.3. Ignoring Contracts

+
+

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	ignored()
+}
+
+
+
+
YAML
+
+
ignored: true
+
+
+
+
+

8.2.4. Passing Values from Files

+
+

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json
+
+
+
+

Further assume that your contract is as follows:

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		method('PUT')
+		headers {
+			contentType(applicationJson())
+		}
+		body(file("request.json"))
+		url("/1")
+	}
+	response {
+		status OK()
+		body(file("response.json"))
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /foo
+  bodyFromFile: request.json
+response:
+  status: 200
+  bodyFromFile: response.json
+
+
+
+

Further assume that the JSON files is as follows:

+
+
+

request.json

+
+
+
+
{
+  "status": "REQUEST"
+}
+
+
+
+

response.json

+
+
+
+
{
+  "status": "RESPONSE"
+}
+
+
+
+

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

+
+
+

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		url("/1")
+		method(PUT())
+		headers {
+			contentType(applicationOctetStream())
+		}
+		body(fileAsBytes("request.pdf"))
+	}
+	response {
+		status 200
+		body(fileAsBytes("response.pdf"))
+		headers {
+			contentType(applicationOctetStream())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  url: /1
+  method: PUT
+  headers:
+    Content-Type: application/octet-stream
+  bodyFromFileAsBytes: request.pdf
+response:
+  status: 200
+  bodyFromFileAsBytes: response.pdf
+  headers:
+    Content-Type: application/octet-stream
+
+
+
+ + + + + +
+ + +You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +
+
+
+
+

8.2.5. HTTP Top-Level Elements

+
+

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	// Definition of HTTP request part of the contract
+	// (this can be a valid request or invalid depending
+	// on type of contract being specified).
+	request {
+		method GET()
+		url "/foo"
+		//...
+	}
+
+	// Definition of HTTP response part of the contract
+	// (a service implementing this contract should respond
+	// with following response after receiving request
+	// specified in "request" part above).
+	response {
+		status 200
+		//...
+	}
+
+	// Contract priority, which can be used for overriding
+	// contracts (1 is highest). Priority is optional.
+	priority 1
+}
+
+
+
+
YAML
+
+
priority: 8
+request:
+...
+response:
+...
+
+
+
+ + + + + +
+ + +If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10. +
+
+
+
+
+

8.3. Request

+
+

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		// HTTP request method (GET/POST/PUT/DELETE).
+		method 'GET'
+
+		// Path component of request URL is specified as follows.
+		urlPath('/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
method: PUT
+url: /foo
+
+
+
+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+
+		// Specifying `url` and `urlPath` in one contract is illegal.
+		url('http://localhost:8888/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  urlPath: /foo
+
+
+
+

request may contain query parameters.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+
+		urlPath('/users') {
+
+			// Each parameter is specified in form
+			// `'paramName' : paramValue` where parameter value
+			// may be a simple literal or one of matcher functions,
+			// all of which are used in this example.
+			queryParameters {
+
+				// If a simple literal is used as value
+				// default matcher function is used (equalTo)
+				parameter 'limit': 100
+
+				// `equalTo` function simply compares passed value
+				// using identity operator (==).
+				parameter 'filter': equalTo("email")
+
+				// `containing` function matches strings
+				// that contains passed substring.
+				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
+
+				// `matching` function tests parameter
+				// against passed regular expression.
+				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
+
+				// `notMatching` functions tests if parameter
+				// does not match passed regular expression.
+				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
+			}
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+  queryParameters:
+    a: b
+    b: c
+  headers:
+    foo: bar
+    fooReq: baz
+  cookies:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  fixedDelayMilliseconds: 1000
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+    cookies:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        predefined:
+
+
+
+

request may contain additional request headers, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each header is added in form `'Header-Name' : 'Header-Value'`.
+		// there are also some helper methods
+		headers {
+			header 'key': 'value'
+			contentType(applicationJson())
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+headers:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain additional request cookies, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
+		// there are also some helper methods
+		cookies {
+			cookie 'key': 'value'
+			cookie('another_key', 'another_value')
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+cookies:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain a request body:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Currently only JSON format of request body is supported.
+		// Format will be determined from a header or body's content.
+		body '''{ "login" : "john", "name": "John The Contract" }'''
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+body:
+  foo: bar
+
+
+
+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  url: /multipart
+  headers:
+    Content-Type: multipart/form-data;boundary=AaB03x
+  multipart:
+    params:
+      # key (parameter name), value (parameter value) pair
+      formParameter: '"formParameterValue"'
+      someBooleanParameter: true
+    named:
+      - paramName: file
+        fileName: filename.csv
+        fileContent: file content
+  matchers:
+    multipart:
+      params:
+        - key: formParameter
+          regex: ".+"
+        - key: someBooleanParameter
+          predefined: any_boolean
+      named:
+        - paramName: file
+          fileName:
+            predefined: non_empty
+          fileContent:
+            predefined: non_empty
+response:
+  status: 200
+
+
+
+

In the preceding example, we define parameters in either of two ways:

+
+
+
Groovy DSL
+
    +
  • +

    Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).

    +
  • +
  • +

    By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

    +
  • +
+
+
+
YAML
+
    +
  • +

    The multipart parameters are set via multipart.params section

    +
  • +
  • +

    The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields

    +
  • +
  • +

    The dynamic bits can be set via the matchers.multipart section

    +
    +
      +
    • +

      for parameters use the params section that can accept +regex or a predefined regular expression

      +
    • +
    • +

      for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

      +
    • +
    +
    +
  • +
+
+
+

From this contract, the generated test is as follows:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+

The WireMock stub is as follows:

+
+
+
+
			'''
+{
+  "request" : {
+	"url" : "/multipart",
+	"method" : "PUT",
+	"headers" : {
+	  "Content-Type" : {
+		"matches" : "multipart/form-data;boundary=AaB03x.*"
+	  }
+	},
+	"bodyPatterns" : [ {
+		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
+  		}, {
+    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
+  		}, {
+	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
+	} ]
+  },
+  "response" : {
+	"status" : 200,
+	"transformers" : [ "response-template", "foo-transformer" ]
+  }
+}
+	'''
+
+
+
+
+

8.4. Response

+
+

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+	}
+	response {
+		// Status code sent by the server
+		// in response to request specified above.
+		status OK()
+	}
+}
+
+
+
+
YAML
+
+
response:
+...
+status: 200
+
+
+
+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

+
+
+ + + + + +
+ + +Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400. +
+
+
+
+

8.5. Dynamic properties

+
+

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

+
+
+

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

+
+
+ + + + + +
+ + +Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information. +
+
+
+

For YAML you can only use the matchers section.

+
+
+

8.5.1. Dynamic properties inside the body

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

+
+
+
+
value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

The following example shows how to set dynamic properties with $():

+
+
+
+
$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

+
+
+
+

8.5.2. Regular expressions

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

+
+
+

Make sure that regex matches a whole region of a sequence as internally a call to +Pattern.matches() +is called. For instance, abc pattern doesn’t match aabc string but .abc does. +There are several additional known limitations as well.

+
+
+

The following example shows how to use regular expressions to write a request:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method('GET')
+		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
+	}
+	response {
+		status OK()
+		body(
+				id: $(anyNumber()),
+				surname: $(
+						consumer('Kowalsky'),
+						producer(regex('[a-zA-Z]+'))
+				),
+				name: 'Jan',
+				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
+				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
+						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
+				)
+		)
+		headers {
+			header 'Content-Type': 'text/plain'
+		}
+	}
+}
+
+
+
+

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url value(consumer(regex('/foo/[0-9]{5}')))
+		body([
+				requestElement: $(consumer(regex('[0-9]{5}')))
+		])
+		headers {
+			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
+		}
+	}
+	response {
+		status OK()
+		body([
+				responseElement: $(producer(regex('[0-9]{7}')))
+		])
+		headers {
+			contentType("application/vnd.fraud.v1+json")
+		}
+	}
+}
+
+
+
+

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

+
+
+

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

+
+
+
+
protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
+
+protected static final Pattern ALPHA_NUMERIC = Pattern.compile("[a-zA-Z0-9]+");
+
+protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile("[\\p{L}]*");
+
+protected static final Pattern NUMBER = Pattern.compile("-?(\\d*\\.\\d+|\\d+)");
+
+protected static final Pattern INTEGER = Pattern.compile("-?(\\d+)");
+
+protected static final Pattern POSITIVE_INT = Pattern.compile("([1-9]\\d*)");
+
+protected static final Pattern DOUBLE = Pattern.compile("-?(\\d*\\.\\d+)");
+
+protected static final Pattern HEX = Pattern.compile("[a-fA-F0-9]+");
+
+protected static final Pattern IP_ADDRESS = Pattern.compile(
+		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
+
+protected static final Pattern HOSTNAME_PATTERN = Pattern
+		.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
+
+protected static final Pattern EMAIL = Pattern
+		.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
+
+protected static final Pattern URL = UrlHelper.URL;
+
+protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
+
+protected static final Pattern UUID = Pattern
+		.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
+
+protected static final Pattern ANY_DATE = Pattern
+		.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+
+protected static final Pattern ANY_DATE_TIME = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern ANY_TIME = Pattern
+		.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
+
+protected static final Pattern NON_BLANK = Pattern.compile("^\\s*\\S[\\S\\s]*");
+
+protected static final Pattern ISO8601_WITH_OFFSET = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d{3})?(Z|[+-][01]\\d:[0-5]\\d)");
+
+protected static Pattern anyOf(String... values) {
+	return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$')
+			.collect(Collectors.joining("|")));
+}
+
+public static String multipartParam(Object name, Object value) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"\r\n(Content-Type: .*\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ value + "\r\n--\\1.*";
+}
+
+public static String multipartFile(Object name, Object filename, Object content,
+		Object contentType) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
+			+ toContentType(contentType)
+			+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ content + "\r\n--\\1.*";
+}
+
+private static String toContentType(Object contentType) {
+	if (contentType == null) {
+		return ".*";
+	}
+	if (contentType instanceof RegexProperty) {
+		return ((RegexProperty) contentType).pattern();
+	}
+	return contentType.toString();
+}
+
+public RegexProperty onlyAlphaUnicode() {
+	return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
+}
+
+public RegexProperty alphaNumeric() {
+	return new RegexProperty(ALPHA_NUMERIC).asString();
+}
+
+public RegexProperty number() {
+	return new RegexProperty(NUMBER).asDouble();
+}
+
+public RegexProperty positiveInt() {
+	return new RegexProperty(POSITIVE_INT).asInteger();
+}
+
+public RegexProperty anyBoolean() {
+	return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
+}
+
+public RegexProperty anInteger() {
+	return new RegexProperty(INTEGER).asInteger();
+}
+
+public RegexProperty aDouble() {
+	return new RegexProperty(DOUBLE).asDouble();
+}
+
+public RegexProperty ipAddress() {
+	return new RegexProperty(IP_ADDRESS).asString();
+}
+
+public RegexProperty hostname() {
+	return new RegexProperty(HOSTNAME_PATTERN).asString();
+}
+
+public RegexProperty email() {
+	return new RegexProperty(EMAIL).asString();
+}
+
+public RegexProperty url() {
+	return new RegexProperty(URL).asString();
+}
+
+public RegexProperty httpsUrl() {
+	return new RegexProperty(HTTPS_URL).asString();
+}
+
+public RegexProperty uuid() {
+	return new RegexProperty(UUID).asString();
+}
+
+public RegexProperty isoDate() {
+	return new RegexProperty(ANY_DATE).asString();
+}
+
+public RegexProperty isoDateTime() {
+	return new RegexProperty(ANY_DATE_TIME).asString();
+}
+
+public RegexProperty isoTime() {
+	return new RegexProperty(ANY_TIME).asString();
+}
+
+
+
+

In your contract, you can use it as shown in the following example:

+
+
+
+
Contract dslWithOptionalsInString = Contract.make {
+	priority 1
+	request {
+		method POST()
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123"))),
+				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
+		)
+	}
+}
+
+
+
+

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

+
+
+
+
+
+
+
+

and this is an example of how you can reference those methods:

+
+
+
+
Contract contractDsl = Contract.make {
+	name "foo"
+	label 'trigger_event'
+	input {
+		triggeredBy('toString()')
+	}
+	outputMessage {
+		sentTo 'topic.rateablequote'
+		body([
+				alpha            : $(anyAlphaUnicode()),
+				number           : $(anyNumber()),
+				anInteger        : $(anyInteger()),
+				positiveInt      : $(anyPositiveInt()),
+				aDouble          : $(anyDouble()),
+				aBoolean         : $(aBoolean()),
+				ip               : $(anyIpAddress()),
+				hostname         : $(anyHostname()),
+				email            : $(anyEmail()),
+				url              : $(anyUrl()),
+				httpsUrl         : $(anyHttpsUrl()),
+				uuid             : $(anyUuid()),
+				date             : $(anyDate()),
+				dateTime         : $(anyDateTime()),
+				time             : $(anyTime()),
+				iso8601WithOffset: $(anyIso8601WithOffset()),
+				nonBlankString   : $(anyNonBlankString()),
+				nonEmptyString   : $(anyNonEmptyString()),
+				anyOf            : $(anyOf('foo', 'bar'))
+		])
+	}
+}
+
+
+
+
Limitations
+
+ + + + + +
+ + +Due to certain limitations of Xeger library that generates string out of +regex, do not use $ and ^ signs in your regex if you rely on automatic +generation. Issue 899 +
+
+
+ + + + + +
+ + +Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). +It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. +Issue 900 +
+
+
+
+
+

8.5.3. Passing Optional Parameters

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

+
+
+
    +
  • +

    STUB side of the Request

    +
  • +
  • +

    TEST side of the Response

    +
  • +
+
+
+

The following example shows how to provide optional parameters:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	priority 1
+	name "optionals"
+	request {
+		method 'POST'
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123")))
+		)
+	}
+}
+
+
+
+

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

+
+
+

If you use Spock for, the following test would be generated from the previous example:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
+import io.restassured.response.ResponseOptions
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+
+\tdef validate_optionals() throws Exception {
+\t\tgiven:
+\t\t\tMockMvcRequestSpecification request = given()
+\t\t\t\t\t.header("Content-Type", "application/json")
+\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
+
+\t\twhen:
+\t\t\tResponseOptions response = given().spec(request)
+\t\t\t\t\t.post("/users/password")
+
+\t\tthen:
+\t\t\tresponse.statusCode() == 404
+\t\t\tresponse.header("Content-Type") == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
+\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
+\t}
+
+}
+"""
+
+
+
+

The following stub would also be generated:

+
+
+
+
					'''
+{
+  "request" : {
+	"url" : "/users/password",
+	"method" : "POST",
+	"bodyPatterns" : [ {
+	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
+	}, {
+	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
+	} ],
+	"headers" : {
+	  "Content-Type" : {
+		"equalTo" : "application/json"
+	  }
+	}
+  },
+  "response" : {
+	"status" : 404,
+	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
+	"headers" : {
+	  "Content-Type" : "application/json"
+	}
+  },
+  "priority" : 1
+}
+'''
+
+
+
+
+

8.5.4. Executing Custom Methods on the Server Side

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

+
+
+
+
+
+
+
+

The following code shows the base class portion of the test case:

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+ + + + + +
+ + +You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need. +
+
+
+

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

+
+
+
    +
  • +

    String: If you point to a String value in the JSON.

    +
  • +
  • +

    JSONArray: If you point to a List in the JSON.

    +
  • +
  • +

    Map: If you point to a Map in the JSON.

    +
  • +
  • +

    Number: If you point to Integer, Double etc. in the JSON.

    +
  • +
  • +

    Boolean: If you point to a Boolean in the JSON.

    +
  • +
+
+
+

In the request part of the contract, you can specify that the body should be taken from +a method.

+
+
+ + + + + +
+ + +You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it. +
+
+
+

The following example shows how to read an object from JSON:

+
+
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		url '/something'
+		body(
+				$(c('foo'), p(execute('hashCode()')))
+		)
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+
+

8.5.5. Referencing the Request from the Response

+
+

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

+
+
+

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

+
+
+
    +
  • +

    fromRequest().url(): Returns the request URL and query parameters.

    +
  • +
  • +

    fromRequest().query(String key): Returns the first query parameter with a given name.

    +
  • +
  • +

    fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.

    +
  • +
  • +

    fromRequest().path(): Returns the full path.

    +
  • +
  • +

    fromRequest().path(int index): Returns the nth path element.

    +
  • +
  • +

    fromRequest().header(String key): Returns the first header with a given name.

    +
  • +
  • +

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    +
  • +
  • +

    fromRequest().body(): Returns the full request body.

    +
  • +
  • +

    fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

    +
  • +
+
+
+

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

+
+
+
    +
  • +

    {{{ request.url }}}: Returns the request URL and query parameters.

    +
  • +
  • +

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    +
  • +
  • +

    {{{ request.path }}}: Returns the full path.

    +
  • +
  • +

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}

    +
  • +
  • +

    {{{ request.headers.key }}}: Returns the first header with a given name.

    +
  • +
  • +

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    +
  • +
  • +

    {{{ request.body }}}: Returns the full request body.

    +
  • +
  • +

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    +
  • +
+
+
+

Consider the following contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /api/v1/xxxx
+  queryParameters:
+    foo:
+      - bar
+      - bar2
+  headers:
+    Authorization:
+      - secret
+      - secret2
+  body:
+    foo: bar
+    baz: 5
+response:
+  status: 200
+  headers:
+    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
+  body:
+    url: "{{{ request.url }}}"
+    path: "{{{ request.path }}}"
+    pathIndex: "{{{ request.path.1 }}}"
+    param: "{{{ request.query.foo }}}"
+    paramIndex: "{{{ request.query.foo.1 }}}"
+    authorization: "{{{ request.headers.Authorization.0 }}}"
+    authorization2: "{{{ request.headers.Authorization.1 }}"
+    fullBody: "{{{ request.body }}}"
+    responseFoo: "{{{ jsonpath this '$.foo' }}}"
+    responseBaz: "{{{ jsonpath this '$.baz' }}}"
+    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"
+
+
+
+

Running a JUnit test generation leads to a test that resembles the following example:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
+
+
+
+

As you can see, elements from the request have been properly referenced in the response.

+
+
+

The generated WireMock stub should resemble the following example:

+
+
+
+
{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+
+
+
+

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

+
+
+
+
{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
+
+
+
+ + + + + +
+ + +This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions: +
+
+
+
    +
  • +

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    +
  • +
  • +

    jsonpath: For a given parameter, find an object in the request body.

    +
  • +
+
+
+
+

8.5.6. Registering Your Own WireMock Extension

+
+

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

+
+
+
+
org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
+org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
+org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter
+
+
+
+

The following is an example of a custom extension:

+
+
+
TestWireMockExtensions.groovy
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.contract.verifier.dsl.wiremock
+
+import com.github.tomakehurst.wiremock.extension.Extension
+
+/**
+ * Extension that registers the default transformer and the custom one
+ */
+class TestWireMockExtensions implements WireMockExtensions {
+	@Override
+	List<Extension> extensions() {
+		return [
+				new DefaultResponseTransformer(),
+				new CustomExtension()
+		]
+	}
+}
+
+class CustomExtension implements Extension {
+
+	@Override
+	String getName() {
+		return "foo-transformer"
+	}
+}
+
+
+
+ + + + + +
+ + +Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it. +
+
+
+
+

8.5.7. Dynamic Properties in the Matchers Sections

+
+

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

+
+
+

You can use the bodyMatchers section for two reasons:

+
+
+
    +
  • +

    Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.

    +
  • +
  • +

    Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

    +
  • +
+
+
+

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

+
+
+
Groovy DSL
+
    +
  • +

    For the stubs(in tests on the Consumer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      +
    • +
    • +

      byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.

      +
    • +
    +
    +
  • +
  • +

    For the verification(in generated tests on the Producer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.

      +
    • +
    • +

      byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.

      +
    • +
    • +

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      +
    • +
    • +

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      +
      +
        +
      • +

        String: If you point to a String value.

        +
      • +
      • +

        JSONArray: If you point to a List.

        +
      • +
      • +

        Map: If you point to a Map.

        +
      • +
      • +

        Number: If you point to Integer, Double, or other kind of number.

        +
      • +
      • +

        Boolean: If you point to a Boolean.

        +
      • +
      +
      +
    • +
    • +

      byNull(): The value taken from the response via the provided JSON Path must be null

      +
    • +
    +
    +
  • +
+
+
+
YAML
+

Please read the Groovy section for detailed explanation of +what the types mean

+
+
+

For YAML the structure of a matcher looks like this

+
+
+
+
- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string
+
+
+
+

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

+
+
+
+
- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode
+
+
+
+

Below you can find the allowed list of `type`s.

+
+
+
    +
  • +

    For stubMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    For testMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    • +

      by_command

      +
    • +
    • +

      by_null

      +
    • +
    +
    +
  • +
+
+
+

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

+
+
+
    +
  • +

    as_integer

    +
  • +
  • +

    as_double

    +
  • +
  • +

    as_float,

    +
  • +
  • +

    as_long

    +
  • +
  • +

    as_short

    +
  • +
  • +

    as_boolean

    +
  • +
  • +

    as_string

    +
  • +
+
+
+

Consider the following example:

+
+
+
Groovy DSL
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		urlPath '/get'
+		body([
+				duck                : 123,
+				alpha               : 'abc',
+				number              : 123,
+				aBoolean            : true,
+				date                : '2017-01-01',
+				dateTime            : '2017-01-01T01:23:45',
+				time                : '01:02:34',
+				valueWithoutAMatcher: 'foo',
+				valueWithTypeMatch  : 'string',
+				key                 : [
+						'complex.key': 'foo'
+				]
+		])
+		bodyMatchers {
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			jsonPath('$.duck', byEquality())
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+		}
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status OK()
+		body([
+				duck                 : 123,
+				alpha                : 'abc',
+				number               : 123,
+				positiveInteger      : 1234567890,
+				negativeInteger      : -1234567890,
+				positiveDecimalNumber: 123.4567890,
+				negativeDecimalNumber: -123.4567890,
+				aBoolean             : true,
+				date                 : '2017-01-01',
+				dateTime             : '2017-01-01T01:23:45',
+				time                 : "01:02:34",
+				valueWithoutAMatcher : 'foo',
+				valueWithTypeMatch   : 'string',
+				valueWithMin         : [
+						1, 2, 3
+				],
+				valueWithMax         : [
+						1, 2, 3
+				],
+				valueWithMinMax      : [
+						1, 2, 3
+				],
+				valueWithMinEmpty    : [],
+				valueWithMaxEmpty    : [],
+				key                  : [
+						'complex.key': 'foo'
+				],
+				nullValue            : null
+		])
+		bodyMatchers {
+			// asserts the jsonpath value against manual regex
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			// asserts the jsonpath value against the provided value
+			jsonPath('$.duck', byEquality())
+			// asserts the jsonpath value against some default regex
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			// asserts vs inbuilt time related regex
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			// asserts that the resulting type is the same as in response body
+			jsonPath('$.valueWithTypeMatch', byType())
+			jsonPath('$.valueWithMin', byType {
+				// results in verification of size of array (min 1)
+				minOccurrence(1)
+			})
+			jsonPath('$.valueWithMax', byType {
+				// results in verification of size of array (max 3)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinMax', byType {
+				// results in verification of size of array (min 1 & max 3)
+				minOccurrence(1)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinEmpty', byType {
+				// results in verification of size of array (min 0)
+				minOccurrence(0)
+			})
+			jsonPath('$.valueWithMaxEmpty', byType {
+				// results in verification of size of array (max 0)
+				maxOccurrence(0)
+			})
+			// will execute a method `assertThatValueIsANumber`
+			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+			jsonPath('$.nullValue', byNull())
+		}
+		headers {
+			contentType(applicationJson())
+			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  urlPath: /get/1
+  headers:
+    Content-Type: application/json
+  cookies:
+    foo: 2
+    bar: 3
+  queryParameters:
+    limit: 10
+    offset: 20
+    filter: 'email'
+    sort: name
+    search: 55
+    age: 99
+    name: John.Doe
+    email: 'bob@email.com'
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    key:
+      "complex.key": 'foo'
+    nullValue: null
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+  matchers:
+    url:
+      regex: /get/[0-9]
+      # predefined:
+      # execute a method
+      #command: 'equals($it)'
+    queryParameters:
+      - key: limit
+        type: equal_to
+        value: 20
+      - key: offset
+        type: containing
+        value: 20
+      - key: sort
+        type: equal_to
+        value: name
+      - key: search
+        type: not_matching
+        value: '^[0-9]{2}$'
+      - key: age
+        type: not_matching
+        value: '^\\w*$'
+      - key: name
+        type: matching
+        value: 'John.*'
+      - key: hello
+        type: absent
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: "$.['key'].['complex.key']"
+        type: by_equality
+      - path: $.nullvalue
+        type: by_null
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+response:
+  status: 200
+  cookies:
+    foo: 1
+    bar: 2
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+    key:
+      'complex.key': 'foo'
+    nulValue: null
+  matchers:
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: $.valueWithTypeMatch
+        type: by_type
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+      - path: $.valueWithMinEmpty
+        type: by_type
+        minOccurrence: 0
+      - path: $.valueWithMaxEmpty
+        type: by_type
+        maxOccurrence: 0
+      - path: $.duck
+        type: by_command
+        value: assertThatValueIsANumber($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+  headers:
+    Content-Type: application/json
+
+
+
+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

+
+
+

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

+
+
+
    +
  • +

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    +
  • +
  • +

    For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.

    +
  • +
  • +

    For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.

    +
  • +
  • +

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

    +
  • +
+
+
+

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
+
+
+
+ + + + + +
+ + +Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. +
+
+
+

The resulting WireMock stub is in the following example:

+
+
+
+
					'''
+{
+  "request" : {
+    "urlPath" : "/get",
+    "method" : "POST",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck == 123)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
+    "headers" : {
+      "Content-Type" : "application/json"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+'''
+
+
+
+ + + + + +
+ + +If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection. +
+
+
+

Consider the following example:

+
+
+
+
Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}
+
+
+
+

The preceding code leads to creating the following test (the code block shows only the assertion section):

+
+
+
+
and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
+
+
+
+

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

+
+
+
+
+

8.6. JAX-RS Support

+
+

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

+
+
+

In order to use JAX-RS mode, use the following settings:

+
+
+
+
testMode == 'JAXRSCLIENT'
+
+
+
+

The following example shows a generated test API:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Response;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static javax.ws.rs.client.Entity.*;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\tWebTarget webTarget;
+
+\t@Test
+\tpublic void validate_() throws Exception {
+
+\t\t// when:
+\t\t\tResponse response = webTarget
+\t\t\t\t\t\t\t.path("/users")
+\t\t\t\t\t\t\t.queryParam("limit", "10")
+\t\t\t\t\t\t\t.queryParam("offset", "20")
+\t\t\t\t\t\t\t.queryParam("filter", "email")
+\t\t\t\t\t\t\t.queryParam("sort", "name")
+\t\t\t\t\t\t\t.queryParam("search", "55")
+\t\t\t\t\t\t\t.queryParam("age", "99")
+\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
+\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
+\t\t\t\t\t\t\t.request()
+\t\t\t\t\t\t\t.build("GET")
+\t\t\t\t\t\t\t.invoke();
+\t\t\tString responseAsString = response.readEntity(String.class);
+
+\t\t// then:
+\t\t\tassertThat(response.getStatus()).isEqualTo(200);
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
+\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
+\t}
+
+}
+
+"""
+
+
+
+
+

8.7. Async Support

+
+

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}
+
+
+
+
YAML
+
+
response:
+    async: true
+
+
+
+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}
+
+
+
+
YAML
+
+
response:
+    fixedDelayMilliseconds: 1000
+
+
+
+
+

8.8. Working with Context Paths

+
+

Spring Cloud Contract supports context paths.

+
+
+ + + + + +
+ + +The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

+
+
+

Consider the following contract:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+		url '/my-context-path/url'
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured:

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ContextPathTestingBaseClass {
+
+	@LocalServerPort int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost";
+		RestAssured.port = this.port;
+	}
+}
+
+
+
+

If you do it this way:

+
+
+
    +
  • +

    All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).

    +
  • +
  • +

    Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

    +
  • +
+
+
+
+

8.9. Working with WebFlux

+
+

Spring Cloud Contract offers two ways of working with WebFlux.

+
+
+

8.9.1. WebFlux with WebTestClient

+
+

One of them is via the WebTestClient mode.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'WEBTESTCLIENT'
+}
+
+
+
+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

+
+
+
+
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}
+
+
+
+
+

8.9.2. WebFlux with Explicit mode

+
+

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured for Web Flux:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(classes = BeerRestBase.Config.class,
+		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+		properties = "server.port=0")
+public abstract class BeerRestBase {
+
+    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+@Configuration
+@EnableAutoConfiguration
+static class Config {
+
+	@Bean
+	PersonCheckingService personCheckingService()  {
+		return personToCheck -> personToCheck.age >= 20;
+	}
+
+	@Bean
+	ProducerController producerController() {
+		return new ProducerController(personCheckingService());
+	}
+}
+
+}
+
+
+
+
+
+

8.10. XML Support for REST

+
+

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

+
+
+

Here is an example of a Groovy DSL contract with XML response body:

+
+
+
+
					Contract.make {
+						request {
+							method GET()
+							urlPath '/get'
+							headers {
+								contentType(applicationXml())
+							}
+						}
+						response {
+							status(OK())
+							headers {
+								contentType(applicationXml())
+							}
+							body """
+<test>
+<duck type='xtype'>123</duck>
+<alpha>abc</alpha>
+<list>
+<elem>abc</elem>
+<elem>def</elem>
+<elem>ghi</elem>
+</list>
+<number>123</number>
+<aBoolean>true</aBoolean>
+<date>2017-01-01</date>
+<dateTime>2017-01-01T01:23:45</dateTime>
+<time>01:02:34</time>
+<valueWithoutAMatcher>foo</valueWithoutAMatcher>
+<key><complex>foo</complex></key>
+</test>"""
+							bodyMatchers {
+								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
+								xPath('/test/duck/text()', byCommand('equals($it)'))
+								xPath('/test/duck/xxx', byNull())
+								xPath('/test/duck/text()', byEquality())
+								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
+								xPath('/test/alpha/text()', byEquality())
+								xPath('/test/number/text()', byRegex(number()))
+								xPath('/test/date/text()', byDate())
+								xPath('/test/dateTime/text()', byTimestamp())
+								xPath('/test/time/text()', byTime())
+								xPath('/test/*/complex/text()', byEquality())
+								xPath('/test/duck/@type', byEquality())
+							}
+						}
+					}
+
+
+
+

And below is an example of a YAML contract with XML request and response bodies:

+
+
+
+
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
+
+
+
+

Here is an example of an automatically generated test for XML response body:

+
+
+
+
@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}
+
+
+
+
+

8.11. Messaging Top-Level Elements

+
+

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

+
+ +
+

8.11.1. Output Triggered by a Method

+
+

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	// Human readable description
+	description 'Some description'
+	// Label by means of which the output message can be triggered
+	label 'some_label'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('bookReturnedTriggered()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo('output')
+		// the body of the output message
+		body('''{ "bookName" : "foo" }''')
+		// the headers of the output message
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+input:
+  # the contract will be triggered by a method
+  triggeredBy: bookReturnedTriggered()
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

+
+
+
+

8.11.2. Output Triggered by a Message

+
+

The output message can be triggered by receiving a message, as shown in the following +example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	description 'Some Description'
+	label 'some_label'
+	// input is a message
+	input {
+		// the message was received from this destination
+		messageFrom('input')
+		// has the following body
+		messageBody([
+				bookName: 'foo'
+		])
+		// and the following headers
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+# input is a message
+input:
+  messageFrom: input
+  # has the following body
+  messageBody:
+    bookName: 'foo'
+  # and the following headers
+  messageHeaders:
+    sample: 'header'
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

+
+
+
+

8.11.3. Consumer/Producer

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. +
+
+
+

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

+
+
+
+
					Contract.make {
+				name "foo"
+						label 'some_label'
+						input {
+							messageFrom value(consumer('jms:output'), producer('jms:input'))
+							messageBody([
+									bookName: 'foo'
+							])
+							messageHeaders {
+								header('sample', 'header')
+							}
+						}
+						outputMessage {
+							sentTo $(consumer('jms:input'), producer('jms:output'))
+							body([
+									bookName: 'foo'
+							])
+						}
+					}
+
+
+
+
+

8.11.4. Common

+
+

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

+
+
+
+
+

8.12. Multiple Contracts in One File

+
+

You can define multiple contracts in one file. Such a contract might resemble the +following example:

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+[
+	Contract.make {
+		name("should post a user")
+		request {
+			method 'POST'
+			url('/users/1')
+		}
+		response {
+			status OK()
+		}
+	},
+	Contract.make {
+		request {
+			method 'POST'
+			url('/users/2')
+		}
+		response {
+			status OK()
+		}
+	}
+]
+
+
+
+
YAML
+
+
---
+name: should post a user
+request:
+  method: POST
+  url: /users/1
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/2
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/3
+response:
+  status: 200
+
+
+
+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

+
+
+
+
package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}
+
+
+
+

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

+
+
+

The generated stubs is shown in the following example:

+
+
+
+
should post a user.json
+1_WithList.json
+
+
+
+

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

+
+
+ + + + + +
+ + +As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful. +
+
+
+
+

8.13. Generating Spring REST Docs snippets from the contracts

+
+

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+<dependency>
+	<groupId>org.springframework.restdocs</groupId>
+	<artifactId>spring-restdocs-mockmvc</artifactId>
+	<optional>true</optional>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
+
+
+
+

Next you need to make some changes to your base class like the following example.

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public abstract class FraudBaseWithWebAppSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Autowired
+	private WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName()))
+				.build());
+	}
+
+	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+public abstract class FraudBaseWithStandaloneSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
+				.standaloneSetup(new FraudDetectionController())
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName())));
+	}
+
+}
+
+
+
+ + + + + +
+ + +You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. +
+
+
+
+
+
+

9. Customization

+
+
+ + + + + +
+ + +This section is valid only for Groovy DSL +
+
+
+

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

+
+
+

9.1. Extending the DSL

+
+

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

+
+
+
    +
  • +

    Creating a JAR with reusable classes.

    +
  • +
  • +

    Referencing of these classes in the DSLs.

    +
  • +
+
+
+

You can find the full example +here.

+
+
+

9.1.1. Common JAR

+
+

The following examples show three classes that can be reused in the DSLs.

+
+
+

PatternUtils contains functions used by both the consumer and the producer.

+
+
+
+
package com.example;
+
+import java.util.regex.Pattern;
+
+/**
+ * If you want to use {@link Pattern} directly in your tests
+ * then you can create a class resembling this one. It can
+ * contain all the {@link Pattern} you want to use in the DSL.
+ *
+ * <pre>
+ * {@code
+ * request {
+ *     body(
+ *         [ age: $(c(PatternUtils.oldEnough()))]
+ *     )
+ * }
+ * </pre>
+ *
+ * Notice that we're using both {@code $()} for dynamic values
+ * and {@code c()} for the consumer side.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class PatternUtils {
+
+	public static String tooYoung() {
+		//remove::start[]
+		return "[0-1][0-9]";
+		//remove::end[return]
+	}
+
+	public static Pattern oldEnough() {
+		//remove::start[]
+		return Pattern.compile("[2-9][0-9]");
+		//remove::end[return]
+	}
+
+	/**
+	 * Makes little sense but it's just an example ;)
+	 */
+	public static Pattern ok() {
+		//remove::start[]
+		return Pattern.compile("OK");
+		//remove::end[return]
+	}
+}
+//end::impl[]
+
+
+
+

ConsumerUtils contains functions used by the consumer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the consumer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you can have a regular expression.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you have to have a concrete value.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ConsumerUtils {
+	/**
+	 * Consumer side property. By using the {@link ClientDslProperty}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * request {
+	 *     body(
+	 *         [ age: $(ConsumerUtils.oldEnough())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 *
+	 * @author Marcin Grzejszczak
+	 */
+	public static ClientDslProperty oldEnough() {
+		//remove::start[]
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
+		//remove::end[return]
+	}
+
+}
+//end::impl[]
+
+
+
+

ProducerUtils contains functions used by the producer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the producer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you have to have a concrete value.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you can have a regular expression.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ProducerUtils {
+
+	/**
+	 * Producer side property. By using the {@link ProducerUtils}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * response {
+	 *     body(
+	 *         [ status: $(ProducerUtils.ok())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 */
+	public static ServerDslProperty ok() {
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ServerDslProperty( PatternUtils.ok(), "OK");
+	}
+}
+//end::impl[]
+
+
+
+
+

9.1.2. Adding the Dependency to the Project

+
+

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

+
+
+
+

9.1.3. Test the Dependency in the Project’s Dependencies

+
+

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

+
+
+
Maven
+
+
<dependency>
+	<groupId>com.example</groupId>
+	<artifactId>beer-common</artifactId>
+	<version>${project.version}</version>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")
+
+
+
+
+

9.1.4. Test a Dependency in the Plugin’s Dependencies

+
+

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example</packageWithBaseClasses>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
+				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>com.example</groupId>
+			<artifactId>beer-common</artifactId>
+			<version>${project.version}</version>
+			<scope>compile</scope>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"
+
+
+
+
+

9.1.5. Referencing classes in DSLs

+
+

You can now reference your classes in your DSL, as shown in the following example:

+
+
+
+
package contracts.beer.rest
+
+import com.example.ConsumerUtils
+import com.example.ProducerUtils
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	description("""
+Represents a successful scenario of getting a beer
+
+```
+given:
+	client is old enough
+when:
+	he applies for a beer
+then:
+	we'll grant him the beer
+```
+
+""")
+	request {
+		method 'POST'
+		url '/check'
+		body(
+				age: $(ConsumerUtils.oldEnough())
+		)
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status 200
+		body("""
+			{
+				"status": "${value(ProducerUtils.ok())}"
+			}
+			""")
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+ + + + + +
+ + +You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. +
+
+
+
+
+
+
+

10. Using the Pluggable Architecture

+
+
+

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

+
+
+

10.1. Custom Contract Converter

+
+

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

+
+
+
+
package org.springframework.cloud.contract.spec;
+
+import java.io.File;
+import java.util.Collection;
+
+/**
+ * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
+ * {@link Contract} to {@code T}.
+ *
+ * @param <T> - type to which we want to convert the contract
+ * @author Marcin Grzejszczak
+ * @since 1.1.0
+ */
+public interface ContractConverter<T> extends ContractStorer<T> {
+
+	/**
+	 * Should this file be accepted by the converter. Can use the file extension to check
+	 * if the conversion is possible.
+	 * @param file - file to be considered for conversion
+	 * @return - {@code true} if the given implementation can convert the file
+	 */
+	boolean isAccepted(File file);
+
+	/**
+	 * Converts the given {@link File} to its {@link Contract} representation.
+	 * @param file - file to convert
+	 * @return - {@link Contract} representation of the file
+	 */
+	Collection<Contract> convertFrom(File file);
+
+	/**
+	 * Converts the given {@link Contract} to a {@link T} representation.
+	 * @param contract - the parsed contract
+	 * @return - {@link T} the type to which we do the conversion
+	 */
+	T convertTo(Collection<Contract> contract);
+
+}
+
+
+
+

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

+
+
+ + + + + +
+ + +Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation. +
+
+
+

The following example shows a typical spring.factories file:

+
+
+
+
org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter
+
+
+
+

10.1.1. Pact Converter

+
+

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

+
+
+

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

+
+
+
    +
  • +

    to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    +
  • +
+
+
+
+

10.1.2. Pact Contract

+
+

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

+
+
+
+
{
+  "provider": {
+    "name": "Provider"
+  },
+  "consumer": {
+    "name": "Consumer"
+  },
+  "interactions": [
+    {
+      "description": "",
+      "request": {
+        "method": "PUT",
+        "path": "/fraudcheck",
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "clientId": "1234567890",
+          "loanAmount": 99999
+        },
+        "generators": {
+          "body": {
+            "$.clientId": {
+              "type": "Regex",
+              "regex": "[0-9]{10}"
+            }
+          }
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.clientId": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "[0-9]{10}"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      },
+      "response": {
+        "status": 200,
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "fraudCheckStatus": "FRAUD",
+          "rejectionReason": "Amount too high"
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.fraudCheckStatus": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "FRAUD"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "metadata": {
+    "pact-specification": {
+      "version": "3.0.0"
+    },
+    "pact-jvm": {
+      "version": "3.5.13"
+    }
+  }
+}
+
+
+
+

The remainder of this section about using Pact refers to the preceding file.

+
+
+
+

10.1.3. Pact for Producers

+
+

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-contract-pact</artifactId>
+			<version>${spring-cloud-contract.version}</version>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"
+
+
+
+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}
+
+
+
+

The corresponding generated stub might be as follows:

+
+
+
+
{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}
+
+
+
+
+

10.1.4. Pact for Consumers

+
+

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-pact</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-contract-pact"
+
+
+
+
+
+

10.2. Using the Custom Test Generator

+
+

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

+
+
+

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.builder;
+
+import java.nio.file.Path;
+import java.util.Collection;
+
+import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
+import org.springframework.cloud.contract.verifier.file.ContractMetadata;
+
+/**
+ * Builds a single test.
+ *
+ * @since 1.1.0
+ */
+public interface SingleTestGenerator {
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param className - the name of the generated test class
+	 * @param classPackage - the name of the package in which the test class should be
+	 * stored
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
+	 */
+	@Deprecated
+	String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String className,
+			String classPackage, String includedDirectoryRelativePath);
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param generatedClassData - information about the generated class
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 */
+	default String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles,
+			String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
+		String className = generatedClassData.className;
+		String classPackage = generatedClassData.classPackage;
+		String path = includedDirectoryRelativePath;
+		return buildClass(properties, listOfFiles, className, classPackage, path);
+	}
+
+	/**
+	 * Extension that should be appended to the generated test class. E.g. {@code .java}
+	 * or {@code .php}
+	 * @param properties - properties passed to the plugin
+	 */
+	String fileExtension(ContractVerifierConfigProperties properties);
+
+	class GeneratedClassData {
+
+		public final String className;
+
+		public final String classPackage;
+
+		public final Path testClassPath;
+
+		public GeneratedClassData(String className, String classPackage,
+				Path testClassPath) {
+			this.className = className;
+			this.classPackage = classPackage;
+			this.testClassPath = testClassPath;
+		}
+
+	}
+
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator
+
+
+
+
+

10.3. Using the Custom Stub Generator

+
+

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.converter
+
+import groovy.transform.CompileStatic
+
+import org.springframework.cloud.contract.spec.Contract
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Converts contracts into their stub representation.
+ *
+ * @since 1.1.0
+ */
+@CompileStatic
+interface StubGenerator {
+
+	/**
+	 * @return {@code true} if the converter can handle the file to convert it into a stub.
+	 */
+	boolean canHandleFileName(String fileName)
+
+	/**
+	 * @return the collection of converted contracts into stubs. One contract can
+	 * result in multiple stubs.
+	 */
+	Map<Contract, String> convertContents(String rootName, ContractMetadata content)
+
+	/**
+	 * @return the name of the converted stub file. If you have multiple contracts
+	 * in a single file then a prefix will be added to the generated file. If you
+	 * provide the {@link Contract#name} field then that field will override the
+	 * generated file name.
+	 *
+	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be
+	 * converted by the implementation to {@code foo.json}. The recursive file
+	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
+	 */
+	String generateOutputFileNameForInput(String inputFileName)
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
# Stub converters
+org.springframework.cloud.contract.verifier.converter.StubGenerator=\
+org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
+
+
+
+

The default implementation is the WireMock stub generation.

+
+
+ + + + + +
+ + +You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. +
+
+
+
+

10.4. Using the Custom Stub Runner

+
+

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

+
+
+

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

+
+
+

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

+
+
+
+
package org.springframework.cloud.contract.stubrunner.provider.moco
+
+import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
+import com.github.dreamhead.moco.runner.JsonRunner
+import com.github.dreamhead.moco.runner.RunnerSetting
+import groovy.util.logging.Commons
+
+import org.springframework.cloud.contract.stubrunner.HttpServerStub
+import org.springframework.util.SocketUtils
+
+@Commons
+class MocoHttpServerStub implements HttpServerStub {
+
+	private boolean started
+	private JsonRunner runner
+	private int port
+
+	@Override
+	int port() {
+		if (!isRunning()) {
+			return -1
+		}
+		return port
+	}
+
+	@Override
+	boolean isRunning() {
+		return started
+	}
+
+	@Override
+	HttpServerStub start() {
+		return start(SocketUtils.findAvailableTcpPort())
+	}
+
+	@Override
+	HttpServerStub start(int port) {
+		this.port = port
+		return this
+	}
+
+	@Override
+	HttpServerStub stop() {
+		if (!isRunning()) {
+			return this
+		}
+		this.runner.stop()
+		return this
+	}
+
+	@Override
+	HttpServerStub registerMappings(Collection<File> stubFiles) {
+		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
+			.collect {
+			log.info("Trying to parse [${it.name}]")
+			try {
+				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
+					build()
+			}
+			catch (Exception e) {
+				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
+				return null
+			}
+		}.findAll { it }
+		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
+			HttpArgs.httpArgs().withPort(this.port).build())
+		this.runner.run()
+		this.started = true
+		return this
+	}
+
+	@Override
+	String registeredMappings() {
+		return ""
+	}
+
+	@Override
+	boolean isAccepted(File file) {
+		return file.name.endsWith(".json")
+	}
+}
+
+
+
+

Then, you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
+
+
+
+

Now you can run stubs with Moco.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. +
+
+
+
+

10.5. Using the Custom Stub Downloader

+
+

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

+
+
+
+
package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}
+
+
+
+

Then you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder
+
+
+
+

Now you can pick a folder with the source of your stubs.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. +
+
+
+
+

10.6. Using the SCM Stub Downloader

+
+

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

+

* stubrunner.properties.git.branch (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

+

* stubrunner.properties.git.username (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

+

* stubrunner.properties.git.password (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

+

* stubrunner.properties.git.no-of-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

+

* stubrunner.properties.git.wait-between-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

+
+
+

10.7. Using the Pact Stub Downloader

+
+

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

+

* stubrunner.properties.pactbroker.host (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

+

* stubrunner.properties.pactbroker.port (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

+

* stubrunner.properties.pactbroker.protocol (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

+

* stubrunner.properties.pactbroker.tags (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

+

* stubrunner.properties.pactbroker.auth.scheme (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

+

* stubrunner.properties.pactbroker.auth.username (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

+

* stubrunner.properties.pactbroker.auth.password (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

+

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

+
+
+
+
+

11. Spring Cloud Contract WireMock

+
+
+

The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details.

+
+
+

If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+	// A service that calls out over HTTP
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:"
+				+ this.environment.getProperty("wiremock.server.port"));
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

+
+
+

11.1. Registering Stubs Automatically

+
+

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureWireMock(stubs="classpath:/stubs")
+public class WiremockImportApplicationTests {
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+ + + + + +
+ + +Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. +
+
+
+

If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

+
+
+
+
@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")
+
+
+
+
+

11.2. Using Files to Specify the Stub Bodies

+
+

WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body.

+
+
+ + + + + +
+ + +When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute. +
+
+
+
+

11.3. Alternative: Using JUnit Rules

+
+

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class WiremockForDocsClassRuleTests {
+
+	// Start WireMock on some dynamic port
+	// for some reason `dynamicPort()` is not working properly
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().dynamicPort());
+
+	// A service that calls out over HTTP to wiremock's port
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:" + wiremock.port());
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

The @ClassRule means that the server shuts down after all the methods in this class +have been run.

+
+
+
+

11.4. Relaxed SSL Validation for Rest Template

+
+

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course).

+
+
+

To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example:

+
+
+
+
@Bean
+public RestTemplate restTemplate(RestTemplateBuilder builder) {
+	return builder.build();
+}
+
+
+
+

You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest("app.baseUrl=https://localhost:6443")
+@AutoConfigureHttpClient
+public class WiremockHttpsServerApplicationTests {
+
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().httpsPort(6443));
+...
+}
+
+
+
+

If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases.

+
+
+

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false.

+
+
+
+

11.5. WireMock and Spring MVC Mocks

+
+

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+public class WiremockForDocsMockServerApplicationTests {
+
+	@Autowired
+	private RestTemplate restTemplate;
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		// will read stubs classpath
+		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
+				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
+				.build();
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World");
+		server.verify();
+	}
+
+}
+
+
+
+

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website.

+
+
+

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one).

+
+
+
+

11.6. Customization of WireMock configuration

+
+

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example:

+
+
+
+
		@Bean
+		WireMockConfigurationCustomizer optionsCustomizer() {
+			return new WireMockConfigurationCustomizer() {
+				@Override
+				public void customize(WireMockConfiguration options) {
+// perform your customization here
+				}
+			};
+		}
+
+
+
+
+

11.7. Generating Stubs using REST Docs

+
+

Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(get("/resource"))
+				.andExpect(content().string("Hello World"))
+				.andDo(document("resource"));
+	}
+}
+
+
+
+

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureWebTestClient
+public class ApplicationTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void contextLoads() throws Exception {
+		client.get().uri("/resource").exchange()
+				.expectBody(String.class).isEqualTo("Hello World")
+ 				.consumeWith(document("resource"));
+	}
+}
+
+
+
+

Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects:

+
+
+
    +
  • +

    Creating a stub that matches only in the way you specify.

    +
  • +
  • +

    Asserting that the request in the test case also matches the same conditions.

    +
  • +
+
+
+

The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example:

+
+
+
+
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
+
+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(post("/resource")
+                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+				.andExpect(status().isOk())
+				.andDo(verify().jsonPath("$.id")
+                        .stub("resource"));
+	}
+}
+
+
+
+

This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place.

+
+
+

Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example:

+
+
+
+
@Test
+public void contextLoads() throws Exception {
+	mockMvc.perform(post("/resource")
+               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+			.andExpect(status().isOk())
+			.andDo(verify()
+					.wiremock(WireMock.post(
+						urlPathEquals("/resource"))
+						.withRequestBody(matchingJsonPath("$.id"))
+                       .stub("post-resource"));
+}
+
+
+
+

The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example:

+
+
+
post-resource.json
+
+
{
+  "request" : {
+    "url" : "/resource",
+    "method" : "POST",
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.id"
+    }]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "Hello World",
+    "headers" : {
+      "X-Application-Context" : "application:-1",
+      "Content-Type" : "text/plain"
+    }
+  }
+}
+
+
+
+ + + + + +
+ + +You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches. +
+
+
+

On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document.

+
+
+
+

11.8. Generating Contracts by Using REST Docs

+
+

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs.

+
+
+

Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them.

+
+
+ + + + + +
+ + +You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. +
+
+
+

Consider the following test:

+
+
+
+
		this.mockMvc
+				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
+						.accept(MediaType.APPLICATION_JSON)
+						.contentType(MediaType.APPLICATION_JSON)
+						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
+				.andExpect(status().isOk()).andExpect(content().string("bar"))
+				// first WireMock
+				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
+						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
+						.contentType(MediaType.valueOf("application/json"))
+						.stub("shouldGrantABeerIfOldEnough"))
+				// then Contract DSL documentation
+				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));
+
+
+
+

The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file.

+
+
+

The contract is called index.groovy and might look like the following example:

+
+
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+    request {
+        method 'POST'
+        url '/foo'
+        body('''
+            {"foo": 23 }
+        ''')
+        headers {
+            header('''Accept''', '''application/json''')
+            header('''Content-Type''', '''application/json''')
+        }
+    }
+    response {
+        status OK()
+        body('''
+        bar
+        ''')
+        headers {
+            header('''Content-Type''', '''application/json;charset=UTF-8''')
+            header('''Content-Length''', '''3''')
+        }
+        testMatchers {
+            jsonPath('$[?(@.foo >= 20)]', byType())
+        }
+    }
+}
+
+
+
+

The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc.

+
+
+
+
+
+

12. Migrations

+
+
+ + + + + +
+ + +For up to date migration guides please visit +the project’s wiki page. +
+
+
+

This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths:

+
+
+

12.1. 1.0.x → 1.1.x

+
+

This section covers upgrading from version 1.0 to version 1.1.

+
+
+

12.1.1. New structure of generated stubs

+
+

In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
+
+
+
+

You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
+
+
+
+

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet.

+
+
+
Maven
+
+
<!-- start of pom.xml -->
+
+<properties>
+    <!-- we don't want the verifier to do a jar for us -->
+    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+</properties>
+
+<!-- ... -->
+
+<!-- You need to set up the assembly plugin -->
+<build>
+    <plugins>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-assembly-plugin</artifactId>
+            <executions>
+                <execution>
+                    <id>stub</id>
+                    <phase>prepare-package</phase>
+                    <goals>
+                        <goal>single</goal>
+                    </goals>
+                    <inherited>false</inherited>
+                    <configuration>
+                        <attach>true</attach>
+                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
+                    </configuration>
+                </execution>
+            </executions>
+        </plugin>
+    </plugins>
+</build>
+<!-- end of pom.xml -->
+
+<!-- start of stub.xml-->
+
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>customer-stubs/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>customer-stubs/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+<!-- end of stub.xml-->
+
+
+
+
Gradle
+
+
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
+//    Preserve directory structure from 1.0.X of spring-cloud-contract
+    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
+    into "${project.buildDir}/resources/main/customer-stubs"
+}
+
+
+
+
+
+

12.2. 1.1.x → 1.2.x

+
+

This section covers upgrading from version 1.1 to version 1.2.

+
+
+

12.2.1. Custom HttpServerStub

+
+

HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub.

+
+
+

See issue 355 for more +detail.

+
+
+
+

12.2.2. New packages for generated tests

+
+

The flow for setting the generated tests package name will look like this:

+
+
+
    +
  • +

    Set basePackageForTests

    +
  • +
  • +

    If basePackageForTests was not set, pick the package from baseClassForTests

    +
  • +
  • +

    If baseClassForTests was not set, pick packageWithBaseClasses

    +
  • +
  • +

    If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests

    +
  • +
+
+
+

See issue 260 for more +detail.

+
+
+
+

12.2.3. New Methods in TemplateProcessor

+
+

In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface:

+
+
+
    +
  • +

    path()

    +
  • +
  • +

    path(int index)

    +
  • +
+
+
+

See issue 388 for more +detail.

+
+
+
+

12.2.4. RestAssured 3.0

+
+

Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception:

+
+
+
+
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
+[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist
+
+
+
+

This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa).

+
+
+

Done via issue 267

+
+
+
+ +
+
+
+ +
+
+

The following links may be helpful when working with Spring Cloud Contract:

+
+ +
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/js/highlight/highlight.min.js b/reference/html/js/highlight/highlight.min.js new file mode 100644 index 0000000000..dcbbb4c7fc --- /dev/null +++ b/reference/html/js/highlight/highlight.min.js @@ -0,0 +1,2 @@ +/*! highlight.js v9.13.1 | BSD3 License | git.io/hljslicense */ +!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&").replace(//g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=M.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function c(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function u(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function c(e){l+=""}function u(e){("start"===e.event?o:c)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substring(s,g[0].offset)),s=g[0].offset,g===e){f.reverse().forEach(c);do u(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===s);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),u(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function l(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):B(a.k).forEach(function(e){c(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.endSameAsBegin&&(a.e=a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return s("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var u=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=u.length?t(u.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e){return new RegExp(e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}function c(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t].endSameAsBegin&&(n.c[t].eR=o(n.c[t].bR.exec(e)[0])),n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function s(e,n){return!a&&r(n.iR,e)}function p(e,n){var t=R.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function d(e,n,t,r){var a=r?"":j.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=p(E,r),e?(M+=e[1],a+=d(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function b(){var e="string"==typeof E.sL;if(e&&!L[E.sL])return n(k);var t=e?f(E.sL,k,!0,B[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(M+=t.r),e&&(B[E.sL]=t.top),d(t.language,t.value,!1,!0)}function v(){y+=null!=E.sL?b():h(),k=""}function m(e){y+=e.cN?d(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function N(e,n){if(k+=e,null==n)return v(),0;var t=c(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),v(),t.rB||t.eB||(k=n)),m(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),v(),a.eE&&(k=n));do E.cN&&(y+=I),E.skip||E.sL||(M+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&(r.endSameAsBegin&&(r.starts.eR=r.eR),m(r.starts,"")),a.rE?0:n.length}if(s(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var R=w(e);if(!R)throw new Error('Unknown language: "'+e+'"');l(R);var x,E=i||R,B={},y="";for(x=E;x!==R;x=x.parent)x.cN&&(y=d(x.cN,"",!0)+y);var k="",M=0;try{for(var C,A,S=0;;){if(E.t.lastIndex=S,C=E.t.exec(t),!C)break;A=N(t.substring(S,C.index),C[0]),S=C.index+A}for(N(t.substr(S)),x=E;x.parent;x=x.parent)x.cN&&(y+=I);return{r:M,value:y,language:e,top:E}}catch(O){if(O.message&&-1!==O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function g(e,t){t=t||j.languages||B(L);var r={r:0,value:n(e)},a=r;return t.filter(w).filter(x).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return j.tabReplace||j.useBR?e.replace(C,function(e,n){return j.useBR&&"\n"===e?"
":j.tabReplace?n.replace(/\t/g,j.tabReplace):""}):e}function d(e,n,t){var r=n?y[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function h(e){var n,t,r,o,s,l=i(e);a(l)||(j.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,s=n.textContent,r=l?f(l,s,!0):g(s),t=c(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=u(t,c(o),s)),r.value=p(r.value),e.innerHTML=r.value,e.className=d(e.className,l,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){j=o(j,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,h)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=L[n]=t(e);r.aliases&&r.aliases.forEach(function(e){y[e]=n})}function R(){return B(L)}function w(e){return e=(e||"").toLowerCase(),L[e]||L[y[e]]}function x(e){var n=w(e);return n&&!n.disableAutodetect}var E=[],B=Object.keys,L={},y={},k=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,C=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,I="
",j={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=h,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.autoDetection=x,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env arg user onbuild stopsignal",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{e:/[^\\]\n/,sL:"bash"}}],i:")?[^\s\(]+(\s+[^\s\(]+)\s*=/,r:5,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"type",b://,k:"reified",r:0},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:t,r:0,c:[{b:/:/,e:/[=,\/]/,eW:!0,c:[{cN:"type",b:e.UIR},e.CLCM,e.CBCM],r:0},e.CLCM,e.CBCM,s,l,c,e.CNM]},e.CBCM]},{cN:"class",bK:"class interface trait",e:/[:\{(]|$/,eE:!0,i:"extends implements",c:[{bK:"public protected internal private constructor"},e.UTM,{cN:"type",b://,eB:!0,eE:!0,r:0},{cN:"type",b:/[,:]\s*/,e:/[<\(,]|$/,eB:!0,rE:!0},s,l]},c,{cN:"meta",b:"^#!/usr/bin/env",e:"$",i:"\n"},o]}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"meta",b:/<\?xml/,e:/\?>/,r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0},{b:'b"',e:'"',skip:!0},{b:"b'",e:"'",skip:!0},s.inherit(s.ASM,{i:null,cN:null,c:null,skip:!0}),s.inherit(s.QSM,{i:null,cN:null,c:null,skip:!0})]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[t],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[t],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("properties",function(r){var t="[ \\t\\f]*",e="[ \\t\\f]+",s="("+t+"[:=]"+t+"|"+e+")",n="([^\\\\\\W:= \\t\\f\\n]|\\\\.)+",a="([^\\\\:= \\t\\f\\n]|\\\\.)+",c={e:s,r:0,starts:{cN:"string",e:/$/,r:0,c:[{b:"\\\\\\n"}]}};return{cI:!0,i:/\S/,c:[r.C("^\\s*[!#]","$"),{b:n+s,rB:!0,c:[{cN:"attr",b:n,endsParent:!0,r:0}],starts:c},{b:a+s,rB:!0,r:0,c:[{cN:"meta",b:a,endsParent:!0,r:0}],starts:c},{cN:"attr",r:0,b:a+t+"$"}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("asciidoc",function(e){return{aliases:["adoc"],c:[e.C("^/{4,}\\n","\\n/{4,}$",{r:10}),e.C("^//","$",{r:0}),{cN:"title",b:"^\\.\\w.*$"},{b:"^[=\\*]{4,}\\n",e:"\\n^[=\\*]{4,}$",r:10},{cN:"section",r:10,v:[{b:"^(={1,5}) .+?( \\1)?$"},{b:"^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$"}]},{cN:"meta",b:"^:.+?:",e:"\\s",eE:!0,r:10},{cN:"meta",b:"^\\[.+?\\]$",r:0},{cN:"quote",b:"^_{4,}\\n",e:"\\n_{4,}$",r:10},{cN:"code",b:"^[\\-\\.]{4,}\\n",e:"\\n[\\-\\.]{4,}$",r:10},{b:"^\\+{4,}\\n",e:"\\n\\+{4,}$",c:[{b:"<",e:">",sL:"xml",r:0}],r:10},{cN:"bullet",b:"^(\\*+|\\-+|\\.+|[^\\n]+?::)\\s+"},{cN:"symbol",b:"^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+",r:10},{cN:"strong",b:"\\B\\*(?![\\*\\s])",e:"(\\n{2}|\\*)",c:[{b:"\\\\*\\w",r:0}]},{cN:"emphasis",b:"\\B'(?!['\\s])",e:"(\\n{2}|')",c:[{b:"\\\\'\\w",r:0}],r:0},{cN:"emphasis",b:"_(?![_\\s])",e:"(\\n{2}|_)",r:0},{cN:"string",v:[{b:"``.+?''"},{b:"`.+?'"}]},{cN:"code",b:"(`.+?`|\\+.+?\\+)",r:0},{cN:"code",b:"^[ \\t]",e:"$",r:0},{b:"^'{3,}[ \\t]*$",r:10},{b:"(link:)?(http|https|ftp|file|irc|image:?):\\S+\\[.*?\\]",rB:!0,c:[{b:"(link|image:?):",r:0},{cN:"link",b:"\\w",e:"[^\\[]+",r:0},{cN:"string",b:"\\[",e:"\\]",eB:!0,eE:!0,r:0}],r:10}]}});hljs.registerLanguage("aspectj",function(e){var t="false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else extends implements break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws privileged aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization staticinitialization withincode target within execution getWithinTypeName handler thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents warning error soft precedence thisAspectInstance",i="get set args call";return{k:t,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"aspect",e:/[{;=]/,eE:!0,i:/[:;"\[\]]/,c:[{bK:"extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton"},e.UTM,{b:/\([^\)]*/,e:/[)]+/,k:t+" "+i,eE:!1}]},{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,r:0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"pointcut after before around throwing returning",e:/[)]/,eE:!1,i:/["\[\]]/,c:[{b:e.UIR+"\\s*\\(",rB:!0,c:[e.UTM]}]},{b:/[:]/,rB:!0,e:/[{;]/,r:0,eE:!1,k:t,i:/["\[\]]/,c:[{b:e.UIR+"\\s*\\(",k:t+" "+i,r:0},e.QSM]},{bK:"new throw",r:0},{cN:"function",b:/\w+ +\w+(\.)?\w+\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,rB:!0,e:/[{;=]/,k:t,eE:!0,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,r:0,k:t,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},e.CNM,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("gradle",function(e){return{cI:!0,k:{keyword:"task project allprojects subprojects artifacts buildscript configurations dependencies repositories sourceSets description delete from into include exclude source classpath destinationDir includes options sourceCompatibility targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant def abstract break case catch continue default do else extends final finally for if implements instanceof native new private protected public return static switch synchronized throw throws transient try volatile while strictfp package import false null super this true antlrtask checkstyle codenarc copy boolean byte char class double float int interface long short void compile runTime file fileTree abs any append asList asWritable call collect compareTo count div dump each eachByte eachFile eachLine every find findAll flatten getAt getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter newReader newWriter next plus pop power previous print println push putAt read readBytes readLines reverse reverseEach round size sort splitEachLine step subMap times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader withStream withWriter withWriterAppend write writeLine"},c:[e.CLCM,e.CBCM,e.ASM,e.QSM,e.NM,e.RM]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment with",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null unknown",built_in:"array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t,e.HCM]},e.CBCM,t,e.HCM]}});hljs.registerLanguage("go",function(e){var t={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:t,i:"",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}}); \ No newline at end of file diff --git a/reference/html/js/highlight/styles/a11y-dark.min.css b/reference/html/js/highlight/styles/a11y-dark.min.css new file mode 100644 index 0000000000..b93b742a45 --- /dev/null +++ b/reference/html/js/highlight/styles/a11y-dark.min.css @@ -0,0 +1,99 @@ +/* a11y-dark theme */ +/* Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css */ +/* @author: ericwbailey */ + +/* Comment */ +.hljs-comment, +.hljs-quote { + color: #d4d0ab; +} + +/* Red */ +.hljs-variable, +.hljs-template-variable, +.hljs-tag, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-regexp, +.hljs-deletion { + color: #ffa07a; +} + +/* Orange */ +.hljs-number, +.hljs-built_in, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params, +.hljs-meta, +.hljs-link { + color: #f5ab35; +} + +/* Yellow */ +.hljs-attribute { + color: #ffd700; +} + +/* Green */ +.hljs-string, +.hljs-symbol, +.hljs-bullet, +.hljs-addition { + color: #abe338; +} + +/* Blue */ +.hljs-title, +.hljs-section { + color: #00e0e0; +} + +/* Purple */ +.hljs-keyword, +.hljs-selector-tag { + color: #dcc6e0; +} + +.hljs { + display: block; + overflow-x: auto; + background: #2b2b2b; + color: #f8f8f2; + padding: 0.5em; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +@media screen and (-ms-high-contrast: active) { + .hljs-addition, + .hljs-attribute, + .hljs-built_in, + .hljs-builtin-name, + .hljs-bullet, + .hljs-comment, + .hljs-link, + .hljs-literal, + .hljs-meta, + .hljs-number, + .hljs-params, + .hljs-string, + .hljs-symbol, + .hljs-type, + .hljs-quote { + color: highlight; + } + + .hljs-keyword, + .hljs-selector-tag { + font-weight: bold; + } +} diff --git a/reference/html/js/highlight/styles/an-old-hope.min.css b/reference/html/js/highlight/styles/an-old-hope.min.css new file mode 100644 index 0000000000..a6d56f4b40 --- /dev/null +++ b/reference/html/js/highlight/styles/an-old-hope.min.css @@ -0,0 +1,89 @@ +/* + +An Old Hope – Star Wars Syntax (c) Gustavo Costa +Original theme - Ocean Dark Theme – by https://github.com/gavsiu +Based on Jesse Leite's Atom syntax theme 'An Old Hope' – https://github.com/JesseLeite/an-old-hope-syntax-atom + +*/ + +/* Death Star Comment */ +.hljs-comment, +.hljs-quote +{ + color: #B6B18B; +} + +/* Darth Vader */ +.hljs-variable, +.hljs-template-variable, +.hljs-tag, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-regexp, +.hljs-deletion +{ + color: #EB3C54; +} + +/* Threepio */ +.hljs-number, +.hljs-built_in, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params, +.hljs-meta, +.hljs-link +{ + color: #E7CE56; +} + +/* Luke Skywalker */ +.hljs-attribute +{ + color: #EE7C2B; +} + +/* Obi Wan Kenobi */ +.hljs-string, +.hljs-symbol, +.hljs-bullet, +.hljs-addition +{ + color: #4FB4D7; +} + +/* Yoda */ +.hljs-title, +.hljs-section +{ + color: #78BB65; +} + +/* Mace Windu */ +.hljs-keyword, +.hljs-selector-tag +{ + color: #B45EA4; +} + +/* Millenium Falcon */ +.hljs +{ + display: block; + overflow-x: auto; + background: #1C1D21; + color: #c0c5ce; + padding: 0.5em; +} + +.hljs-emphasis +{ + font-style: italic; +} + +.hljs-strong +{ + font-weight: bold; +} diff --git a/reference/html/js/highlight/styles/atom-one-dark-reasonable.min.css b/reference/html/js/highlight/styles/atom-one-dark-reasonable.min.css new file mode 100644 index 0000000000..fd41c996a3 --- /dev/null +++ b/reference/html/js/highlight/styles/atom-one-dark-reasonable.min.css @@ -0,0 +1,77 @@ +/* + +Atom One Dark With support for ReasonML by Gidi Morris, based off work by Daniel Gamage + +Original One Dark Syntax theme from https://github.com/atom/one-dark-syntax + +*/ +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + line-height: 1.3em; + color: #abb2bf; + background: #282c34; + border-radius: 5px; +} +.hljs-keyword, .hljs-operator { + color: #F92672; +} +.hljs-pattern-match { + color: #F92672; +} +.hljs-pattern-match .hljs-constructor { + color: #61aeee; +} +.hljs-function { + color: #61aeee; +} +.hljs-function .hljs-params { + color: #A6E22E; +} +.hljs-function .hljs-params .hljs-typing { + color: #FD971F; +} +.hljs-module-access .hljs-module { + color: #7e57c2; +} +.hljs-constructor { + color: #e2b93d; +} +.hljs-constructor .hljs-string { + color: #9CCC65; +} +.hljs-comment, .hljs-quote { + color: #b18eb1; + font-style: italic; +} +.hljs-doctag, .hljs-formula { + color: #c678dd; +} +.hljs-section, .hljs-name, .hljs-selector-tag, .hljs-deletion, .hljs-subst { + color: #e06c75; +} +.hljs-literal { + color: #56b6c2; +} +.hljs-string, .hljs-regexp, .hljs-addition, .hljs-attribute, .hljs-meta-string { + color: #98c379; +} +.hljs-built_in, .hljs-class .hljs-title { + color: #e6c07b; +} +.hljs-attr, .hljs-variable, .hljs-template-variable, .hljs-type, .hljs-selector-class, .hljs-selector-attr, .hljs-selector-pseudo, .hljs-number { + color: #d19a66; +} +.hljs-symbol, .hljs-bullet, .hljs-link, .hljs-meta, .hljs-selector-id, .hljs-title { + color: #61aeee; +} +.hljs-emphasis { + font-style: italic; +} +.hljs-strong { + font-weight: bold; +} +.hljs-link { + text-decoration: underline; +} diff --git a/reference/html/js/highlight/styles/atom-one-dark.min.css b/reference/html/js/highlight/styles/atom-one-dark.min.css new file mode 100644 index 0000000000..1616aafe31 --- /dev/null +++ b/reference/html/js/highlight/styles/atom-one-dark.min.css @@ -0,0 +1,96 @@ +/* + +Atom One Dark by Daniel Gamage +Original One Dark Syntax theme from https://github.com/atom/one-dark-syntax + +base: #282c34 +mono-1: #abb2bf +mono-2: #818896 +mono-3: #5c6370 +hue-1: #56b6c2 +hue-2: #61aeee +hue-3: #c678dd +hue-4: #98c379 +hue-5: #e06c75 +hue-5-2: #be5046 +hue-6: #d19a66 +hue-6-2: #e6c07b + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #abb2bf; + background: #282c34; +} + +.hljs-comment, +.hljs-quote { + color: #5c6370; + font-style: italic; +} + +.hljs-doctag, +.hljs-keyword, +.hljs-formula { + color: #c678dd; +} + +.hljs-section, +.hljs-name, +.hljs-selector-tag, +.hljs-deletion, +.hljs-subst { + color: #e06c75; +} + +.hljs-literal { + color: #56b6c2; +} + +.hljs-string, +.hljs-regexp, +.hljs-addition, +.hljs-attribute, +.hljs-meta-string { + color: #98c379; +} + +.hljs-built_in, +.hljs-class .hljs-title { + color: #e6c07b; +} + +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-type, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-number { + color: #d19a66; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link, +.hljs-meta, +.hljs-selector-id, +.hljs-title { + color: #61aeee; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-link { + text-decoration: underline; +} diff --git a/reference/html/js/highlight/styles/atom-one-light.min.css b/reference/html/js/highlight/styles/atom-one-light.min.css new file mode 100644 index 0000000000..d5bd1d2a9a --- /dev/null +++ b/reference/html/js/highlight/styles/atom-one-light.min.css @@ -0,0 +1,96 @@ +/* + +Atom One Light by Daniel Gamage +Original One Light Syntax theme from https://github.com/atom/one-light-syntax + +base: #fafafa +mono-1: #383a42 +mono-2: #686b77 +mono-3: #a0a1a7 +hue-1: #0184bb +hue-2: #4078f2 +hue-3: #a626a4 +hue-4: #50a14f +hue-5: #e45649 +hue-5-2: #c91243 +hue-6: #986801 +hue-6-2: #c18401 + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #383a42; + background: #fafafa; +} + +.hljs-comment, +.hljs-quote { + color: #a0a1a7; + font-style: italic; +} + +.hljs-doctag, +.hljs-keyword, +.hljs-formula { + color: #a626a4; +} + +.hljs-section, +.hljs-name, +.hljs-selector-tag, +.hljs-deletion, +.hljs-subst { + color: #e45649; +} + +.hljs-literal { + color: #0184bb; +} + +.hljs-string, +.hljs-regexp, +.hljs-addition, +.hljs-attribute, +.hljs-meta-string { + color: #50a14f; +} + +.hljs-built_in, +.hljs-class .hljs-title { + color: #c18401; +} + +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-type, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-number { + color: #986801; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link, +.hljs-meta, +.hljs-selector-id, +.hljs-title { + color: #4078f2; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-link { + text-decoration: underline; +} diff --git a/reference/html/js/highlight/styles/dracula.min.css b/reference/html/js/highlight/styles/dracula.min.css new file mode 100644 index 0000000000..d591db6801 --- /dev/null +++ b/reference/html/js/highlight/styles/dracula.min.css @@ -0,0 +1,76 @@ +/* + +Dracula Theme v1.2.0 + +https://github.com/zenorocha/dracula-theme + +Copyright 2015, All rights reserved + +Code licensed under the MIT license +http://zenorocha.mit-license.org + +@author Éverton Ribeiro +@author Zeno Rocha + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #282a36; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-section, +.hljs-link { + color: #8be9fd; +} + +.hljs-function .hljs-keyword { + color: #ff79c6; +} + +.hljs, +.hljs-subst { + color: #f8f8f2; +} + +.hljs-string, +.hljs-title, +.hljs-name, +.hljs-type, +.hljs-attribute, +.hljs-symbol, +.hljs-bullet, +.hljs-addition, +.hljs-variable, +.hljs-template-tag, +.hljs-template-variable { + color: #f1fa8c; +} + +.hljs-comment, +.hljs-quote, +.hljs-deletion, +.hljs-meta { + color: #6272a4; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-title, +.hljs-section, +.hljs-doctag, +.hljs-type, +.hljs-name, +.hljs-strong { + font-weight: bold; +} + +.hljs-emphasis { + font-style: italic; +} diff --git a/reference/html/js/highlight/styles/github.min.css b/reference/html/js/highlight/styles/github.min.css new file mode 100644 index 0000000000..791932b87e --- /dev/null +++ b/reference/html/js/highlight/styles/github.min.css @@ -0,0 +1,99 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; +} + +.hljs-comment, +.hljs-quote { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-subst { + color: #333; + font-weight: bold; +} + +.hljs-number, +.hljs-literal, +.hljs-variable, +.hljs-template-variable, +.hljs-tag .hljs-attr { + color: #008080; +} + +.hljs-string, +.hljs-doctag { + color: #d14; +} + +.hljs-title, +.hljs-section, +.hljs-selector-id { + color: #900; + font-weight: bold; +} + +.hljs-subst { + font-weight: normal; +} + +.hljs-type, +.hljs-class .hljs-title { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-name, +.hljs-attribute { + color: #000080; + font-weight: normal; +} + +.hljs-regexp, +.hljs-link { + color: #009926; +} + +.hljs-symbol, +.hljs-bullet { + color: #990073; +} + +.hljs-built_in, +.hljs-builtin-name { + color: #0086b3; +} + +.hljs-meta { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/html/js/highlight/styles/monokai-sublime.min.css b/reference/html/js/highlight/styles/monokai-sublime.min.css new file mode 100644 index 0000000000..2864170daf --- /dev/null +++ b/reference/html/js/highlight/styles/monokai-sublime.min.css @@ -0,0 +1,83 @@ +/* + +Monokai Sublime style. Derived from Monokai by noformnocontent http://nn.mit-license.org/ + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #23241f; +} + +.hljs, +.hljs-tag, +.hljs-subst { + color: #f8f8f2; +} + +.hljs-strong, +.hljs-emphasis { + color: #a8a8a2; +} + +.hljs-bullet, +.hljs-quote, +.hljs-number, +.hljs-regexp, +.hljs-literal, +.hljs-link { + color: #ae81ff; +} + +.hljs-code, +.hljs-title, +.hljs-section, +.hljs-selector-class { + color: #a6e22e; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-name, +.hljs-attr { + color: #f92672; +} + +.hljs-symbol, +.hljs-attribute { + color: #66d9ef; +} + +.hljs-params, +.hljs-class .hljs-title { + color: #f8f8f2; +} + +.hljs-string, +.hljs-type, +.hljs-built_in, +.hljs-builtin-name, +.hljs-selector-id, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-addition, +.hljs-variable, +.hljs-template-variable { + color: #e6db74; +} + +.hljs-comment, +.hljs-deletion, +.hljs-meta { + color: #75715e; +} diff --git a/reference/html/js/highlight/styles/monokai.min.css b/reference/html/js/highlight/styles/monokai.min.css new file mode 100644 index 0000000000..775d53f91a --- /dev/null +++ b/reference/html/js/highlight/styles/monokai.min.css @@ -0,0 +1,70 @@ +/* +Monokai style - ported by Luigi Maselli - http://grigio.org +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #272822; color: #ddd; +} + +.hljs-tag, +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-strong, +.hljs-name { + color: #f92672; +} + +.hljs-code { + color: #66d9ef; +} + +.hljs-class .hljs-title { + color: white; +} + +.hljs-attribute, +.hljs-symbol, +.hljs-regexp, +.hljs-link { + color: #bf79db; +} + +.hljs-string, +.hljs-bullet, +.hljs-subst, +.hljs-title, +.hljs-section, +.hljs-emphasis, +.hljs-type, +.hljs-built_in, +.hljs-builtin-name, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-addition, +.hljs-variable, +.hljs-template-tag, +.hljs-template-variable { + color: #a6e22e; +} + +.hljs-comment, +.hljs-quote, +.hljs-deletion, +.hljs-meta { + color: #75715e; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-doctag, +.hljs-title, +.hljs-section, +.hljs-type, +.hljs-selector-id { + font-weight: bold; +} diff --git a/reference/html/js/highlight/styles/solarized-light.min.css b/reference/html/js/highlight/styles/solarized-light.min.css new file mode 100644 index 0000000000..fdcfcc72c4 --- /dev/null +++ b/reference/html/js/highlight/styles/solarized-light.min.css @@ -0,0 +1,84 @@ +/* + +Orginal Style from ethanschoonover.com/solarized (c) Jeremy Hull + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #fdf6e3; + color: #657b83; +} + +.hljs-comment, +.hljs-quote { + color: #93a1a1; +} + +/* Solarized Green */ +.hljs-keyword, +.hljs-selector-tag, +.hljs-addition { + color: #859900; +} + +/* Solarized Cyan */ +.hljs-number, +.hljs-string, +.hljs-meta .hljs-meta-string, +.hljs-literal, +.hljs-doctag, +.hljs-regexp { + color: #2aa198; +} + +/* Solarized Blue */ +.hljs-title, +.hljs-section, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class { + color: #268bd2; +} + +/* Solarized Yellow */ +.hljs-attribute, +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-class .hljs-title, +.hljs-type { + color: #b58900; +} + +/* Solarized Orange */ +.hljs-symbol, +.hljs-bullet, +.hljs-subst, +.hljs-meta, +.hljs-meta .hljs-keyword, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-link { + color: #cb4b16; +} + +/* Solarized Red */ +.hljs-built_in, +.hljs-deletion { + color: #dc322f; +} + +.hljs-formula { + background: #eee8d5; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/html/js/highlight/styles/zenburn.min.css b/reference/html/js/highlight/styles/zenburn.min.css new file mode 100644 index 0000000000..07be502016 --- /dev/null +++ b/reference/html/js/highlight/styles/zenburn.min.css @@ -0,0 +1,80 @@ +/* + +Zenburn style from voldmar.ru (c) Vladimir Epifanov +based on dark.css by Ivan Sagalaev + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #3f3f3f; + color: #dcdcdc; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-tag { + color: #e3ceab; +} + +.hljs-template-tag { + color: #dcdcdc; +} + +.hljs-number { + color: #8cd0d3; +} + +.hljs-variable, +.hljs-template-variable, +.hljs-attribute { + color: #efdcbc; +} + +.hljs-literal { + color: #efefaf; +} + +.hljs-subst { + color: #8f8f8f; +} + +.hljs-title, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-section, +.hljs-type { + color: #efef8f; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link { + color: #dca3a3; +} + +.hljs-deletion, +.hljs-string, +.hljs-built_in, +.hljs-builtin-name { + color: #cc9393; +} + +.hljs-addition, +.hljs-comment, +.hljs-quote, +.hljs-meta { + color: #7f9f7f; +} + + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/html/js/toc.js b/reference/html/js/toc.js new file mode 100644 index 0000000000..a6e933bf96 --- /dev/null +++ b/reference/html/js/toc.js @@ -0,0 +1,107 @@ +var toctitle = document.getElementById('toctitle'); +var path = window.location.pathname; +if (toctitle != null) { + var oldtoc = toctitle.nextElementSibling; + var newtoc = document.createElement('div'); + newtoc.setAttribute('id', 'tocbot'); + newtoc.setAttribute('class', 'js-toc desktop-toc'); + oldtoc.setAttribute('class', 'mobile-toc'); + oldtoc.parentNode.appendChild(newtoc); + tocbot.init({ + contentSelector: '#content', + headingSelector: 'h1, h2, h3, h4, h5', + positionFixedSelector: 'body', + fixedSidebarOffset: 90, + smoothScroll: false + }); + if (!path.endsWith("index.html") && !path.endsWith("/")) { + var link = document.createElement("a"); + link.setAttribute("href", "index.html"); + link.innerHTML = " Back to index"; + var block = document.createElement("div"); + block.setAttribute('class', 'back-action'); + block.appendChild(link); + var toc = document.getElementById('toc'); + var next = document.getElementById('toctitle').nextElementSibling; + toc.insertBefore(block, next); + } +} + +var headerHtml = '
\n' + + '

\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '

\n' + + '
'; + +var header = document.createElement("div"); +header.innerHTML = headerHtml; +document.body.insertBefore(header, document.body.firstChild); \ No newline at end of file diff --git a/reference/html/js/tocbot/tocbot.css b/reference/html/js/tocbot/tocbot.css new file mode 100644 index 0000000000..0632de2328 --- /dev/null +++ b/reference/html/js/tocbot/tocbot.css @@ -0,0 +1 @@ +.toc{overflow-y:auto}.toc>.toc-list{overflow:hidden;position:relative}.toc>.toc-list li{list-style:none}.toc-list{margin:0;padding-left:10px}a.toc-link{color:currentColor;height:100%}.is-collapsible{max-height:1000px;overflow:hidden;transition:all 300ms ease-in-out}.is-collapsed{max-height:0}.is-position-fixed{position:fixed !important;top:0}.is-active-link{font-weight:700}.toc-link::before{background-color:#EEE;content:' ';display:inline-block;height:inherit;left:0;margin-top:-1px;position:absolute;width:2px}.is-active-link::before{background-color:#54BC4B} diff --git a/reference/html/js/tocbot/tocbot.min.js b/reference/html/js/tocbot/tocbot.min.js new file mode 100644 index 0000000000..943d8fdb77 --- /dev/null +++ b/reference/html/js/tocbot/tocbot.min.js @@ -0,0 +1 @@ +!function(e){function t(o){if(n[o])return n[o].exports;var l=n[o]={i:o,l:!1,exports:{}};return e[o].call(l.exports,l,l.exports,t),l.l=!0,l.exports}var n={};t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=0)}([function(e,t,n){(function(o){var l,i,s;!function(n,o){i=[],l=o(n),void 0!==(s="function"==typeof l?l.apply(t,i):l)&&(e.exports=s)}(void 0!==o?o:this.window||this.global,function(e){"use strict";function t(){for(var e={},t=0;te.fixedSidebarOffset?-1===n.className.indexOf(e.positionFixedClass)&&(n.className+=h+e.positionFixedClass):n.className=n.className.split(h+e.positionFixedClass).join("")}function s(t){var n=document.documentElement.scrollTop||f.scrollTop;e.positionFixedSelector&&i();var o,l=t;if(m&&null!==document.querySelector(e.tocSelector)&&l.length>0){d.call(l,function(t,i){if(t.offsetTop>n+e.headingsOffset+10){return o=l[0===i?i:i-1],!0}if(i===l.length-1)return o=l[l.length-1],!0});var s=document.querySelector(e.tocSelector).querySelectorAll("."+e.linkClass);u.call(s,function(t){t.className=t.className.split(h+e.activeLinkClass).join("")});var c=document.querySelector(e.tocSelector).querySelectorAll("."+e.listItemClass);u.call(c,function(t){t.className=t.className.split(h+e.activeListItemClass).join("")});var a=document.querySelector(e.tocSelector).querySelector("."+e.linkClass+".node-name--"+o.nodeName+'[href="#'+o.id+'"]');-1===a.className.indexOf(e.activeLinkClass)&&(a.className+=h+e.activeLinkClass);var p=a.parentNode;p&&-1===p.className.indexOf(e.activeListItemClass)&&(p.className+=h+e.activeListItemClass);var C=document.querySelector(e.tocSelector).querySelectorAll("."+e.listClass+"."+e.collapsibleClass);u.call(C,function(t){-1===t.className.indexOf(e.isCollapsedClass)&&(t.className+=h+e.isCollapsedClass)}),a.nextSibling&&-1!==a.nextSibling.className.indexOf(e.isCollapsedClass)&&(a.nextSibling.className=a.nextSibling.className.split(h+e.isCollapsedClass).join("")),r(a.parentNode.parentNode)}}function r(t){return-1!==t.className.indexOf(e.collapsibleClass)&&-1!==t.className.indexOf(e.isCollapsedClass)?(t.className=t.className.split(h+e.isCollapsedClass).join(""),r(t.parentNode.parentNode)):t}function c(t){var n=t.target||t.srcElement;"string"==typeof n.className&&-1!==n.className.indexOf(e.linkClass)&&(m=!1)}function a(){m=!0}var u=[].forEach,d=[].some,f=document.body,m=!0,h=" ";return{enableTocAnimation:a,disableTocAnimation:c,render:n,updateToc:s}}},function(e,t){e.exports=function(e){function t(e){return e[e.length-1]}function n(e){return+e.nodeName.split("H").join("")}function o(t){var o={id:t.id,children:[],nodeName:t.nodeName,headingLevel:n(t),textContent:t.textContent.trim()};return e.includeHtml&&(o.childNodes=t.childNodes),o}function l(l,i){for(var s=o(l),r=n(l),c=i,a=t(c),u=a?a.headingLevel:0,d=r-u;d>0;)a=t(c),a&&void 0!==a.children&&(c=a.children),d--;return r>=e.collapseDepth&&(s.isCollapsed=!0),c.push(s),c}function i(t,n){var o=n;e.ignoreSelector&&(o=n.split(",").map(function(t){return t.trim()+":not("+e.ignoreSelector+")"}));try{return document.querySelector(t).querySelectorAll(o)}catch(e){return console.warn("Element not found: "+t),null}}function s(e){return r.call(e,function(e,t){return l(o(t),e.nest),e},{nest:[]})}var r=[].reduce;return{nestHeadingsArray:s,selectHeadings:i}}},function(e,t){function n(e){function t(e){return"a"===e.tagName.toLowerCase()&&(e.hash.length>0||"#"===e.href.charAt(e.href.length-1))&&(n(e.href)===s||n(e.href)+"#"===s)}function n(e){return e.slice(0,e.lastIndexOf("#"))}function l(e){var t=document.getElementById(e.substring(1));t&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())}!function(){document.documentElement.style}();var i=e.duration,s=location.hash?n(location.href):location.href;!function(){function n(n){!t(n.target)||n.target.className.indexOf("no-smooth-scroll")>-1||"#"===n.target.href.charAt(n.target.href.length-2)&&"!"===n.target.href.charAt(n.target.href.length-1)||-1===n.target.className.indexOf(e.linkClass)||o(n.target.hash,{duration:i,callback:function(){l(n.target.hash)}})}document.body.addEventListener("click",n,!1)}()}function o(e,t){function n(e){s=e-i,window.scrollTo(0,c.easing(s,r,u,d)),s + + + + + + +Links + + + + + + + + + + +
+
+ +
+
+

The following links may be helpful when working with Spring Cloud Contract:

+
+ +
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/migrations.html b/reference/html/migrations.html new file mode 100644 index 0000000000..c8c70230a3 --- /dev/null +++ b/reference/html/migrations.html @@ -0,0 +1,345 @@ + + + + + + + +Migrations + + + + + + + + + + +
+
+

Migrations

+
+
+ + + + + +
+ + +For up to date migration guides please visit +the project’s wiki page. +
+
+
+

This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths:

+
+
+

1.0.x → 1.1.x

+
+

This section covers upgrading from version 1.0 to version 1.1.

+
+
+

New structure of generated stubs

+
+

In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
+
+
+
+

You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
+
+
+
+

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet.

+
+
+
Maven
+
+
<!-- start of pom.xml -->
+
+<properties>
+    <!-- we don't want the verifier to do a jar for us -->
+    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+</properties>
+
+<!-- ... -->
+
+<!-- You need to set up the assembly plugin -->
+<build>
+    <plugins>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-assembly-plugin</artifactId>
+            <executions>
+                <execution>
+                    <id>stub</id>
+                    <phase>prepare-package</phase>
+                    <goals>
+                        <goal>single</goal>
+                    </goals>
+                    <inherited>false</inherited>
+                    <configuration>
+                        <attach>true</attach>
+                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
+                    </configuration>
+                </execution>
+            </executions>
+        </plugin>
+    </plugins>
+</build>
+<!-- end of pom.xml -->
+
+<!-- start of stub.xml-->
+
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>customer-stubs/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>customer-stubs/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+<!-- end of stub.xml-->
+
+
+
+
Gradle
+
+
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
+//    Preserve directory structure from 1.0.X of spring-cloud-contract
+    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
+    into "${project.buildDir}/resources/main/customer-stubs"
+}
+
+
+
+
+
+

1.1.x → 1.2.x

+
+

This section covers upgrading from version 1.1 to version 1.2.

+
+
+

Custom HttpServerStub

+
+

HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub.

+
+
+

See issue 355 for more +detail.

+
+
+
+

New packages for generated tests

+
+

The flow for setting the generated tests package name will look like this:

+
+
+
    +
  • +

    Set basePackageForTests

    +
  • +
  • +

    If basePackageForTests was not set, pick the package from baseClassForTests

    +
  • +
  • +

    If baseClassForTests was not set, pick packageWithBaseClasses

    +
  • +
  • +

    If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests

    +
  • +
+
+
+

See issue 260 for more +detail.

+
+
+
+

New Methods in TemplateProcessor

+
+

In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface:

+
+
+
    +
  • +

    path()

    +
  • +
  • +

    path(int index)

    +
  • +
+
+
+

See issue 388 for more +detail.

+
+
+
+

RestAssured 3.0

+
+

Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception:

+
+
+
+
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
+[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist
+
+
+
+

This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa).

+
+
+

Done via issue 267

+
+
+
+ +
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/sagan-boot.html b/reference/html/sagan-boot.html new file mode 100644 index 0000000000..f35bb626fc --- /dev/null +++ b/reference/html/sagan-boot.html @@ -0,0 +1,221 @@ + + + + + + + +Untitled + + + + + + + + + + +
+
+
+
+

Add Sleuth to your classpath:

+
+
+

Maven

+
+
+
+
<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-sleuth</artifactId>
+            <version>${spring-cloud-sleuth.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+<dependencies>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-sleuth</artifactId>
+    </dependency>
+</dependencies>
+
+
+
+

Gradle

+
+
+
+
buildscript {
+    dependencies {
+        classpath "io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE"
+    }
+}
+
+apply plugin: "io.spring.dependency-management"
+
+dependencyManagement {
+     imports {
+          mavenBom "org.springframework.cloud:spring-cloud-sleuth:${springCloudSleuthVersion}"
+     }
+}
+dependencies {
+    compile 'org.springframework.cloud:spring-cloud-starter-sleuth'
+}
+
+
+
+

As long as Spring Cloud Sleuth is on the classpath any Spring Boot application will generate trace data:

+
+
+
+
@SpringBootApplication
+@RestController
+public class Application {
+
+  private static Logger log = LoggerFactory.getLogger(DemoController.class);
+
+  @RequestMapping("/")
+  public String home() {
+    log.info("Handling home");
+    return "Hello World";
+  }
+
+  public static void main(String[] args) {
+    SpringApplication.run(Application.class, args);
+  }
+
+}
+
+
+
+

Run this app and then hit the home page. You will see traceId and spanId populated in the logs. If this app calls out to another one (e.g. with RestTemplate) it will send the trace data in headers and if the receiver is another Sleuth app you will see the trace continue there.

+
+
+ + + + + +
+ + +instead of logging the request in the handler explicitly, you could set logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG +
+
+
+ + + + + +
+ + +If you use Zipkin, configure the probability of spans exported by setting (for 2.0.x) spring.sleuth.sampler.probability or (up till 2.0.x)spring.sleuth.sampler.percentage (default: 0.1, which is 10 percent). Otherwise, you might think that Sleuth is not working because it omits some spans. +
+
+
+ + + + + +
+ + +Set spring.application.name=bar (for instance) to see the service name as well as the trace and span ids. +
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/sagan-index.html b/reference/html/sagan-index.html new file mode 100644 index 0000000000..2a8d4f86af --- /dev/null +++ b/reference/html/sagan-index.html @@ -0,0 +1,144 @@ + + + + + + + +Features + + + + + + + + + + +
+
+
+
+

Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from Dapper, Zipkin and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service.

+
+
+
+
+

Features

+
+
+

A Span is the basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Span’s are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, key-value annotations, the ID of the span that caused them, and process ID’s (normally IP address). Spans are started and stopped, and they keep track of their timing information. Once you create a span, you must stop it at some point in the future. A set of spans forming a tree-like structure called a Trace. For example, if you are running a distributed big-data store, a trace might be formed by a put request.

+
+
+

Spring Cloud Sleuth features:

+
+
+
    +
  • +

    Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator.

    +
  • +
  • +

    Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible.

    +
  • +
  • +

    Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client).

    +
  • +
  • +

    If spring-cloud-sleuth-zipkin is available then the app will generate and collect Zipkin-compatible traces via HTTP. By default it sends them to a Zipkin collector service on localhost (port 9411). Configure the location of the service using spring.zipkin.baseUrl.

    +
  • +
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/spring-cloud-contract-verifier.html b/reference/html/spring-cloud-contract-verifier.html new file mode 100644 index 0000000000..9a43812cd9 --- /dev/null +++ b/reference/html/spring-cloud-contract-verifier.html @@ -0,0 +1,13979 @@ + + + + + + + +Spring Cloud Contract Verifier Introduction + + + + + + + + + + +
+
+

Spring Cloud Contract Verifier Introduction

+
+
+

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

+
+
+

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

+
+
+
    +
  • +

    JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.

    +
  • +
  • +

    Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.

    +
  • +
  • +

    Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

    +
  • +
+
+
+

History

+
+

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

+
+
+

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

+
+
+
+

Why a Contract Verifier?

+
+

Assume that we have a system consisting of multiple microservices:

+
+
+

Testing issues

+
+

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

+
+
+
    +
  • +

    Deploy all microservices and perform end-to-end tests.

    +
  • +
  • +

    Mock other microservices in unit/integration tests.

    +
  • +
+
+
+

Both have their advantages but also a lot of disadvantages.

+
+
+

Deploy all microservices and perform end to end tests

+
+
+

Advantages:

+
+
+
    +
  • +

    Simulates production.

    +
  • +
  • +

    Tests real communication between services.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.

    +
  • +
  • +

    The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).

    +
  • +
  • +

    They take a long time to run.

    +
  • +
  • +

    The feedback comes very late in the process.

    +
  • +
  • +

    They are extremely hard to debug.

    +
  • +
+
+
+

Mock other microservices in unit/integration tests

+
+
+

Advantages:

+
+
+
    +
  • +

    They provide very fast feedback.

    +
  • +
  • +

    They have no infrastructure requirements.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    The implementor of the service creates stubs that might have nothing to do with +reality.

    +
  • +
  • +

    You can go to production with passing tests and failing production.

    +
  • +
+
+
+

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

+
+
+

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

+
+
+
+
+

Purposes

+
+

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

+
+
+
    +
  • +

    To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.

    +
  • +
  • +

    To promote ATDD method and Microservices architectural style.

    +
  • +
  • +

    To provide a way to publish changes in contracts that are immediately visible on both +sides.

    +
  • +
  • +

    To generate boilerplate test code to be used on the server side.

    +
  • +
+
+
+ + + + + +
+ + +Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. +
+
+
+
+

How It Works

+
+

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

+
+
+

A Three-second Tour

+
+

This very brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find a somewhat longer tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    +
    +
    +
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

+
+
+
+
+

A Three-minute Tour

+
+

This brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find an even more brief tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

+
+
+
+
package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}
+
+
+
+

The same contract expressed in YAML would look like the following example:

+
+
+
+
request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8
+
+
+
+

In the case of messaging, you can define:

+
+
+
    +
  • +

    The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).

    +
  • +
  • +

    The methods that should be called after the message is received.

    +
  • +
  • +

    The methods that, when called, should trigger a message.

    +
  • +
+
+
+

The following example shows a Camel messaging contract expressed in Groovy DSL:

+
+
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+

The following example shows the same contract expressed in YAML:

+
+
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

+
+
+

The following example shows a sample auto-generated test for an HTTP contract:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

+
+
+

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

+
+
+

Here is an example of a test generated in WEBTESTCLIENT test mode:

+
+
+
+
[source,java,indent=0]
+
+
+
+
+
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}
+
+
+
+

Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin +testFramework property to either JUNIT5, TESTNG or Spock.

+
+
+ + + + + +
+ + +You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. +
+
+
+

The following example shows an auto-generated test in Spock for a messaging stub contract:

+
+
+
+
[source,groovy,indent=0]
+
+
+
+
+
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+
+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

+
+
+

Docker Project

+
+
+

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To get started, add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    +
    +
    +
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+
+
+

Defining the Contract

+
+

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

+
+
+

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+
+

Client Side

+
+

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

+
+
+
+

Server Side

+
+

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

+
+
+

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

+
+
+

The autogenerated test looks, more or less, like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+
+
+

Step-by-step Guide to Consumer Driven Contracts (CDC)

+
+

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

+
+
+

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

+
+
+

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

+
+
+

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

+
+ +
+ + + + + +
+ + +In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository. +
+
+
+

Technical note

+
+

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
repositories {
+	mavenCentral()
+	mavenLocal()
+	maven { url "https://repo.spring.io/snapshot" }
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/release" }
+}
+
+
+
+
+

Consumer side (Loan Issuance)

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

+
+
+
    +
  1. +

    Start doing TDD by writing a test for your feature.

    +
  2. +
  3. +

    Write the missing implementation.

    +
  4. +
  5. +

    Clone the Fraud Detection service repository locally.

    +
  6. +
  7. +

    Define the contract locally in the repo of Fraud Detection service.

    +
  8. +
  9. +

    Add the Spring Cloud Contract Verifier plugin.

    +
  10. +
  11. +

    Run the integration tests.

    +
  12. +
  13. +

    File a pull request.

    +
  14. +
  15. +

    Create an initial implementation.

    +
  16. +
  17. +

    Take over the pull request.

    +
  18. +
  19. +

    Write the missing implementation.

    +
  20. +
  21. +

    Deploy your app.

    +
  22. +
  23. +

    Work online.

    +
  24. +
+
+
+

Start doing TDD by writing a test for your feature.

+
+
+
+
@Test
+public void shouldBeRejectedDueToAbnormalLoanAmount() {
+	// given:
+	LoanApplication application = new LoanApplication(new Client("1234567890"),
+			99999);
+	// when:
+	LoanApplicationResult loanApplication = service.loanApplication(application);
+	// then:
+	assertThat(loanApplication.getLoanApplicationStatus())
+			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
+	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
+}
+
+
+
+

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

+
+
+

Write the missing implementation.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

+
+
+

If you start the test at this point, it breaks, because no service currently runs on port +8080.

+
+
+

Clone the Fraud Detection service repository locally.

+
+
+

You can start by playing around with the server side contract. To do so, you must first +clone it.

+
+
+
+
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
+
+
+
+

Define the contract locally in the repo of Fraud Detection service.

+
+
+

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

+
+
+ + + + + +
+ + +Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder. +
+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the Contract DSL section for more information. We highly recommend using the map notation!

+
+
+ + + + + +
+ + +You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON. +
+
+
+

The previously shown contract is an agreement between two sides that:

+
+
+
    +
  • +

    if an HTTP request is sent with all of

    +
    +
      +
    • +

      a PUT method on the /fraudcheck endpoint,

      +
    • +
    • +

      a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json,

      +
    • +
    +
    +
  • +
  • +

    then an HTTP response is sent to the consumer that

    +
    +
      +
    • +

      has status 200,

      +
    • +
    • +

      contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json.

      +
    • +
    +
    +
  • +
+
+
+

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

+
+
+

Add the Spring Cloud Contract Verifier plugin.

+
+
+

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

+
+
+
    +
  • +

    generate and run tests

    +
  • +
  • +

    produce and install stubs

    +
  • +
+
+
+

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

+
+
+
+
$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests
+
+
+
+

In the logs, you see something like this:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

The following line is extremely important:

+
+
+
+
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

It confirms that the stubs of the http-server have been installed in the local +repository.

+
+
+

Run the integration tests.

+
+
+

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

+
+
+

Add the Spring Cloud Contract BOM:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release-train.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

Now, when you run your tests, you see something like this:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

+
+
+

File a pull request.

+
+
+

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

+
+
+

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

+
+
+
+

Producer side (Fraud Detection server)

+
+

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

+
+
+

Create an initial implementation.

+
+
+

As a reminder, you can see the initial implementation here:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

Take over the pull request.

+
+
+
+
$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
+
+
+
+

You must add the dependencies needed by the autogenerated tests:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+ + + + + +
+ + +This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name. +
+
+
+

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

+
+
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class FraudBase {
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
+				new FraudStatsController(stubbedStatsProvider()));
+	}
+
+	private StatsProvider stubbedStatsProvider() {
+		return fraudType -> {
+			switch (fraudType) {
+			case DRUNKS:
+				return 100;
+			case ALL:
+				return 200;
+			}
+			return 0;
+		};
+	}
+
+	public void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

Now, if you run the ./mvnw clean install, you get something like this:

+
+
+
+
Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
+
+
+
+

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

+
+
+

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

+
+
+

Write the missing implementation.

+
+
+

Because you know the expected input and expected output, you can write the missing +implementation:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+if (amountGreaterThanThreshold(fraudCheck)) {
+	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
+}
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

+
+
+

Deploy your app.

+
+
+

Once you finish your work, you can deploy your change. First, merge the branch:

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master
+
+
+
+

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

+
+
+
+

Consumer Side (Loan Issuance) Final Step

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

+
+
+

Merge branch to master.

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+
+
+
+

Work online.

+
+
+

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

+
+
+
+
+
+
+
+

That’s it!

+
+
+
+
+

Dependencies

+
+

The best way to add dependencies is to use the proper starter dependency.

+
+
+

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

+
+
+
+ +
+

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

+
+
+

Spring Cloud Contract video

+
+

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

+
+
+
+ +
+
+
+ +
+
+

Samples

+
+

You can find some samples at +samples.

+
+
+
+
+
+

Spring Cloud Contract FAQ

+
+
+

Why use Spring Cloud Contract Verifier and not X ?

+
+

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

+
+
+
    +
  • +

    Possibility to do CDC with messaging

    +
  • +
  • +

    Clear and easy to use, statically typed DSL

    +
  • +
  • +

    Possibility to copy paste your current JSON file to the contract and only edit its elements

    +
  • +
  • +

    Automatic generation of tests from the defined Contract

    +
  • +
  • +

    Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory

    +
  • +
  • +

    Spring Cloud integration - no discovery service is needed for integration tests

    +
  • +
  • +

    Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality

    +
  • +
  • +

    Via Docker adds support for any language & framework used

    +
  • +
+
+
+
+

I don’t want to write a contract in Groovy!

+
+

No problem. You can write a contract in YAML!

+
+
+
+

What is this value(consumer(), producer()) ?

+
+

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

and JSON response

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

+
+
+

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}
+
+
+
+

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}
+
+
+
+

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

+
+
+

Either via the value method

+
+
+
+
value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

or using the $() method

+
+
+
+
$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

You can read more about this in the Contract DSL section.

+
+
+

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

+
+
+ + + + + +
+ + +If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated. +
+
+
+

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

+
+
+

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
+
+
+
+ + + + + +
+ + +Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies. +
+
+
+
+

How to do Stubs versioning?

+
+

API Versioning

+
+

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

+
+
+
    +
  • +

    use Hypermedia, links and do not version your API by any means

    +
  • +
  • +

    pass versions through headers / urls

    +
  • +
+
+
+

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

+
+
+

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

+
+
+
+

JAR versioning

+
+

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

+
+
+

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

+
+
+
+
1.0.0.20161020-201521-RELEASE
+
+
+
+

In that case your generated stub jar will look like this.

+
+
+
+
1.0.0.20161020-201521-RELEASE-stubs.jar
+
+
+
+

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
+
+
+
+
+

Dev or prod stubs

+
+

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

+
+
+

Example of tests using development version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

Example of tests using production version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
+
+
+
+

You can pass those values also via properties from your deployment pipeline.

+
+
+
+
+

Common repo with contracts

+
+

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

+
+
+

Repo structure

+
+

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

+
+
+
+
├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml
+
+
+
+

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

+
+
+

Example of a pom.xml inside the server folder.

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.2.0.M4</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>
+
+
+
+

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

+
+
+

The pom.xml in the root folder can look like this:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>
+
+
+
+

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

+
+
+
+
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
+

Workflow

+
+

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

+
+
+
+

Consumer

+
+

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

+
+
+ + + + + +
+ + +You need to have Maven installed locally +
+
+
+
+

Producer

+
+

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>
+
+
+
+

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from https://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

+
+
+

The rest of the flow looks the same.

+
+
+
+

How can I define messaging contracts per topic not per producer?

+
+

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

+
+
+
For Maven Project
+
+

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

+
+
+
+
<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>
+
+
+
+
+
For Gradle Project
+
+
    +
  • +

    Add a custom configuration for the common-repo dependency:

    +
  • +
+
+
+
+
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
+
+
+
+
    +
  • +

    Add the common-repo dependency to your classpath:

    +
  • +
+
+
+
+
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
+
+
+
+
    +
  • +

    Download the dependency to an appropriate folder:

    +
  • +
+
+
+
+
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
+
+
+
+
    +
  • +

    Unzip JAR:

    +
  • +
+
+
+
+
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
+
+
+
+
    +
  • +

    Cleanup unused contracts:

    +
  • +
+
+
+
+
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
+
+
+
+
    +
  • +

    Create task dependencies:

    +
  • +
+
+
+
+
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
+
+
+
+
    +
  • +

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

    +
  • +
+
+
+
+
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}
+
+
+
+
+
+
+

Do I need a Binary Storage? Can’t I use Git?

+
+

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

+
+
+

The repository would have to the following setup +(which you can checkout here):

+
+
+
+
.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json
+
+
+
+

Under META-INF folder:

+
+
+
    +
  • +

    we group applications via groupId (e.g. com.example)

    +
  • +
  • +

    then each application is represented via the artifactId (e.g. beer-api-producer-git)

    +
  • +
  • +

    next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    +
    +
      +
    • +

      + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT

        +
      • +
      • +

        if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called latest or + we will pick that folder

        +
      • +
      +
      +
    • +
    • +

      release - to find the latest release version of your stubs. That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called release we will pick that folder

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    finally, there are two folders:

    +
    +
      +
    • +

      contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.

      +
    • +
    • +

      mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

      +
    • +
    +
    +
  • +
+
+
+

Protocol convention

+
+

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

+
+
+

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

+
+
+
+
git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+
+
+
+
+

Producer

+
+

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

+
+
+ + + + + +
+ + +You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass, the stubs will be committed in the cloned repository

    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
+

Producer with contracts stored locally

+
+

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<!-- In the default configuration, we want to use the contracts stored locally -->
+	<configuration>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*messaging.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
+			</baseClassMapping>
+			<baseClassMapping>
+				<contractPackageRegex>.*rest.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+		<basePackageForTests>com.example</basePackageForTests>
+	</configuration>
+	<executions>
+		<execution>
+			<phase>package</phase>
+			<goals>
+				<!-- By default we will not push the stubs back to SCM,
+				you have to explicitly add it as a goal -->
+				<goal>pushStubsToScm</goal>
+			</goals>
+			<configuration>
+				<!-- We want to pick contracts from a Git repository -->
+				<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
+				</contractsRepositoryUrl>
+				<!-- Example of URL via git protocol -->
+				<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- Example of URL via http protocol -->
+				<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- We reuse the contract dependency section to set up the path
+				to the folder that contains the contract definitions. In our case the
+				path will be /groupId/artifactId/version/contracts -->
+				<contractDependency>
+					<groupId>${project.groupId}</groupId>
+					<artifactId>${project.artifactId}</artifactId>
+					<version>${project.version}</version>
+				</contractDependency>
+				<!-- The mode can't be classpath -->
+				<contractsMode>LOCAL</contractsMode>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		// Base package for generated tests
+	basePackageForTests = "com.example"
+	baseClassMappings {
+		baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
+		baseClassMapping(".*rest.*", "com.example.BeerRestBase")
+	}
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publishStubsToScm {
+	// We want to modify the default set up of the plugin when publish stubs to scm is called
+	customize {
+		// We want to pick contracts from a Git repository
+		contractDependency {
+			stringNotation = "${project.group}:${project.name}:${project.version}"
+		}
+		/*
+		We reuse the contract dependency section to set up the path
+		to the folder that contains the contract definitions. In our case the
+		path will be /groupId/artifactId/version/contracts
+		 */
+		contractRepository {
+			repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
+		}
+		// The mode can't be classpath
+		contractsMode = "LOCAL"
+	}
+}
+
+publish.dependsOn("publishStubsToScm")
+publishToMavenLocal.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Contracts from the default src/test/resources/contracts directory will be picked

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass

    +
    +
      +
    • +

      Git project will be cloned to a temporary directory

      +
    • +
    • +

      The stubs and contracts will be committed in the cloned repository

      +
    • +
    +
    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
Keeping contracts with the producer and stubs in an external repository
+
+

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

+
+
+

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

+
+
+
+
+

Consumer

+
+

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

+
+
+
+
@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/

    +
  • +
  • +

    Stub servers will be started and fed with mappings

    +
  • +
  • +

    Messaging definitions will be read and used in the messaging tests

    +
  • +
+
+
+
+
+

Can I use the Pact Broker?

+
+

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

+
+
+

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the Pact Converter section.

+
+
+ + + + + +
+ + +Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met. +
+
+
+

Pact Consumer

+
+

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

+
+
+
+

Producer

+
+

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into tests and stubs

    +
  • +
  • +

    The JAR with the stubs gets automatically created as usual

    +
  • +
+
+
+
+

Pact Consumer (Producer Contract approach)

+
+

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

+
+
+

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

+
+
+
Maven
+
+
<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+
Gradle
+
+
dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}
+
+
+
+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into stub definitions

    +
  • +
  • +

    The stub servers will be started and fed with stubs

    +
  • +
+
+
+

For more information about Pact support you can go to +the Using the Pact Stub Downloader section.

+
+
+
+
+

How can I debug the request/response being sent by the generated tests client?

+
+

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

+
+
+
+
logging.level.org.apache.http.wire=DEBUG
+
+
+
+

How can I debug the mapping/request/response being sent by WireMock?

+
+

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

+
+
+

To turn off this feature just bump WireMock logging to ERROR

+
+
+
+
logging.level.com.github.tomakehurst.wiremock=ERROR
+
+
+
+
+

How can I see what got registered in the HTTP server stub?

+
+

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

+
+
+
+

Can I reference text from file?

+
+

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

+
+
+
+
+
+
+

Spring Cloud Contract Verifier Setup

+
+
+

You can set up Spring Cloud Contract Verifier in the following ways:

+
+ +
+

Gradle Project

+
+

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

Prerequisites

+
+

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

+
+
+ + + + + +
+ + +If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information +
+
+
+
+

Add Gradle Plugin with Dependencies

+
+

To add a Gradle plugin with dependencies, use code similar to this:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}
+
+
+
+
+

Gradle and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}
+
+
+
+

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

Snapshot Versions for Gradle

+
+

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+}
+
+
+
+
+

Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

+
+
+

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

Run the Plugin

+
+

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

+
+
+
+

Default Setup

+
+

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

+
+
+
+
contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}
+
+
+
+
+

Configure Plugin

+
+

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

+
+
+
+
contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}
+
+
+
+
+

Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    +
  • +
  • +

    staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.

    +
  • +
  • +

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.

    +
  • +
  • +

    contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.

    +
  • +
  • +

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

The following properties are used when you want to specify the location of the JAR +containing the contracts:

+
+
+
    +
  • +

    contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.

    +
  • +
  • +

    contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.

    +
  • +
  • +

    contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

+
+
+
+

Different Base Classes for Contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    Provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
packageWithBaseClasses = 'com.example.base'
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
baseClassForTests = "com.example.FooBase"
+baseClassMappings {
+	baseClassMapping('.*/com/.*', 'com.example.ComBase')
+	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
+}
+
+
+
+

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

Invoking Generated Tests

+
+

To ensure that the provider side is compliant with defined contracts, you need to invoke:

+
+
+
+
./gradlew generateContractTests test
+
+
+
+
+

Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

+
+
+
+
$ ./gradlew pushStubsToScm
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

+
+
+
+

Spring Cloud Contract Verifier on the Consumer Side

+
+

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

+
+
+
+
./gradlew generateClientStubs
+
+
+
+ + + + + +
+ + +The stubsOutputDir option has to be set for stub generation to work. +
+
+
+

When present, JSON stubs can be used in automated tests of consuming a service.

+
+
+
+
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}
+
+
+
+

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

+
+
+
+
+

Maven Project

+
+

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

Add maven plugin

+
+

Add the Spring Cloud Contract BOM in a fashion similar to this:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+ +
+
+

Maven and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

Snapshot versions for Maven

+
+

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

+
+
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
+

Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

Run plugin

+
+

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

+
+
+
+

Configure plugin

+
+

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>
+
+
+
+
+

Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.

    +
  • +
  • +

    baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

If you want to download your contract definitions from a Maven repository, you can use +the following options:

+
+
+
    +
  • +

    contractDependency: The contract dependency that contains all the packaged contracts.

    +
  • +
  • +

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.

    +
  • +
  • +

    contractsMode: Picks the mode in which stubs will be found and registered

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
  • +

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.

    +
  • +
  • +

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    +
  • +
+
+
+

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}
+
+
+
+

You can also setup the whole context if necessary.

+
+
+
+
import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}
+
+
+
+

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}
+
+
+
+

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

+
+
+
+

Different base classes for contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<packageWithBaseClasses>hello</packageWithBaseClasses>
+	</configuration>
+</plugin>
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<baseClassForTests>com.example.FooBase</baseClassForTests>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*com.*</contractPackageRegex>
+				<baseClassFQN>com.example.TestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+</plugin>
+
+
+
+

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

Invoking generated tests

+
+

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

+
+
+

For Groovy Spock code, use the following:

+
+
+
+
<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>
+
+
+
+

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

+
+
+
+

Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

+
+
+
+

Maven Plugin and STS

+
+

If you see the following exception while using STS:

+
+
+
+STS Exception +
+
+
+

When you click on the error marker you should see something like this:

+
+
+
+
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
+
+
+
+

In order to fix this issue, provide the following section in your pom.xml:

+
+
+
+
<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>
+
+
+
+
+

Maven Plugin with Spock Tests

+
+

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

+
+
+

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

+
+
+
+
+
+
+
+

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

+
+
+
+
+
+
+
+
+
+

Stubs and Transitive Dependencies

+
+

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

+
+
+
+
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...
+
+
+
+

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

+
+
+
    +
  • +

    Mark all application dependencies as optional

    +
  • +
  • +

    Create a separate artifactid for the stubs

    +
  • +
  • +

    Exclude dependencies on the consumer side

    +
  • +
+
+
+

Mark all application dependencies as optional

+
+
+

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

+
+
+

Create a separate artifactid for the stubs

+
+
+

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

+
+
+

Exclude dependencies on the consumer side

+
+
+

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

+
+
+
+

Scenarios

+
+

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

+
+
+
+
my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy
+
+
+
+

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

+
+
+
    +
  1. +

    login marked as Started pointing to…​

    +
  2. +
  3. +

    showCart marked as Step1 pointing to…​

    +
  4. +
  5. +

    logout marked as Step2 which will close the scenario.

    +
  6. +
+
+
+

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

+
+
+

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

+
+
+
+

Docker Project

+
+

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

+
+
+ + + + + +
+ + +The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones. +
+
+
+

Short intro to Maven, JARs and Binary storage

+
+

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

+
+
+

Part of the following definitions were taken from the Maven Glossary

+
+
+
    +
  • +

    Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.

    +
  • +
  • +

    Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.

    +
  • +
  • +

    JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.

    +
  • +
  • +

    GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.

    +
  • +
  • +

    Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.

    +
  • +
  • +

    Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

    +
  • +
+
+
+
+

How it works

+
+

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

+
+
+

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

+
+
+
    +
  • +

    generate the contract tests

    +
  • +
  • +

    execute the tests against the provided URL

    +
  • +
  • +

    generate the WireMock stubs

    +
  • +
  • +

    (optional - turned on by default) publish the stubs to a Artifact Manager

    +
  • +
+
+
+
Environment Variables
+
+

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

+
+
+
    +
  • +

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    +
  • +
  • +

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    +
  • +
  • +

    PROJECT_NAME - artifact id. Defaults to example

    +
  • +
  • +

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    +
  • +
  • +

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    +
  • +
  • +

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    +
  • +
  • +

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    +
  • +
+
+
+

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

+
+
+
    +
  • +

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    +
  • +
  • +

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    +
  • +
  • +

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    +
  • +
+
+
+

These environment variables are used when tests are executed:

+
+
+
    +
  • +

    APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)

    +
  • +
  • +

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    +
  • +
  • +

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    +
  • +
+
+
+
+
+

Example of usage

+
+

Let’s take a look at a simple MVC application

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

The contracts are available under /contracts folder.

+
+
+
+

Server side (nodejs)

+
+

Since we want to run tests, we could just execute:

+
+
+
+
$ npm test
+
+
+
+

however, for learning purposes, let’s split it into pieces:

+
+
+
+
# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"
+
+
+
+

What will happen is that via bash scripts:

+
+
+
    +
  • +

    infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.

    +
  • +
  • +

    due to those constraints the contracts also represent the +stateful situation

    +
    +
      +
    • +

      first request is a POST that causes data to get inserted to the database

      +
    • +
    • +

      second request is a GET that returns a list of data with 1 previously inserted element

      +
    • +
    +
    +
  • +
  • +

    the NodeJS application will be started (on port 3000)

    +
  • +
  • +

    contract tests will be generated via Docker and tests +will be executed against the running application

    +
    +
      +
    • +

      the contracts will be taken from /contracts folder.

      +
    • +
    • +

      the output of the test execution is available under +node_modules/spring-cloud-contract/output.

      +
    • +
    +
    +
  • +
  • +

    the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    +
  • +
+
+
+

To see how the client side looks like check out the Stub Runner Docker section.

+
+
+
+
+
+
+

Spring Cloud Contract Verifier Messaging

+
+
+

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

+
+
+

Integrations

+
+

You can use one of the following four integration configurations:

+
+
+
    +
  • +

    Apache Camel

    +
  • +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

+
+
+ + + + + +
+ + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here: +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+
+

Manual Integration Testing

+
+

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

+
+
+

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

+
+
+
+
@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
+
+
+
+ + + + + +
+ + +If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation. +
+
+
+
+

Publisher-Side Test Generation

+
+

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5, TestNG or Spock tests.

+
+
+

There are 3 main scenarios that we should take into consideration:

+
+
+
    +
  • +

    Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).

    +
  • +
  • +

    Scenario 2: The input message triggers an output message.

    +
  • +
  • +

    Scenario 3: The input message is consumed and there is no output message.

    +
  • +
+
+
+ + + + + +
+ + +The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms). +
+
+
+

Scenario 1: No Input Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					triggeredBy('bookReturnedTriggered()')
+				}
+				outputMessage {
+					sentTo('activemq:output')
+					body('''{ "bookName" : "foo" }''')
+					headers {
+						header('BOOK-NAME', 'foo')
+						messagingContentType(applicationJson())
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  triggeredBy: bookReturnedTriggered
+outputMessage:
+  sentTo: activemq:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+    contentType: application/json
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// when:
+\t\t\tbookReturnedTriggered();
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+\t\t\tassertThat(response.getHeader("contentType")).isNotNull();
+\t\t\tassertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					'''\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\twhen:
+\t\t\tbookReturnedTriggered()
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+\t\t\tresponse.getHeader("contentType") != null
+\t\t\tresponse.getHeader("contentType").toString() == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+'''
+
+
+
+
+

Scenario 2: Output Triggered by Input

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:input')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+				}
+				outputMessage {
+					sentTo('jms:output')
+					body([
+							bookName: 'foo'
+					])
+					headers {
+						header('BOOK-NAME', 'foo')
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:input
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+outputMessage:
+  sentTo: jms:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input");
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input")
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+"""
+
+
+
+
+

Scenario 3: No Output Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

The following JUnit test is created:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete");
+\t\t\tbookWasDeleted();
+
+\t}
+
+}
+
+"""
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete")
+\t\t\tbookWasDeleted()
+
+\t\tthen:
+\t\t\tnoExceptionThrown()
+\t}
+
+}
+"""
+
+
+
+
+
+

Consumer Stub Generation

+
+

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

+
+
+

For more information, see Stub Runner for Messaging section.

+
+
+
Maven
+
+
<dependencies>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
+	</dependency>
+
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+		<scope>test</scope>
+	</dependency>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-stream-test-support</artifactId>
+		<scope>test</scope>
+	</dependency>
+</dependencies>
+
+<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>Hoxton.BUILD-SNAPSHOT</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+
+
+

Spring Cloud Contract Stub Runner

+
+
+

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

+
+
+

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

+
+
+

Snapshot versions

+
+

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+
+
+
+
+

Publishing Stubs as JARs

+
+

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

+
+
+ + + + + +
+ + +For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. +
+
+
+
Maven
+
+
<!-- First disable the default jar setup in the properties section -->
+<!-- we don't want the verifier to do a jar for us -->
+<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+
+<!-- Next add the assembly plugin to your build -->
+<!-- we want the assembly plugin to generate the JAR -->
+<plugin>
+	<groupId>org.apache.maven.plugins</groupId>
+	<artifactId>maven-assembly-plugin</artifactId>
+	<executions>
+		<execution>
+			<id>stub</id>
+			<phase>prepare-package</phase>
+			<goals>
+				<goal>single</goal>
+			</goals>
+			<inherited>false</inherited>
+			<configuration>
+				<attach>true</attach>
+				<descriptors>
+					${basedir}/src/assembly/stub.xml
+				</descriptors>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>src/main/java</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/classes</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+

Stub Runner Core

+
+

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts.

+
+
+

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined.

+
+
+

Retrieving stubs

+
+

You can pick the following options of acquiring stubs

+
+
+
    +
  • +

    Aether based solution that downloads JARs with stubs from Artifactory / Nexus

    +
  • +
  • +

    Classpath scanning solution that searches classpath via pattern to retrieve stubs

    +
  • +
  • +

    Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    +
  • +
+
+
+

The latter example is described in the Custom Stub Runner section.

+
+
+
Stub downloading
+
+

You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options

+
+
+
    +
  • +

    StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath

    +
  • +
  • +

    StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)

    +
  • +
  • +

    StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

    +
  • +
+
+
+

Example:

+
+
+
+
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+
+
+
+
+
Classpath scanning
+
+

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example:

+
+
+
+
@AutoConfigureStubRunner(ids = {
+    "com.example:beer-api-producer:+:stubs:8095",
+    "com.example.foo:bar:1.0.0:superstubs:8096"
+})
+
+
+
+

If you’ve added the dependencies to your classpath

+
+
+
Maven
+
+
<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>beer-api-producer-restdocs</artifactId>
+    <classifier>stubs</classifier>
+    <version>0.0.1-SNAPSHOT</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+<dependency>
+    <groupId>com.example.foo</groupId>
+    <artifactId>bar</artifactId>
+    <classifier>superstubs</classifier>
+    <version>1.0.0</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
+    transitive = false
+}
+testCompile("com.example.foo:bar:1.0.0:superstubs") {
+    transitive = false
+}
+
+
+
+

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

+
+
+
    +
  • +

    /META-INF/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /contracts/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /mappings/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
+
+
+

and com.example.foo:bar

+
+
+
    +
  • +

    /META-INF/com.example.foo/bar/*/.*

    +
  • +
  • +

    /contracts/com.example.foo/bar/*/.*

    +
  • +
  • +

    /mappings/com.example.foo/bar/*/.*

    +
  • +
+
+
+ + + + + +
+ + +As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs. +
+
+
+

The producer would setup the contracts like this:

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                └── com.example
+                    └── beer-api-producer-restdocs
+                        └── nested
+                            └── contract3.groovy
+
+
+
+

To achieve proper stub packaging.

+
+
+

Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar.

+
+
+
+
└── META-INF
+    └── com.example
+        └── beer-api-producer-restdocs
+            └── 2.0.0
+                ├── contracts
+                │   └── nested
+                │       └── contract2.groovy
+                └── mappings
+                    └── mapping.json
+
+
+
+

By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts.

+
+
+
+
Configuring HTTP Server Stubs
+
+

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub.

+
+
+

Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

+
+
+
WireMockHttpServerStubConfigurer implementation
+
+
@CompileStatic
+static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+	@Override
+	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+			int httpsPort = SocketUtils.findAvailableTcpPort()
+			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+			return httpStubConfiguration
+					.httpsPort(httpsPort)
+		}
+		return httpStubConfiguration
+	}
+}
+
+
+
+

You can then reuse it via the annotation

+
+
+
+
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+
+
+
+

Whenever an https port is found, it will take precedence over the http one.

+
+
+
+
+

Running stubs

+
+
Running using main app
+
+

You can set the following options to the main class:

+
+
+
+
-c, --classifier                Suffix for the jar containing stubs (e.
+                                  g. 'stubs' if the stub jar would
+                                  have a 'stubs' classifier for stubs:
+                                  foobar-stubs ). Defaults to 'stubs'
+                                  (default: stubs)
+--maxPort, --maxp <Integer>     Maximum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  15000 (default: 15000)
+--minPort, --minp <Integer>     Minimum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  10000 (default: 10000)
+-p, --password                  Password to user when connecting to
+                                  repository
+--phost, --proxyHost            Proxy host to use for repository
+                                  requests
+--pport, --proxyPort [Integer]  Proxy port to use for repository
+                                  requests
+-r, --root                      Location of a Jar containing server
+                                  where you keep your stubs (e.g. http:
+                                  //nexus.
+                                  net/content/repositories/repository)
+-s, --stubs                     Comma separated list of Ivy
+                                  representation of jars with stubs.
+                                  Eg. groupid:artifactid1,groupid2:
+                                  artifactid2:classifier
+--sm, --stubsMode               Stubs mode to be used. Acceptable values
+                                  [CLASSPATH, LOCAL, REMOTE]
+-u, --username                  Username to user when connecting to
+                                  repository
+
+
+
+
+
HTTP Stubs
+
+

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

+
+
+

Example:

+
+
+
+
{
+    "request": {
+        "method": "GET",
+        "url": "/ping"
+    },
+    "response": {
+        "status": 200,
+        "body": "pong",
+        "headers": {
+            "Content-Type": "text/plain"
+        }
+    }
+}
+
+
+
+
+
Viewing registered mappings
+
+

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

+
+
+

You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this

+
+
+
+
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
+mappingsOutputFolder = "target/outputmappings/")
+
+
+
+

and for the JUnit approach like this:

+
+
+
+
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
+			.repoRoot("https://some_url")
+			.downloadStub("a.b.c", "loanIssuance")
+			.downloadStub("a.b.c:fraudDetectionServer")
+			.withMappingsOutputFolder("target/outputmappings")
+
+
+
+

Then if you check out the folder target/outputmappings you would see the following structure

+
+
+
+
.
+├── fraudDetectionServer_13705
+└── loanIssuance_12255
+
+
+
+

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server:

+
+
+
+
[{
+  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
+  "request" : {
+    "url" : "/name",
+    "method" : "GET"
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "fraudDetectionServer"
+  },
+  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
+},
+...
+]
+
+
+
+
+
Messaging Stubs
+
+

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

+
+
+
+
+
+

Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

+
+

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

+
+
+
    +
  • +

    download them

    +
  • +
  • +

    cache them locally

    +
  • +
  • +

    unzip them to a temporary folder

    +
  • +
  • +

    start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port

    +
  • +
  • +

    feed the WireMock server with all JSON files that are valid WireMock definitions

    +
  • +
  • +

    can also send messages (remember to pass an implementation of MessageVerifier interface)

    +
  • +
+
+
+

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information.

+
+
+

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+
+import org.springframework.cloud.contract.spec.Contract;
+
+/**
+ * Contract for finding registered stubs.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubFinder extends StubTrigger {
+
+	/**
+	 * For the given groupId and artifactId tries to find the matching URL of the running
+	 * stub.
+	 * @param groupId - might be null. In that case a search only via artifactId takes
+	 * place
+	 * @param artifactId - artifact id of the stub
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
+
+	/**
+	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
+	 * tries to find the matching URL of the running stub. You can also pass only
+	 * {@code artifactId}.
+	 * @param ivyNotation - Ivy representation of the Maven artifact
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
+
+	/**
+	 * @return all running stubs
+	 */
+	RunningStubs findAllRunningStubs();
+
+	/**
+	 * @return the list of Contracts
+	 */
+	Map<StubConfiguration, Collection<Contract>> getContracts();
+
+}
+
+
+
+

Example of usage in Spock tests:

+
+
+
+
@ClassRule
+@Shared
+StubRunnerRule rule = new StubRunnerRule()
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule")
+
+
+def 'should start WireMock servers'() {
+	expect: 'WireMocks are running'
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+		rule.findStubUrl('loanIssuance') != null
+		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+	and:
+		rule.findAllRunningStubs().isPresent('loanIssuance')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+	and: 'Stubs were registered'
+		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+}
+
+def 'should output mappings to output folder'() {
+	when:
+		def url = rule.findStubUrl('fraudDetectionServer')
+	then:
+		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
+}
+
+
+
+

Example of usage in JUnit tests:

+
+
+
+
	@Test
+	public void should_start_wiremock_servers() throws Exception {
+		// expect: 'WireMocks are running'
+		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
+		then(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isNotNull();
+		// and:
+		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs",
+				"fraudDetectionServer")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isTrue();
+		// and: 'Stubs were registered'
+		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
+				.isEqualTo("loanIssuance");
+		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
+				.isEqualTo("fraudDetectionServer");
+	}
+
+	private String httpGet(String url) throws Exception {
+		try (InputStream stream = URI.create(url).toURL().openStream()) {
+			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
+		}
+	}
+
+}
+
+
+
+

JUnit 5 Extension example:

+
+
+
+
// Visible for Junit
+@RegisterExtension
+static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
+		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule");
+
+@BeforeAll
+@AfterAll
+static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+private static String repoRoot() {
+	try {
+		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
+				.toURI().toString();
+	}
+	catch (Exception e) {
+		return "";
+	}
+}
+
+
+
+

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

+
+
+ + + + + +
+ + +To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown. +
+
+
+

Maven settings

+
+

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

+
+
+
+

Providing fixed ports

+
+

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

+
+
+
+

Fluent API

+
+

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.withPort(12345).downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

You can see that for this example the following test is valid:

+
+
+
+
then(rule.findStubUrl("loanIssuance"))
+		.isEqualTo(URI.create("http://localhost:12345").toURL());
+then(rule.findStubUrl("fraudDetectionServer"))
+		.isEqualTo(URI.create("http://localhost:12346").toURL());
+
+
+
+
+

Stub Runner with Spring

+
+

Sets up Spring configuration of the Stub Runner project.

+
+
+

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs.

+
+
+

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
+		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
+		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
+@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+@ActiveProfiles("test")
+class StubRunnerConfigurationSpec extends Specification {
+
+	@Autowired
+	StubFinder stubFinder
+	@Autowired
+	Environment environment
+	@StubRunnerPort("fraudDetectionServer")
+	int fraudDetectionServerPort
+	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+	int fraudDetectionServerPortWithGroupId
+	@Value('${foo}')
+	Integer foo
+
+	@BeforeClass
+	@AfterClass
+	void setupProps() {
+		System.clearProperty("stubrunner.repository.root")
+		System.clearProperty("stubrunner.classifier")
+	}
+
+	def 'should start WireMock servers'() {
+		expect: 'WireMocks are running'
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+		and:
+			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+		and: 'Stubs were registered'
+			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+		and: 'Fraud Detection is an HTTPS endpoint'
+			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
+	}
+
+	def 'should throw an exception when stub is not found'() {
+		when:
+			stubFinder.findStubUrl('nonExistingService')
+		then:
+			thrown(StubNotFoundException)
+		when:
+			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
+		then:
+			thrown(StubNotFoundException)
+	}
+
+	def 'should register started servers as environment variables'() {
+		expect:
+			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
+			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
+	}
+
+	def 'should be able to interpolate a running stub in the passed test property'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			environment.getProperty("foo", Integer) == fraudPort
+			environment.getProperty("fooWithGroup", Integer) == fraudPort
+			foo == fraudPort
+	}
+
+	@Issue("#573")
+	def 'should be able to retrieve the port of a running stub via an annotation'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			fraudDetectionServerPort == fraudPort
+			fraudDetectionServerPortWithGroupId == fraudPort
+	}
+
+	def 'should dump all mappings to a file'() {
+		when:
+			def url = stubFinder.findStubUrl("fraudDetectionServer")
+		then:
+			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
+	}
+
+	@Configuration
+	@EnableAutoConfiguration
+	static class Config {}
+
+	@CompileStatic
+	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+		@Override
+		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+				int httpsPort = SocketUtils.findAvailableTcpPort()
+				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+				return httpStubConfiguration
+						.httpsPort(httpsPort)
+			}
+			return httpStubConfiguration
+		}
+	}
+}
+
+
+
+

for the following configuration file:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids:
+    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
+    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
+    - org.springframework.cloud.contract.verifier.stubs:bootService
+  stubs-mode: remote
+
+
+
+

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation.

+
+
+
+
@AutoConfigureStubRunner(
+		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
+				"org.springframework.cloud.contract.verifier.stubs:bootService"],
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		repositoryRoot = "classpath:m2repo/repository/")
+
+
+
+

Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar.

+
+
+
    +
  • +

    stubrunner.runningstubs.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.bar.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.bar.port

    +
  • +
+
+
+

Which you can reference in your code.

+
+
+

You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar.

+
+
+
+
@StubRunnerPort("foo")
+int fooPort;
+@StubRunnerPort("com.example:bar")
+int barPort;
+
+
+
+
+
+

Stub Runner Spring Cloud

+
+

Stub Runner can integrate with Spring Cloud.

+
+
+

For real life examples you can check the

+
+ +
+

Stubbing Service Discovery

+
+

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

+
+
+
    +
  • +

    DiscoveryClient

    +
  • +
  • +

    Ribbon ServerList

    +
  • +
+
+
+

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

+
+
+

For example this test will pass

+
+
+
+
def 'should make service discovery work'() {
+	expect: 'WireMocks are running'
+		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+	and: 'Stubs can be reached via load service discovery'
+		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
+		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
+}
+
+
+
+

for the following configuration file

+
+
+
+
stubrunner:
+  idsToServiceIds:
+    ivyNotation: someValueInsideYourCode
+    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer
+
+
+
+
Test profiles and service discovery
+
+

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features.

+
+
+

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka)

+
+
+
+
    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
+    static {
+        System.setProperty("eureka.client.enabled", "false");
+        System.setProperty("spring.cloud.config.failFast", "false");
+    }
+
+
+
+
+
+

Additional Configuration

+
+

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

+
+
+ + + + + +
+ + +By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones. +
+
+
+

The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables

+
+
+
    +
  • +

    maven.repo.local - path to the custom maven local repository location

    +
  • +
  • +

    org.apache.maven.user-settings - path to custom maven user settings location

    +
  • +
  • +

    org.apache.maven.global-settings - path to maven global settings location

    +
  • +
+
+
+
+
+

Stub Runner Boot Application

+
+

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers.

+
+
+

One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information.

+
+
+

How to use it?

+
+
Stub Runner Server
+
+

Just add the

+
+
+
+
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
+
+
+
+

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

+
+
+

For the properties check the Stub Runner Spring section.

+
+
+
+
Stub Runner Server Fat Jar
+
+

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

+
+
+
+
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
+
+
+
+
+
Spring Cloud CLI
+
+

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner.

+
+
+

In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally)

+
+
+
stubrunner.yml
+
+
stubrunner:
+  stubsMode: LOCAL
+  ids:
+    - com.example:beer-api-producer:+:9876
+
+
+
+

and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750.

+
+
+
+
+

Endpoints

+
+
HTTP
+
+
    +
  • +

    GET /stubs - returns a list of all running stubs in ivy:integer notation

    +
  • +
  • +

    GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
Messaging
+
+

For Messaging

+
+
+
    +
  • +

    GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation

    +
  • +
  • +

    POST /triggers/{label} - executes a trigger with label

    +
  • +
  • +

    POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
+

Example

+
+
+
@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
+@ActiveProfiles("test")
+class StubRunnerBootSpec extends Specification {
+
+	@Autowired
+	StubRunning stubRunning
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
+				new TriggerController(stubRunning))
+	}
+
+	def 'should return a list of running stub servers in "full ivy:port" notation'() {
+		when:
+			String response = RestAssuredMockMvc.get('/stubs').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
+	}
+
+	def 'should return a port on which a [#stubId] stub is running'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
+		then:
+			response.statusCode == 200
+			Integer.valueOf(response.body.asString()) > 0
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService',
+					   'bootService']
+	}
+
+	def 'should return 404 when missing stub was called'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
+		then:
+			response.statusCode == 404
+	}
+
+	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
+		when:
+			String response = RestAssuredMockMvc.get('/triggers').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
+	}
+
+	def 'should trigger a messaging label'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger('delete_book')
+	}
+
+	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger(stubId, 'delete_book')
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
+	}
+
+	def 'should throw exception when trigger is missing'() {
+		when:
+			RestAssuredMockMvc.post("/triggers/missing_label")
+		then:
+			Exception e = thrown(Exception)
+			e.message.contains("Exception occurred while trying to return [missing_label] label.")
+			e.message.contains("Available labels are")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
+	}
+
+}
+
+
+
+
+

Stub Runner Boot with Service Discovery

+
+

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios.

+
+
+

The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running.

+
+
+
+
@SpringBootApplication
+@EnableStubRunnerServer
+@EnableEurekaClient
+@AutoConfigureStubRunner
+public class StubRunnerBootEurekaExample {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
+	}
+
+}
+
+
+
+

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

+
+
+

Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties

+
+
+
+
* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
+* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
+* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
+* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
+* cloud.contract.verifier.stubs:bootService (3)
+* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
+* someNameThatShouldMapFraudDetectionServer (4)
+*
+* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
+* behaviour where the discovery service is stubbed. That's why the stub registration will
+* be picked (3) - we provide a list of stubs to download (4) - we provide a list of
+
+
+
+

That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot.

+
+
+
+
+

Stubs Per Consumer

+
+

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

+
+
+ + + + + +
+ + +This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it. +
+
+
+

Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer.

+
+
+

Consumer foo-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       foo: "foo"
+    }
+}
+
+
+
+

Consumer bar-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       bar: "bar"
+    }
+}
+
+
+
+

You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature.

+
+
+

On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered.

+
+
+

On the foo producer side the contracts would look like this

+
+
+
+
.
+└── contracts
+    ├── bar-consumer
+    │   ├── bookReturnedForBar.groovy
+    │   └── shouldCallBar.groovy
+    └── foo-consumer
+        ├── bookReturnedForFoo.groovy
+        └── shouldCallFoo.groovy
+
+
+
+

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

Or set the consumer name explicitly

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		consumerName = "foo-consumer",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

You can check out issue 224 for more +information about the reasons behind this change.

+
+
+
+

Common

+
+

This section briefly describes common properties, including:

+
+ +
+

Common Properties for JUnit and Spring

+
+

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

+
+
+

Stub Runner Stubs IDs

+
+

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

+
+
+
+
groupId:artifactId:version:classifier:port
+
+
+
+

Note that version, classifier and port are optional.

+
+
+
    +
  • +

    If you do not provide the port, a random one will be picked.

    +
  • +
  • +

    If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).

    +
  • +
  • +

    If you do not provide the version, then the + will be passed and the latest one is +downloaded.

    +
  • +
+
+
+

port means the port of the WireMock server.

+
+
+ + + + + +
+ + +Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here. +
+
+
+
+
+

Stub Runner Docker

+
+

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

+
+
+

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here Docker Project.

+
+
+

How to use it

+
+

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

+
+
+
+

Example of client side usage in a non JVM project

+
+

We’d like to use the stubs created in this Server side (nodejs) step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

Let’s run the Stub Runner Boot application with the stubs.

+
+
+
+
# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
+
+
+
+

What’s happening is that

+
+
+
    +
  • +

    a standalone Stub Runner application got started

    +
  • +
  • +

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    +
  • +
  • +

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    +
  • +
  • +

    after a while Stub Runner will be running on port 8083

    +
  • +
  • +

    and the stubs will be running at port 9876

    +
  • +
+
+
+

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

+
+
+
+
# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
+
+
+
+ + + + + +
+ + +If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" +
+
+
+
+
+
+
+

Stub Runner for Messaging

+
+
+

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

+
+
+
    +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Apache Camel

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

It also provides entry points to integrate with any other solution on the market.

+
+
+ + + + + +
+ + +If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP. +
+
+
+

Stub triggering

+
+

To trigger a message, use the StubTrigger interface:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Contract for triggering stub messages.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubTrigger {
+
+	/**
+	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
+	 * You can use only {@code artifactId} too.
+	 *
+	 * Feature related to messaging.
+	 * @param ivyNotation ivy notation of a stub
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String ivyNotation, String labelName);
+
+	/**
+	 * Triggers an event by a given label.
+	 *
+	 * Feature related to messaging.
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String labelName);
+
+	/**
+	 * Triggers all possible events.
+	 *
+	 * Feature related to messaging.
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger();
+
+	/**
+	 * Feature related to messaging.
+	 * @return a mapping of ivy notation of a dependency to all the labels it has.
+	 */
+	Map<String, Collection<String>> labels();
+
+}
+
+
+
+

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

+
+
+

StubTrigger gives you the following options to trigger a message:

+
+ +
+

Trigger by Label

+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+
+

Trigger by Group and Artifact Ids

+
+
+
stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')
+
+
+
+
+

Trigger by Artifact Ids

+
+
+
stubFinder.trigger('streamService', 'return_book_1')
+
+
+
+
+

Trigger All Messages

+
+
+
stubFinder.trigger()
+
+
+
+
+
+

Stub Runner Camel

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes.

+
+
+

Adding it to the project

+
+

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

Disabling the functionality

+
+

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

+
+
+
+

Examples

+
+
Stubs structure
+
+

Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application.

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── camelService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── camelService-0.0.1-SNAPSHOT.pom
+                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

And the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Let’s consider the following contracts (let' number it with 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and number 2

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('jms:input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
+
Scenario 1 (no input message)
+
+

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])
+
+
+
+
+
+
+

Stub Runner Integration

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes.

+
+
+

Adding the Runner to the Project

+
+

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

Disabling the functionality

+
+

If you need to disable this functionality, set the +stubrunner.integration.enabled=false property.

+
+
+

Assume that you have the following Maven repository with deployed stubs for the +integrationService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── integrationService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
+                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and the following Spring Integration Route:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			 xmlns:beans="http://www.springframework.org/schema/beans"
+			 xmlns="http://www.springframework.org/schema/integration"
+			 xsi:schemaLocation="http://www.springframework.org/schema/beans
+			https://www.springframework.org/schema/beans/spring-beans.xsd
+			http://www.springframework.org/schema/integration
+			http://www.springframework.org/schema/integration/spring-integration.xsd">
+
+
+	<!-- REQUIRED FOR TESTING -->
+	<bridge input-channel="output"
+			output-channel="outputTest"/>
+
+	<channel id="outputTest">
+		<queue/>
+	</channel>
+
+</beans:beans>
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message would pass the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the input destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

Stub Runner Stream

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes.

+
+
+ + + + + +
+ + +If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support. +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+

Adding the Runner to the Project

+
+

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

Disabling the functionality

+
+

If you need to disable this functionality, set the stubrunner.stream.enabled=false +property.

+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +streamService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── streamService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── streamService-0.0.1-SNAPSHOT.pom
+                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input { triggeredBy('bookReturnedTriggered()') }
+	outputMessage {
+		sentTo('returnBook')
+		body('''{ "bookName" : "foo" }''')
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('bookStorage')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders { header('sample', 'header') }
+	}
+	outputMessage {
+		sentTo('returnBook')
+		body([
+				bookName: 'foo'
+		])
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner.repositoryRoot: classpath:m2repo/repository/
+stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
+stubrunner.stubs-mode: remote
+spring:
+  cloud:
+    stream:
+      bindings:
+        output:
+          destination: returnBook
+        input:
+          destination: bookStorage
+
+server:
+  port: 0
+
+debug: true
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to a channel whose destination is +returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the bookStorage +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')
+
+
+
+

To listen to the output of the message sent to returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

Stub Runner Spring AMQP

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes.

+
+
+

The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application.

+
+
+

On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context.

+
+
+

As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners.

+
+
+

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header.

+
+
+

Adding the Runner to the Project

+
+

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner.

+
+
+ + + + + +
+ + +If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties. +
+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application.

+
+
+
+
└── .m2
+    └── repository
+        └── com
+            └── example
+                └── spring-cloud-contract-amqp-test
+                    ├── 0.4.0-SNAPSHOT
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
+                    │   └── maven-metadata-local.xml
+                    └── maven-metadata-local.xml
+
+
+
+

Further assume that the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── contracts
+    └── shouldProduceValidPersonData.groovy
+
+
+
+

Consider the following contract:

+
+
+
+
Contract.make {
+	// Human readable description
+	description 'Should produce valid person data'
+	// Label by means of which the output message can be triggered
+	label 'contract-test.person.created.event'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('createPerson()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo 'contract-test.exchange'
+		headers {
+			header('contentType': 'application/json')
+			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
+		}
+		// the body of the output message
+		body([
+				id  : $(consumer(9), producer(regex("[0-9]+"))),
+				name: "me"
+		])
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
+  stubs-mode: remote
+  amqp:
+    enabled: true
+server:
+  port: 0
+
+
+
+
Triggering the message
+
+

To trigger a message using the contract above, use the StubTrigger interface as +follows:

+
+
+
+
stubTrigger.trigger("contract-test.person.created.event")
+
+
+
+

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange.

+
+
+
+
@Bean
+public Binding binding() {
+	return BindingBuilder.bind(new Queue("test.queue"))
+			.to(new DirectExchange("contract-test.exchange")).with("#");
+}
+
+
+
+

The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message.

+
+
+
+
@Bean
+public SimpleMessageListenerContainer simpleMessageListenerContainer(
+		ConnectionFactory connectionFactory,
+		MessageListenerAdapter listenerAdapter) {
+	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
+	container.setConnectionFactory(connectionFactory);
+	container.setQueueNames("test.queue");
+	container.setMessageListener(listenerAdapter);
+
+	return container;
+}
+
+
+
+

Also, the following annotated listener matches and is invoked:

+
+
+
+
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
+		exchange = @Exchange(value = "contract-test.exchange",
+				ignoreDeclarationExceptions = "true")))
+public void handlePerson(Person person) {
+	this.person = person;
+}
+
+
+
+ + + + + +
+ + +The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer. +
+
+
+
+
Spring AMQP Test Configuration
+
+

In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory.

+
+
+

To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false

+
+
+
+
stubrunner:
+  amqp:
+    mockConnection: false
+
+
+
+
+
+
+
+
+

Contract DSL

+
+
+

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

+
+
+

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

+
+
+ + + + + +
+ + +Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }. +
+
+
+ + + + + +
+ + +Spring Cloud Contract supports defining multiple contracts in a single file. +
+
+
+

The following is a complete example of a Groovy contract definition:

+
+
+
+
+
+
+
+

The following is a complete example of a YAML contract definition:

+
+
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+ + + + + +
+ + +You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert +
+
+
+

Limitations

+
+ + + + + +
+ + +Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. +
+
+
+ + + + + +
+ + +The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration. +
+
+
+ + + + + +
+ + +Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation. +
+
+
+
+

Common Top-Level elements

+
+

The following sections describe the most common top-level elements:

+
+ +
+

Description

+
+

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

+
+
+
Groovy DSL
+
+
			org.springframework.cloud.contract.spec.Contract.make {
+				description('''
+given:
+	An input
+when:
+	Sth happens
+then:
+	Output
+''')
+			}
+
+
+
+
YAML
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+
+

Name

+
+

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

+
+
+ + + + + +
+ + +You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. +
+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	name("some_special_name")
+}
+
+
+
+
YAML
+
+
name: some name
+
+
+
+
+

Ignoring Contracts

+
+

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	ignored()
+}
+
+
+
+
YAML
+
+
ignored: true
+
+
+
+
+

Passing Values from Files

+
+

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json
+
+
+
+

Further assume that your contract is as follows:

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		method('PUT')
+		headers {
+			contentType(applicationJson())
+		}
+		body(file("request.json"))
+		url("/1")
+	}
+	response {
+		status OK()
+		body(file("response.json"))
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /foo
+  bodyFromFile: request.json
+response:
+  status: 200
+  bodyFromFile: response.json
+
+
+
+

Further assume that the JSON files is as follows:

+
+
+

request.json

+
+
+
+
{
+  "status": "REQUEST"
+}
+
+
+
+

response.json

+
+
+
+
{
+  "status": "RESPONSE"
+}
+
+
+
+

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

+
+
+

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		url("/1")
+		method(PUT())
+		headers {
+			contentType(applicationOctetStream())
+		}
+		body(fileAsBytes("request.pdf"))
+	}
+	response {
+		status 200
+		body(fileAsBytes("response.pdf"))
+		headers {
+			contentType(applicationOctetStream())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  url: /1
+  method: PUT
+  headers:
+    Content-Type: application/octet-stream
+  bodyFromFileAsBytes: request.pdf
+response:
+  status: 200
+  bodyFromFileAsBytes: response.pdf
+  headers:
+    Content-Type: application/octet-stream
+
+
+
+ + + + + +
+ + +You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +
+
+
+
+

HTTP Top-Level Elements

+
+

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	// Definition of HTTP request part of the contract
+	// (this can be a valid request or invalid depending
+	// on type of contract being specified).
+	request {
+		method GET()
+		url "/foo"
+		//...
+	}
+
+	// Definition of HTTP response part of the contract
+	// (a service implementing this contract should respond
+	// with following response after receiving request
+	// specified in "request" part above).
+	response {
+		status 200
+		//...
+	}
+
+	// Contract priority, which can be used for overriding
+	// contracts (1 is highest). Priority is optional.
+	priority 1
+}
+
+
+
+
YAML
+
+
priority: 8
+request:
+...
+response:
+...
+
+
+
+ + + + + +
+ + +If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10. +
+
+
+
+
+

Request

+
+

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		// HTTP request method (GET/POST/PUT/DELETE).
+		method 'GET'
+
+		// Path component of request URL is specified as follows.
+		urlPath('/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
method: PUT
+url: /foo
+
+
+
+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+
+		// Specifying `url` and `urlPath` in one contract is illegal.
+		url('http://localhost:8888/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  urlPath: /foo
+
+
+
+

request may contain query parameters.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+
+		urlPath('/users') {
+
+			// Each parameter is specified in form
+			// `'paramName' : paramValue` where parameter value
+			// may be a simple literal or one of matcher functions,
+			// all of which are used in this example.
+			queryParameters {
+
+				// If a simple literal is used as value
+				// default matcher function is used (equalTo)
+				parameter 'limit': 100
+
+				// `equalTo` function simply compares passed value
+				// using identity operator (==).
+				parameter 'filter': equalTo("email")
+
+				// `containing` function matches strings
+				// that contains passed substring.
+				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
+
+				// `matching` function tests parameter
+				// against passed regular expression.
+				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
+
+				// `notMatching` functions tests if parameter
+				// does not match passed regular expression.
+				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
+			}
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+  queryParameters:
+    a: b
+    b: c
+  headers:
+    foo: bar
+    fooReq: baz
+  cookies:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  fixedDelayMilliseconds: 1000
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+    cookies:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        predefined:
+
+
+
+

request may contain additional request headers, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each header is added in form `'Header-Name' : 'Header-Value'`.
+		// there are also some helper methods
+		headers {
+			header 'key': 'value'
+			contentType(applicationJson())
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+headers:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain additional request cookies, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
+		// there are also some helper methods
+		cookies {
+			cookie 'key': 'value'
+			cookie('another_key', 'another_value')
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+cookies:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain a request body:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Currently only JSON format of request body is supported.
+		// Format will be determined from a header or body's content.
+		body '''{ "login" : "john", "name": "John The Contract" }'''
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+body:
+  foo: bar
+
+
+
+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  url: /multipart
+  headers:
+    Content-Type: multipart/form-data;boundary=AaB03x
+  multipart:
+    params:
+      # key (parameter name), value (parameter value) pair
+      formParameter: '"formParameterValue"'
+      someBooleanParameter: true
+    named:
+      - paramName: file
+        fileName: filename.csv
+        fileContent: file content
+  matchers:
+    multipart:
+      params:
+        - key: formParameter
+          regex: ".+"
+        - key: someBooleanParameter
+          predefined: any_boolean
+      named:
+        - paramName: file
+          fileName:
+            predefined: non_empty
+          fileContent:
+            predefined: non_empty
+response:
+  status: 200
+
+
+
+

In the preceding example, we define parameters in either of two ways:

+
+
+
Groovy DSL
+
    +
  • +

    Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).

    +
  • +
  • +

    By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

    +
  • +
+
+
+
YAML
+
    +
  • +

    The multipart parameters are set via multipart.params section

    +
  • +
  • +

    The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields

    +
  • +
  • +

    The dynamic bits can be set via the matchers.multipart section

    +
    +
      +
    • +

      for parameters use the params section that can accept +regex or a predefined regular expression

      +
    • +
    • +

      for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

      +
    • +
    +
    +
  • +
+
+
+

From this contract, the generated test is as follows:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+

The WireMock stub is as follows:

+
+
+
+
			'''
+{
+  "request" : {
+	"url" : "/multipart",
+	"method" : "PUT",
+	"headers" : {
+	  "Content-Type" : {
+		"matches" : "multipart/form-data;boundary=AaB03x.*"
+	  }
+	},
+	"bodyPatterns" : [ {
+		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
+  		}, {
+    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
+  		}, {
+	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
+	} ]
+  },
+  "response" : {
+	"status" : 200,
+	"transformers" : [ "response-template", "foo-transformer" ]
+  }
+}
+	'''
+
+
+
+
+

Response

+
+

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+	}
+	response {
+		// Status code sent by the server
+		// in response to request specified above.
+		status OK()
+	}
+}
+
+
+
+
YAML
+
+
response:
+...
+status: 200
+
+
+
+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

+
+
+ + + + + +
+ + +Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400. +
+
+
+
+

Dynamic properties

+
+

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

+
+
+

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

+
+
+ + + + + +
+ + +Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information. +
+
+
+

For YAML you can only use the matchers section.

+
+
+

Dynamic properties inside the body

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

+
+
+
+
value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

The following example shows how to set dynamic properties with $():

+
+
+
+
$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

+
+
+
+

Regular expressions

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

+
+
+

Make sure that regex matches a whole region of a sequence as internally a call to +Pattern.matches() +is called. For instance, abc pattern doesn’t match aabc string but .abc does. +There are several additional known limitations as well.

+
+
+

The following example shows how to use regular expressions to write a request:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method('GET')
+		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
+	}
+	response {
+		status OK()
+		body(
+				id: $(anyNumber()),
+				surname: $(
+						consumer('Kowalsky'),
+						producer(regex('[a-zA-Z]+'))
+				),
+				name: 'Jan',
+				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
+				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
+						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
+				)
+		)
+		headers {
+			header 'Content-Type': 'text/plain'
+		}
+	}
+}
+
+
+
+

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url value(consumer(regex('/foo/[0-9]{5}')))
+		body([
+				requestElement: $(consumer(regex('[0-9]{5}')))
+		])
+		headers {
+			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
+		}
+	}
+	response {
+		status OK()
+		body([
+				responseElement: $(producer(regex('[0-9]{7}')))
+		])
+		headers {
+			contentType("application/vnd.fraud.v1+json")
+		}
+	}
+}
+
+
+
+

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

+
+
+

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

+
+
+
+
protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
+
+protected static final Pattern ALPHA_NUMERIC = Pattern.compile("[a-zA-Z0-9]+");
+
+protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile("[\\p{L}]*");
+
+protected static final Pattern NUMBER = Pattern.compile("-?(\\d*\\.\\d+|\\d+)");
+
+protected static final Pattern INTEGER = Pattern.compile("-?(\\d+)");
+
+protected static final Pattern POSITIVE_INT = Pattern.compile("([1-9]\\d*)");
+
+protected static final Pattern DOUBLE = Pattern.compile("-?(\\d*\\.\\d+)");
+
+protected static final Pattern HEX = Pattern.compile("[a-fA-F0-9]+");
+
+protected static final Pattern IP_ADDRESS = Pattern.compile(
+		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
+
+protected static final Pattern HOSTNAME_PATTERN = Pattern
+		.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
+
+protected static final Pattern EMAIL = Pattern
+		.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
+
+protected static final Pattern URL = UrlHelper.URL;
+
+protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
+
+protected static final Pattern UUID = Pattern
+		.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
+
+protected static final Pattern ANY_DATE = Pattern
+		.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+
+protected static final Pattern ANY_DATE_TIME = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern ANY_TIME = Pattern
+		.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
+
+protected static final Pattern NON_BLANK = Pattern.compile("^\\s*\\S[\\S\\s]*");
+
+protected static final Pattern ISO8601_WITH_OFFSET = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d{3})?(Z|[+-][01]\\d:[0-5]\\d)");
+
+protected static Pattern anyOf(String... values) {
+	return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$')
+			.collect(Collectors.joining("|")));
+}
+
+public static String multipartParam(Object name, Object value) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"\r\n(Content-Type: .*\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ value + "\r\n--\\1.*";
+}
+
+public static String multipartFile(Object name, Object filename, Object content,
+		Object contentType) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
+			+ toContentType(contentType)
+			+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ content + "\r\n--\\1.*";
+}
+
+private static String toContentType(Object contentType) {
+	if (contentType == null) {
+		return ".*";
+	}
+	if (contentType instanceof RegexProperty) {
+		return ((RegexProperty) contentType).pattern();
+	}
+	return contentType.toString();
+}
+
+public RegexProperty onlyAlphaUnicode() {
+	return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
+}
+
+public RegexProperty alphaNumeric() {
+	return new RegexProperty(ALPHA_NUMERIC).asString();
+}
+
+public RegexProperty number() {
+	return new RegexProperty(NUMBER).asDouble();
+}
+
+public RegexProperty positiveInt() {
+	return new RegexProperty(POSITIVE_INT).asInteger();
+}
+
+public RegexProperty anyBoolean() {
+	return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
+}
+
+public RegexProperty anInteger() {
+	return new RegexProperty(INTEGER).asInteger();
+}
+
+public RegexProperty aDouble() {
+	return new RegexProperty(DOUBLE).asDouble();
+}
+
+public RegexProperty ipAddress() {
+	return new RegexProperty(IP_ADDRESS).asString();
+}
+
+public RegexProperty hostname() {
+	return new RegexProperty(HOSTNAME_PATTERN).asString();
+}
+
+public RegexProperty email() {
+	return new RegexProperty(EMAIL).asString();
+}
+
+public RegexProperty url() {
+	return new RegexProperty(URL).asString();
+}
+
+public RegexProperty httpsUrl() {
+	return new RegexProperty(HTTPS_URL).asString();
+}
+
+public RegexProperty uuid() {
+	return new RegexProperty(UUID).asString();
+}
+
+public RegexProperty isoDate() {
+	return new RegexProperty(ANY_DATE).asString();
+}
+
+public RegexProperty isoDateTime() {
+	return new RegexProperty(ANY_DATE_TIME).asString();
+}
+
+public RegexProperty isoTime() {
+	return new RegexProperty(ANY_TIME).asString();
+}
+
+
+
+

In your contract, you can use it as shown in the following example:

+
+
+
+
Contract dslWithOptionalsInString = Contract.make {
+	priority 1
+	request {
+		method POST()
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123"))),
+				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
+		)
+	}
+}
+
+
+
+

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

+
+
+
+
+
+
+
+

and this is an example of how you can reference those methods:

+
+
+
+
Contract contractDsl = Contract.make {
+	name "foo"
+	label 'trigger_event'
+	input {
+		triggeredBy('toString()')
+	}
+	outputMessage {
+		sentTo 'topic.rateablequote'
+		body([
+				alpha            : $(anyAlphaUnicode()),
+				number           : $(anyNumber()),
+				anInteger        : $(anyInteger()),
+				positiveInt      : $(anyPositiveInt()),
+				aDouble          : $(anyDouble()),
+				aBoolean         : $(aBoolean()),
+				ip               : $(anyIpAddress()),
+				hostname         : $(anyHostname()),
+				email            : $(anyEmail()),
+				url              : $(anyUrl()),
+				httpsUrl         : $(anyHttpsUrl()),
+				uuid             : $(anyUuid()),
+				date             : $(anyDate()),
+				dateTime         : $(anyDateTime()),
+				time             : $(anyTime()),
+				iso8601WithOffset: $(anyIso8601WithOffset()),
+				nonBlankString   : $(anyNonBlankString()),
+				nonEmptyString   : $(anyNonEmptyString()),
+				anyOf            : $(anyOf('foo', 'bar'))
+		])
+	}
+}
+
+
+
+
Limitations
+
+ + + + + +
+ + +Due to certain limitations of Xeger library that generates string out of +regex, do not use $ and ^ signs in your regex if you rely on automatic +generation. Issue 899 +
+
+
+ + + + + +
+ + +Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). +It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. +Issue 900 +
+
+
+
+
+

Passing Optional Parameters

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

+
+
+
    +
  • +

    STUB side of the Request

    +
  • +
  • +

    TEST side of the Response

    +
  • +
+
+
+

The following example shows how to provide optional parameters:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	priority 1
+	name "optionals"
+	request {
+		method 'POST'
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123")))
+		)
+	}
+}
+
+
+
+

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

+
+
+

If you use Spock for, the following test would be generated from the previous example:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
+import io.restassured.response.ResponseOptions
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+
+\tdef validate_optionals() throws Exception {
+\t\tgiven:
+\t\t\tMockMvcRequestSpecification request = given()
+\t\t\t\t\t.header("Content-Type", "application/json")
+\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
+
+\t\twhen:
+\t\t\tResponseOptions response = given().spec(request)
+\t\t\t\t\t.post("/users/password")
+
+\t\tthen:
+\t\t\tresponse.statusCode() == 404
+\t\t\tresponse.header("Content-Type") == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
+\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
+\t}
+
+}
+"""
+
+
+
+

The following stub would also be generated:

+
+
+
+
					'''
+{
+  "request" : {
+	"url" : "/users/password",
+	"method" : "POST",
+	"bodyPatterns" : [ {
+	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
+	}, {
+	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
+	} ],
+	"headers" : {
+	  "Content-Type" : {
+		"equalTo" : "application/json"
+	  }
+	}
+  },
+  "response" : {
+	"status" : 404,
+	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
+	"headers" : {
+	  "Content-Type" : "application/json"
+	}
+  },
+  "priority" : 1
+}
+'''
+
+
+
+
+

Executing Custom Methods on the Server Side

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

+
+
+
+
+
+
+
+

The following code shows the base class portion of the test case:

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+ + + + + +
+ + +You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need. +
+
+
+

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

+
+
+
    +
  • +

    String: If you point to a String value in the JSON.

    +
  • +
  • +

    JSONArray: If you point to a List in the JSON.

    +
  • +
  • +

    Map: If you point to a Map in the JSON.

    +
  • +
  • +

    Number: If you point to Integer, Double etc. in the JSON.

    +
  • +
  • +

    Boolean: If you point to a Boolean in the JSON.

    +
  • +
+
+
+

In the request part of the contract, you can specify that the body should be taken from +a method.

+
+
+ + + + + +
+ + +You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it. +
+
+
+

The following example shows how to read an object from JSON:

+
+
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		url '/something'
+		body(
+				$(c('foo'), p(execute('hashCode()')))
+		)
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+
+

Referencing the Request from the Response

+
+

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

+
+
+

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

+
+
+
    +
  • +

    fromRequest().url(): Returns the request URL and query parameters.

    +
  • +
  • +

    fromRequest().query(String key): Returns the first query parameter with a given name.

    +
  • +
  • +

    fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.

    +
  • +
  • +

    fromRequest().path(): Returns the full path.

    +
  • +
  • +

    fromRequest().path(int index): Returns the nth path element.

    +
  • +
  • +

    fromRequest().header(String key): Returns the first header with a given name.

    +
  • +
  • +

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    +
  • +
  • +

    fromRequest().body(): Returns the full request body.

    +
  • +
  • +

    fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

    +
  • +
+
+
+

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

+
+
+
    +
  • +

    {{{ request.url }}}: Returns the request URL and query parameters.

    +
  • +
  • +

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    +
  • +
  • +

    {{{ request.path }}}: Returns the full path.

    +
  • +
  • +

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}

    +
  • +
  • +

    {{{ request.headers.key }}}: Returns the first header with a given name.

    +
  • +
  • +

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    +
  • +
  • +

    {{{ request.body }}}: Returns the full request body.

    +
  • +
  • +

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    +
  • +
+
+
+

Consider the following contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /api/v1/xxxx
+  queryParameters:
+    foo:
+      - bar
+      - bar2
+  headers:
+    Authorization:
+      - secret
+      - secret2
+  body:
+    foo: bar
+    baz: 5
+response:
+  status: 200
+  headers:
+    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
+  body:
+    url: "{{{ request.url }}}"
+    path: "{{{ request.path }}}"
+    pathIndex: "{{{ request.path.1 }}}"
+    param: "{{{ request.query.foo }}}"
+    paramIndex: "{{{ request.query.foo.1 }}}"
+    authorization: "{{{ request.headers.Authorization.0 }}}"
+    authorization2: "{{{ request.headers.Authorization.1 }}"
+    fullBody: "{{{ request.body }}}"
+    responseFoo: "{{{ jsonpath this '$.foo' }}}"
+    responseBaz: "{{{ jsonpath this '$.baz' }}}"
+    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"
+
+
+
+

Running a JUnit test generation leads to a test that resembles the following example:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
+
+
+
+

As you can see, elements from the request have been properly referenced in the response.

+
+
+

The generated WireMock stub should resemble the following example:

+
+
+
+
{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+
+
+
+

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

+
+
+
+
{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
+
+
+
+ + + + + +
+ + +This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions: +
+
+
+
    +
  • +

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    +
  • +
  • +

    jsonpath: For a given parameter, find an object in the request body.

    +
  • +
+
+
+
+

Registering Your Own WireMock Extension

+
+

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

+
+
+
+
org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
+org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
+org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter
+
+
+
+

The following is an example of a custom extension:

+
+
+
TestWireMockExtensions.groovy
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.contract.verifier.dsl.wiremock
+
+import com.github.tomakehurst.wiremock.extension.Extension
+
+/**
+ * Extension that registers the default transformer and the custom one
+ */
+class TestWireMockExtensions implements WireMockExtensions {
+	@Override
+	List<Extension> extensions() {
+		return [
+				new DefaultResponseTransformer(),
+				new CustomExtension()
+		]
+	}
+}
+
+class CustomExtension implements Extension {
+
+	@Override
+	String getName() {
+		return "foo-transformer"
+	}
+}
+
+
+
+ + + + + +
+ + +Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it. +
+
+
+
+

Dynamic Properties in the Matchers Sections

+
+

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

+
+
+

You can use the bodyMatchers section for two reasons:

+
+
+
    +
  • +

    Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.

    +
  • +
  • +

    Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

    +
  • +
+
+
+

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

+
+
+
Groovy DSL
+
    +
  • +

    For the stubs(in tests on the Consumer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      +
    • +
    • +

      byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.

      +
    • +
    +
    +
  • +
  • +

    For the verification(in generated tests on the Producer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.

      +
    • +
    • +

      byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.

      +
    • +
    • +

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      +
    • +
    • +

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      +
      +
        +
      • +

        String: If you point to a String value.

        +
      • +
      • +

        JSONArray: If you point to a List.

        +
      • +
      • +

        Map: If you point to a Map.

        +
      • +
      • +

        Number: If you point to Integer, Double, or other kind of number.

        +
      • +
      • +

        Boolean: If you point to a Boolean.

        +
      • +
      +
      +
    • +
    • +

      byNull(): The value taken from the response via the provided JSON Path must be null

      +
    • +
    +
    +
  • +
+
+
+
YAML
+

Please read the Groovy section for detailed explanation of +what the types mean

+
+
+

For YAML the structure of a matcher looks like this

+
+
+
+
- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string
+
+
+
+

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

+
+
+
+
- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode
+
+
+
+

Below you can find the allowed list of `type`s.

+
+
+
    +
  • +

    For stubMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    For testMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    • +

      by_command

      +
    • +
    • +

      by_null

      +
    • +
    +
    +
  • +
+
+
+

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

+
+
+
    +
  • +

    as_integer

    +
  • +
  • +

    as_double

    +
  • +
  • +

    as_float,

    +
  • +
  • +

    as_long

    +
  • +
  • +

    as_short

    +
  • +
  • +

    as_boolean

    +
  • +
  • +

    as_string

    +
  • +
+
+
+

Consider the following example:

+
+
+
Groovy DSL
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		urlPath '/get'
+		body([
+				duck                : 123,
+				alpha               : 'abc',
+				number              : 123,
+				aBoolean            : true,
+				date                : '2017-01-01',
+				dateTime            : '2017-01-01T01:23:45',
+				time                : '01:02:34',
+				valueWithoutAMatcher: 'foo',
+				valueWithTypeMatch  : 'string',
+				key                 : [
+						'complex.key': 'foo'
+				]
+		])
+		bodyMatchers {
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			jsonPath('$.duck', byEquality())
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+		}
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status OK()
+		body([
+				duck                 : 123,
+				alpha                : 'abc',
+				number               : 123,
+				positiveInteger      : 1234567890,
+				negativeInteger      : -1234567890,
+				positiveDecimalNumber: 123.4567890,
+				negativeDecimalNumber: -123.4567890,
+				aBoolean             : true,
+				date                 : '2017-01-01',
+				dateTime             : '2017-01-01T01:23:45',
+				time                 : "01:02:34",
+				valueWithoutAMatcher : 'foo',
+				valueWithTypeMatch   : 'string',
+				valueWithMin         : [
+						1, 2, 3
+				],
+				valueWithMax         : [
+						1, 2, 3
+				],
+				valueWithMinMax      : [
+						1, 2, 3
+				],
+				valueWithMinEmpty    : [],
+				valueWithMaxEmpty    : [],
+				key                  : [
+						'complex.key': 'foo'
+				],
+				nullValue            : null
+		])
+		bodyMatchers {
+			// asserts the jsonpath value against manual regex
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			// asserts the jsonpath value against the provided value
+			jsonPath('$.duck', byEquality())
+			// asserts the jsonpath value against some default regex
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			// asserts vs inbuilt time related regex
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			// asserts that the resulting type is the same as in response body
+			jsonPath('$.valueWithTypeMatch', byType())
+			jsonPath('$.valueWithMin', byType {
+				// results in verification of size of array (min 1)
+				minOccurrence(1)
+			})
+			jsonPath('$.valueWithMax', byType {
+				// results in verification of size of array (max 3)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinMax', byType {
+				// results in verification of size of array (min 1 & max 3)
+				minOccurrence(1)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinEmpty', byType {
+				// results in verification of size of array (min 0)
+				minOccurrence(0)
+			})
+			jsonPath('$.valueWithMaxEmpty', byType {
+				// results in verification of size of array (max 0)
+				maxOccurrence(0)
+			})
+			// will execute a method `assertThatValueIsANumber`
+			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+			jsonPath('$.nullValue', byNull())
+		}
+		headers {
+			contentType(applicationJson())
+			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  urlPath: /get/1
+  headers:
+    Content-Type: application/json
+  cookies:
+    foo: 2
+    bar: 3
+  queryParameters:
+    limit: 10
+    offset: 20
+    filter: 'email'
+    sort: name
+    search: 55
+    age: 99
+    name: John.Doe
+    email: 'bob@email.com'
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    key:
+      "complex.key": 'foo'
+    nullValue: null
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+  matchers:
+    url:
+      regex: /get/[0-9]
+      # predefined:
+      # execute a method
+      #command: 'equals($it)'
+    queryParameters:
+      - key: limit
+        type: equal_to
+        value: 20
+      - key: offset
+        type: containing
+        value: 20
+      - key: sort
+        type: equal_to
+        value: name
+      - key: search
+        type: not_matching
+        value: '^[0-9]{2}$'
+      - key: age
+        type: not_matching
+        value: '^\\w*$'
+      - key: name
+        type: matching
+        value: 'John.*'
+      - key: hello
+        type: absent
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: "$.['key'].['complex.key']"
+        type: by_equality
+      - path: $.nullvalue
+        type: by_null
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+response:
+  status: 200
+  cookies:
+    foo: 1
+    bar: 2
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+    key:
+      'complex.key': 'foo'
+    nulValue: null
+  matchers:
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: $.valueWithTypeMatch
+        type: by_type
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+      - path: $.valueWithMinEmpty
+        type: by_type
+        minOccurrence: 0
+      - path: $.valueWithMaxEmpty
+        type: by_type
+        maxOccurrence: 0
+      - path: $.duck
+        type: by_command
+        value: assertThatValueIsANumber($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+  headers:
+    Content-Type: application/json
+
+
+
+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

+
+
+

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

+
+
+
    +
  • +

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    +
  • +
  • +

    For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.

    +
  • +
  • +

    For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.

    +
  • +
  • +

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

    +
  • +
+
+
+

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
+
+
+
+ + + + + +
+ + +Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. +
+
+
+

The resulting WireMock stub is in the following example:

+
+
+
+
					'''
+{
+  "request" : {
+    "urlPath" : "/get",
+    "method" : "POST",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck == 123)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
+    "headers" : {
+      "Content-Type" : "application/json"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+'''
+
+
+
+ + + + + +
+ + +If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection. +
+
+
+

Consider the following example:

+
+
+
+
Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}
+
+
+
+

The preceding code leads to creating the following test (the code block shows only the assertion section):

+
+
+
+
and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
+
+
+
+

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

+
+
+
+
+

JAX-RS Support

+
+

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

+
+
+

In order to use JAX-RS mode, use the following settings:

+
+
+
+
testMode == 'JAXRSCLIENT'
+
+
+
+

The following example shows a generated test API:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Response;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static javax.ws.rs.client.Entity.*;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\tWebTarget webTarget;
+
+\t@Test
+\tpublic void validate_() throws Exception {
+
+\t\t// when:
+\t\t\tResponse response = webTarget
+\t\t\t\t\t\t\t.path("/users")
+\t\t\t\t\t\t\t.queryParam("limit", "10")
+\t\t\t\t\t\t\t.queryParam("offset", "20")
+\t\t\t\t\t\t\t.queryParam("filter", "email")
+\t\t\t\t\t\t\t.queryParam("sort", "name")
+\t\t\t\t\t\t\t.queryParam("search", "55")
+\t\t\t\t\t\t\t.queryParam("age", "99")
+\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
+\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
+\t\t\t\t\t\t\t.request()
+\t\t\t\t\t\t\t.build("GET")
+\t\t\t\t\t\t\t.invoke();
+\t\t\tString responseAsString = response.readEntity(String.class);
+
+\t\t// then:
+\t\t\tassertThat(response.getStatus()).isEqualTo(200);
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
+\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
+\t}
+
+}
+
+"""
+
+
+
+
+

Async Support

+
+

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}
+
+
+
+
YAML
+
+
response:
+    async: true
+
+
+
+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}
+
+
+
+
YAML
+
+
response:
+    fixedDelayMilliseconds: 1000
+
+
+
+
+

Working with Context Paths

+
+

Spring Cloud Contract supports context paths.

+
+
+ + + + + +
+ + +The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

+
+
+

Consider the following contract:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+		url '/my-context-path/url'
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured:

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ContextPathTestingBaseClass {
+
+	@LocalServerPort int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost";
+		RestAssured.port = this.port;
+	}
+}
+
+
+
+

If you do it this way:

+
+
+
    +
  • +

    All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).

    +
  • +
  • +

    Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

    +
  • +
+
+
+
+

Working with WebFlux

+
+

Spring Cloud Contract offers two ways of working with WebFlux.

+
+
+

WebFlux with WebTestClient

+
+

One of them is via the WebTestClient mode.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'WEBTESTCLIENT'
+}
+
+
+
+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

+
+
+
+
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}
+
+
+
+
+

WebFlux with Explicit mode

+
+

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured for Web Flux:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(classes = BeerRestBase.Config.class,
+		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+		properties = "server.port=0")
+public abstract class BeerRestBase {
+
+    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+@Configuration
+@EnableAutoConfiguration
+static class Config {
+
+	@Bean
+	PersonCheckingService personCheckingService()  {
+		return personToCheck -> personToCheck.age >= 20;
+	}
+
+	@Bean
+	ProducerController producerController() {
+		return new ProducerController(personCheckingService());
+	}
+}
+
+}
+
+
+
+
+
+

XML Support for REST

+
+

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

+
+
+

Here is an example of a Groovy DSL contract with XML response body:

+
+
+
+
					Contract.make {
+						request {
+							method GET()
+							urlPath '/get'
+							headers {
+								contentType(applicationXml())
+							}
+						}
+						response {
+							status(OK())
+							headers {
+								contentType(applicationXml())
+							}
+							body """
+<test>
+<duck type='xtype'>123</duck>
+<alpha>abc</alpha>
+<list>
+<elem>abc</elem>
+<elem>def</elem>
+<elem>ghi</elem>
+</list>
+<number>123</number>
+<aBoolean>true</aBoolean>
+<date>2017-01-01</date>
+<dateTime>2017-01-01T01:23:45</dateTime>
+<time>01:02:34</time>
+<valueWithoutAMatcher>foo</valueWithoutAMatcher>
+<key><complex>foo</complex></key>
+</test>"""
+							bodyMatchers {
+								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
+								xPath('/test/duck/text()', byCommand('equals($it)'))
+								xPath('/test/duck/xxx', byNull())
+								xPath('/test/duck/text()', byEquality())
+								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
+								xPath('/test/alpha/text()', byEquality())
+								xPath('/test/number/text()', byRegex(number()))
+								xPath('/test/date/text()', byDate())
+								xPath('/test/dateTime/text()', byTimestamp())
+								xPath('/test/time/text()', byTime())
+								xPath('/test/*/complex/text()', byEquality())
+								xPath('/test/duck/@type', byEquality())
+							}
+						}
+					}
+
+
+
+

And below is an example of a YAML contract with XML request and response bodies:

+
+
+
+
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
+
+
+
+

Here is an example of an automatically generated test for XML response body:

+
+
+
+
@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}
+
+
+
+
+

Messaging Top-Level Elements

+
+

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

+
+ +
+

Output Triggered by a Method

+
+

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	// Human readable description
+	description 'Some description'
+	// Label by means of which the output message can be triggered
+	label 'some_label'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('bookReturnedTriggered()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo('output')
+		// the body of the output message
+		body('''{ "bookName" : "foo" }''')
+		// the headers of the output message
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+input:
+  # the contract will be triggered by a method
+  triggeredBy: bookReturnedTriggered()
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

+
+
+
+

Output Triggered by a Message

+
+

The output message can be triggered by receiving a message, as shown in the following +example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	description 'Some Description'
+	label 'some_label'
+	// input is a message
+	input {
+		// the message was received from this destination
+		messageFrom('input')
+		// has the following body
+		messageBody([
+				bookName: 'foo'
+		])
+		// and the following headers
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+# input is a message
+input:
+  messageFrom: input
+  # has the following body
+  messageBody:
+    bookName: 'foo'
+  # and the following headers
+  messageHeaders:
+    sample: 'header'
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

+
+
+
+

Consumer/Producer

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. +
+
+
+

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

+
+
+
+
					Contract.make {
+				name "foo"
+						label 'some_label'
+						input {
+							messageFrom value(consumer('jms:output'), producer('jms:input'))
+							messageBody([
+									bookName: 'foo'
+							])
+							messageHeaders {
+								header('sample', 'header')
+							}
+						}
+						outputMessage {
+							sentTo $(consumer('jms:input'), producer('jms:output'))
+							body([
+									bookName: 'foo'
+							])
+						}
+					}
+
+
+
+
+

Common

+
+

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

+
+
+
+
+

Multiple Contracts in One File

+
+

You can define multiple contracts in one file. Such a contract might resemble the +following example:

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+[
+	Contract.make {
+		name("should post a user")
+		request {
+			method 'POST'
+			url('/users/1')
+		}
+		response {
+			status OK()
+		}
+	},
+	Contract.make {
+		request {
+			method 'POST'
+			url('/users/2')
+		}
+		response {
+			status OK()
+		}
+	}
+]
+
+
+
+
YAML
+
+
---
+name: should post a user
+request:
+  method: POST
+  url: /users/1
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/2
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/3
+response:
+  status: 200
+
+
+
+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

+
+
+
+
package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}
+
+
+
+

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

+
+
+

The generated stubs is shown in the following example:

+
+
+
+
should post a user.json
+1_WithList.json
+
+
+
+

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

+
+
+ + + + + +
+ + +As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful. +
+
+
+
+

Generating Spring REST Docs snippets from the contracts

+
+

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+<dependency>
+	<groupId>org.springframework.restdocs</groupId>
+	<artifactId>spring-restdocs-mockmvc</artifactId>
+	<optional>true</optional>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
+
+
+
+

Next you need to make some changes to your base class like the following example.

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public abstract class FraudBaseWithWebAppSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Autowired
+	private WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName()))
+				.build());
+	}
+
+	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+public abstract class FraudBaseWithStandaloneSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
+				.standaloneSetup(new FraudDetectionController())
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName())));
+	}
+
+}
+
+
+
+ + + + + +
+ + +You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. +
+
+
+
+
+
+

Customization

+
+
+ + + + + +
+ + +This section is valid only for Groovy DSL +
+
+
+

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

+
+
+

Extending the DSL

+
+

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

+
+
+
    +
  • +

    Creating a JAR with reusable classes.

    +
  • +
  • +

    Referencing of these classes in the DSLs.

    +
  • +
+
+
+

You can find the full example +here.

+
+
+

Common JAR

+
+

The following examples show three classes that can be reused in the DSLs.

+
+
+

PatternUtils contains functions used by both the consumer and the producer.

+
+
+
+
package com.example;
+
+import java.util.regex.Pattern;
+
+/**
+ * If you want to use {@link Pattern} directly in your tests
+ * then you can create a class resembling this one. It can
+ * contain all the {@link Pattern} you want to use in the DSL.
+ *
+ * <pre>
+ * {@code
+ * request {
+ *     body(
+ *         [ age: $(c(PatternUtils.oldEnough()))]
+ *     )
+ * }
+ * </pre>
+ *
+ * Notice that we're using both {@code $()} for dynamic values
+ * and {@code c()} for the consumer side.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class PatternUtils {
+
+	public static String tooYoung() {
+		//remove::start[]
+		return "[0-1][0-9]";
+		//remove::end[return]
+	}
+
+	public static Pattern oldEnough() {
+		//remove::start[]
+		return Pattern.compile("[2-9][0-9]");
+		//remove::end[return]
+	}
+
+	/**
+	 * Makes little sense but it's just an example ;)
+	 */
+	public static Pattern ok() {
+		//remove::start[]
+		return Pattern.compile("OK");
+		//remove::end[return]
+	}
+}
+//end::impl[]
+
+
+
+

ConsumerUtils contains functions used by the consumer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the consumer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you can have a regular expression.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you have to have a concrete value.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ConsumerUtils {
+	/**
+	 * Consumer side property. By using the {@link ClientDslProperty}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * request {
+	 *     body(
+	 *         [ age: $(ConsumerUtils.oldEnough())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 *
+	 * @author Marcin Grzejszczak
+	 */
+	public static ClientDslProperty oldEnough() {
+		//remove::start[]
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
+		//remove::end[return]
+	}
+
+}
+//end::impl[]
+
+
+
+

ProducerUtils contains functions used by the producer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the producer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you have to have a concrete value.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you can have a regular expression.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ProducerUtils {
+
+	/**
+	 * Producer side property. By using the {@link ProducerUtils}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * response {
+	 *     body(
+	 *         [ status: $(ProducerUtils.ok())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 */
+	public static ServerDslProperty ok() {
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ServerDslProperty( PatternUtils.ok(), "OK");
+	}
+}
+//end::impl[]
+
+
+
+
+

Adding the Dependency to the Project

+
+

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

+
+
+
+

Test the Dependency in the Project’s Dependencies

+
+

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

+
+
+
Maven
+
+
<dependency>
+	<groupId>com.example</groupId>
+	<artifactId>beer-common</artifactId>
+	<version>${project.version}</version>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")
+
+
+
+
+

Test a Dependency in the Plugin’s Dependencies

+
+

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example</packageWithBaseClasses>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
+				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>com.example</groupId>
+			<artifactId>beer-common</artifactId>
+			<version>${project.version}</version>
+			<scope>compile</scope>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"
+
+
+
+
+

Referencing classes in DSLs

+
+

You can now reference your classes in your DSL, as shown in the following example:

+
+
+
+
package contracts.beer.rest
+
+import com.example.ConsumerUtils
+import com.example.ProducerUtils
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	description("""
+Represents a successful scenario of getting a beer
+
+```
+given:
+	client is old enough
+when:
+	he applies for a beer
+then:
+	we'll grant him the beer
+```
+
+""")
+	request {
+		method 'POST'
+		url '/check'
+		body(
+				age: $(ConsumerUtils.oldEnough())
+		)
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status 200
+		body("""
+			{
+				"status": "${value(ProducerUtils.ok())}"
+			}
+			""")
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+ + + + + +
+ + +You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. +
+
+
+
+
+
+
+

Using the Pluggable Architecture

+
+
+

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

+
+
+

Custom Contract Converter

+
+

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

+
+
+
+
package org.springframework.cloud.contract.spec;
+
+import java.io.File;
+import java.util.Collection;
+
+/**
+ * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
+ * {@link Contract} to {@code T}.
+ *
+ * @param <T> - type to which we want to convert the contract
+ * @author Marcin Grzejszczak
+ * @since 1.1.0
+ */
+public interface ContractConverter<T> extends ContractStorer<T> {
+
+	/**
+	 * Should this file be accepted by the converter. Can use the file extension to check
+	 * if the conversion is possible.
+	 * @param file - file to be considered for conversion
+	 * @return - {@code true} if the given implementation can convert the file
+	 */
+	boolean isAccepted(File file);
+
+	/**
+	 * Converts the given {@link File} to its {@link Contract} representation.
+	 * @param file - file to convert
+	 * @return - {@link Contract} representation of the file
+	 */
+	Collection<Contract> convertFrom(File file);
+
+	/**
+	 * Converts the given {@link Contract} to a {@link T} representation.
+	 * @param contract - the parsed contract
+	 * @return - {@link T} the type to which we do the conversion
+	 */
+	T convertTo(Collection<Contract> contract);
+
+}
+
+
+
+

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

+
+
+ + + + + +
+ + +Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation. +
+
+
+

The following example shows a typical spring.factories file:

+
+
+
+
org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter
+
+
+
+

Pact Converter

+
+

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

+
+
+

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

+
+
+
    +
  • +

    to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    +
  • +
+
+
+
+

Pact Contract

+
+

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

+
+
+
+
{
+  "provider": {
+    "name": "Provider"
+  },
+  "consumer": {
+    "name": "Consumer"
+  },
+  "interactions": [
+    {
+      "description": "",
+      "request": {
+        "method": "PUT",
+        "path": "/fraudcheck",
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "clientId": "1234567890",
+          "loanAmount": 99999
+        },
+        "generators": {
+          "body": {
+            "$.clientId": {
+              "type": "Regex",
+              "regex": "[0-9]{10}"
+            }
+          }
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.clientId": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "[0-9]{10}"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      },
+      "response": {
+        "status": 200,
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "fraudCheckStatus": "FRAUD",
+          "rejectionReason": "Amount too high"
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.fraudCheckStatus": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "FRAUD"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "metadata": {
+    "pact-specification": {
+      "version": "3.0.0"
+    },
+    "pact-jvm": {
+      "version": "3.5.13"
+    }
+  }
+}
+
+
+
+

The remainder of this section about using Pact refers to the preceding file.

+
+
+
+

Pact for Producers

+
+

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-contract-pact</artifactId>
+			<version>${spring-cloud-contract.version}</version>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"
+
+
+
+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}
+
+
+
+

The corresponding generated stub might be as follows:

+
+
+
+
{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}
+
+
+
+
+

Pact for Consumers

+
+

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-pact</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-contract-pact"
+
+
+
+
+
+

Using the Custom Test Generator

+
+

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

+
+
+

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.builder;
+
+import java.nio.file.Path;
+import java.util.Collection;
+
+import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
+import org.springframework.cloud.contract.verifier.file.ContractMetadata;
+
+/**
+ * Builds a single test.
+ *
+ * @since 1.1.0
+ */
+public interface SingleTestGenerator {
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param className - the name of the generated test class
+	 * @param classPackage - the name of the package in which the test class should be
+	 * stored
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
+	 */
+	@Deprecated
+	String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String className,
+			String classPackage, String includedDirectoryRelativePath);
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param generatedClassData - information about the generated class
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 */
+	default String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles,
+			String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
+		String className = generatedClassData.className;
+		String classPackage = generatedClassData.classPackage;
+		String path = includedDirectoryRelativePath;
+		return buildClass(properties, listOfFiles, className, classPackage, path);
+	}
+
+	/**
+	 * Extension that should be appended to the generated test class. E.g. {@code .java}
+	 * or {@code .php}
+	 * @param properties - properties passed to the plugin
+	 */
+	String fileExtension(ContractVerifierConfigProperties properties);
+
+	class GeneratedClassData {
+
+		public final String className;
+
+		public final String classPackage;
+
+		public final Path testClassPath;
+
+		public GeneratedClassData(String className, String classPackage,
+				Path testClassPath) {
+			this.className = className;
+			this.classPackage = classPackage;
+			this.testClassPath = testClassPath;
+		}
+
+	}
+
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator
+
+
+
+
+

Using the Custom Stub Generator

+
+

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.converter
+
+import groovy.transform.CompileStatic
+
+import org.springframework.cloud.contract.spec.Contract
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Converts contracts into their stub representation.
+ *
+ * @since 1.1.0
+ */
+@CompileStatic
+interface StubGenerator {
+
+	/**
+	 * @return {@code true} if the converter can handle the file to convert it into a stub.
+	 */
+	boolean canHandleFileName(String fileName)
+
+	/**
+	 * @return the collection of converted contracts into stubs. One contract can
+	 * result in multiple stubs.
+	 */
+	Map<Contract, String> convertContents(String rootName, ContractMetadata content)
+
+	/**
+	 * @return the name of the converted stub file. If you have multiple contracts
+	 * in a single file then a prefix will be added to the generated file. If you
+	 * provide the {@link Contract#name} field then that field will override the
+	 * generated file name.
+	 *
+	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be
+	 * converted by the implementation to {@code foo.json}. The recursive file
+	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
+	 */
+	String generateOutputFileNameForInput(String inputFileName)
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
# Stub converters
+org.springframework.cloud.contract.verifier.converter.StubGenerator=\
+org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
+
+
+
+

The default implementation is the WireMock stub generation.

+
+
+ + + + + +
+ + +You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. +
+
+
+
+

Using the Custom Stub Runner

+
+

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

+
+
+

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

+
+
+

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

+
+
+
+
package org.springframework.cloud.contract.stubrunner.provider.moco
+
+import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
+import com.github.dreamhead.moco.runner.JsonRunner
+import com.github.dreamhead.moco.runner.RunnerSetting
+import groovy.util.logging.Commons
+
+import org.springframework.cloud.contract.stubrunner.HttpServerStub
+import org.springframework.util.SocketUtils
+
+@Commons
+class MocoHttpServerStub implements HttpServerStub {
+
+	private boolean started
+	private JsonRunner runner
+	private int port
+
+	@Override
+	int port() {
+		if (!isRunning()) {
+			return -1
+		}
+		return port
+	}
+
+	@Override
+	boolean isRunning() {
+		return started
+	}
+
+	@Override
+	HttpServerStub start() {
+		return start(SocketUtils.findAvailableTcpPort())
+	}
+
+	@Override
+	HttpServerStub start(int port) {
+		this.port = port
+		return this
+	}
+
+	@Override
+	HttpServerStub stop() {
+		if (!isRunning()) {
+			return this
+		}
+		this.runner.stop()
+		return this
+	}
+
+	@Override
+	HttpServerStub registerMappings(Collection<File> stubFiles) {
+		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
+			.collect {
+			log.info("Trying to parse [${it.name}]")
+			try {
+				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
+					build()
+			}
+			catch (Exception e) {
+				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
+				return null
+			}
+		}.findAll { it }
+		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
+			HttpArgs.httpArgs().withPort(this.port).build())
+		this.runner.run()
+		this.started = true
+		return this
+	}
+
+	@Override
+	String registeredMappings() {
+		return ""
+	}
+
+	@Override
+	boolean isAccepted(File file) {
+		return file.name.endsWith(".json")
+	}
+}
+
+
+
+

Then, you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
+
+
+
+

Now you can run stubs with Moco.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. +
+
+
+
+

Using the Custom Stub Downloader

+
+

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

+
+
+
+
package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}
+
+
+
+

Then you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder
+
+
+
+

Now you can pick a folder with the source of your stubs.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. +
+
+
+
+

Using the SCM Stub Downloader

+
+

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

+

* stubrunner.properties.git.branch (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

+

* stubrunner.properties.git.username (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

+

* stubrunner.properties.git.password (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

+

* stubrunner.properties.git.no-of-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

+

* stubrunner.properties.git.wait-between-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

+
+
+

Using the Pact Stub Downloader

+
+

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

+

* stubrunner.properties.pactbroker.host (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

+

* stubrunner.properties.pactbroker.port (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

+

* stubrunner.properties.pactbroker.protocol (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

+

* stubrunner.properties.pactbroker.tags (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

+

* stubrunner.properties.pactbroker.auth.scheme (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

+

* stubrunner.properties.pactbroker.auth.username (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

+

* stubrunner.properties.pactbroker.auth.password (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

+

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/spring-cloud-contract.html b/reference/html/spring-cloud-contract.html new file mode 100644 index 0000000000..3ba3a37584 --- /dev/null +++ b/reference/html/spring-cloud-contract.html @@ -0,0 +1,15095 @@ + + + + + + + +Spring Cloud Contract + + + + + + + + + + +
+
+
+
+

Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant

+
+
+

{spring-cloud-version}

+
+
+
+
+

1. Spring Cloud Contract

+
+
+

You need confidence when pushing new features to a new application or service in a +distributed system. This project provides support for Consumer Driven Contracts and +service schemas in Spring applications (for both HTTP and message-based interactions), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers.

+
+
+
+
+

2. Spring Cloud Contract Verifier Introduction

+
+
+

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

+
+
+

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

+
+
+
    +
  • +

    JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.

    +
  • +
  • +

    Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.

    +
  • +
  • +

    Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

    +
  • +
+
+
+

2.1. History

+
+

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

+
+
+

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

+
+
+
+

2.2. Why a Contract Verifier?

+
+

Assume that we have a system consisting of multiple microservices:

+
+
+
+Microservices Architecture +
+
+
+

2.2.1. Testing issues

+
+

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

+
+
+
    +
  • +

    Deploy all microservices and perform end-to-end tests.

    +
  • +
  • +

    Mock other microservices in unit/integration tests.

    +
  • +
+
+
+

Both have their advantages but also a lot of disadvantages.

+
+
+

Deploy all microservices and perform end to end tests

+
+
+

Advantages:

+
+
+
    +
  • +

    Simulates production.

    +
  • +
  • +

    Tests real communication between services.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.

    +
  • +
  • +

    The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).

    +
  • +
  • +

    They take a long time to run.

    +
  • +
  • +

    The feedback comes very late in the process.

    +
  • +
  • +

    They are extremely hard to debug.

    +
  • +
+
+
+

Mock other microservices in unit/integration tests

+
+
+

Advantages:

+
+
+
    +
  • +

    They provide very fast feedback.

    +
  • +
  • +

    They have no infrastructure requirements.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    The implementor of the service creates stubs that might have nothing to do with +reality.

    +
  • +
  • +

    You can go to production with passing tests and failing production.

    +
  • +
+
+
+

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

+
+
+
+Stubbed Services +
+
+
+

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

+
+
+
+
+

2.3. Purposes

+
+

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

+
+
+
    +
  • +

    To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.

    +
  • +
  • +

    To promote ATDD method and Microservices architectural style.

    +
  • +
  • +

    To provide a way to publish changes in contracts that are immediately visible on both +sides.

    +
  • +
  • +

    To generate boilerplate test code to be used on the server side.

    +
  • +
+
+
+ + + + + +
+ + +Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. +
+
+
+
+

2.4. How It Works

+
+

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

+
+
+

2.4.1. A Three-second Tour

+
+

This very brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find a somewhat longer tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    +
    +
    +
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

+
+
+
+
+

2.4.2. A Three-minute Tour

+
+

This brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find an even more brief tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

+
+
+
+
package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}
+
+
+
+

The same contract expressed in YAML would look like the following example:

+
+
+
+
request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8
+
+
+
+

In the case of messaging, you can define:

+
+
+
    +
  • +

    The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).

    +
  • +
  • +

    The methods that should be called after the message is received.

    +
  • +
  • +

    The methods that, when called, should trigger a message.

    +
  • +
+
+
+

The following example shows a Camel messaging contract expressed in Groovy DSL:

+
+
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+

The following example shows the same contract expressed in YAML:

+
+
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

+
+
+

The following example shows a sample auto-generated test for an HTTP contract:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

+
+
+

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

+
+
+

Here is an example of a test generated in WEBTESTCLIENT test mode:

+
+
+
+
[source,java,indent=0]
+
+
+
+
+
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}
+
+
+
+

Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin +testFramework property to either JUNIT5, TESTNG or Spock.

+
+
+ + + + + +
+ + +You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. +
+
+
+

The following example shows an auto-generated test in Spock for a messaging stub contract:

+
+
+
+
[source,groovy,indent=0]
+
+
+
+
+
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+
+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

+
+
+

Docker Project

+
+
+

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To get started, add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    +
    +
    +
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: https://repo.spring.io/libs-snapshot
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+
+
+

2.4.3. Defining the Contract

+
+

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

+
+
+

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+
+

2.4.4. Client Side

+
+

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

+
+
+
+

2.4.5. Server Side

+
+

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

+
+
+

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

+
+
+

The autogenerated test looks, more or less, like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+
+
+

2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)

+
+

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

+
+
+

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

+
+
+

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

+
+
+

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

+
+ +
+ + + + + +
+ + +In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository. +
+
+
+

2.5.1. Technical note

+
+

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
repositories {
+	mavenCentral()
+	mavenLocal()
+	maven { url "https://repo.spring.io/snapshot" }
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/release" }
+}
+
+
+
+
+

2.5.2. Consumer side (Loan Issuance)

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

+
+
+
    +
  1. +

    Start doing TDD by writing a test for your feature.

    +
  2. +
  3. +

    Write the missing implementation.

    +
  4. +
  5. +

    Clone the Fraud Detection service repository locally.

    +
  6. +
  7. +

    Define the contract locally in the repo of Fraud Detection service.

    +
  8. +
  9. +

    Add the Spring Cloud Contract Verifier plugin.

    +
  10. +
  11. +

    Run the integration tests.

    +
  12. +
  13. +

    File a pull request.

    +
  14. +
  15. +

    Create an initial implementation.

    +
  16. +
  17. +

    Take over the pull request.

    +
  18. +
  19. +

    Write the missing implementation.

    +
  20. +
  21. +

    Deploy your app.

    +
  22. +
  23. +

    Work online.

    +
  24. +
+
+
+

Start doing TDD by writing a test for your feature.

+
+
+
+
@Test
+public void shouldBeRejectedDueToAbnormalLoanAmount() {
+	// given:
+	LoanApplication application = new LoanApplication(new Client("1234567890"),
+			99999);
+	// when:
+	LoanApplicationResult loanApplication = service.loanApplication(application);
+	// then:
+	assertThat(loanApplication.getLoanApplicationStatus())
+			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
+	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
+}
+
+
+
+

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

+
+
+

Write the missing implementation.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

+
+
+
+
ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
+		"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
+		new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
+
+
+
+

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

+
+
+

If you start the test at this point, it breaks, because no service currently runs on port +8080.

+
+
+

Clone the Fraud Detection service repository locally.

+
+
+

You can start by playing around with the server side contract. To do so, you must first +clone it.

+
+
+
+
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
+
+
+
+

Define the contract locally in the repo of Fraud Detection service.

+
+
+

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

+
+
+ + + + + +
+ + +Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder. +
+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request { // (1)
+		method 'PUT' // (2)
+		url '/fraudcheck' // (3)
+		body([ // (4)
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount : 99999
+		])
+		headers { // (5)
+			contentType('application/json')
+		}
+	}
+	response { // (6)
+		status OK() // (7)
+		body([ // (8)
+			   fraudCheckStatus  : "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers { // (9)
+			contentType('application/json')
+		}
+	}
+}
+
+/*
+From the Consumer perspective, when shooting a request in the integration test:
+
+(1) - If the consumer sends a request
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the response will be sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` equal to `application/json`
+
+From the Producer perspective, in the autogenerated producer-side test:
+
+(1) - A request will be sent to the producer
+(2) - With the "PUT" method
+(3) - to the URL "/fraudcheck"
+(4) - with the JSON body that
+ * has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
+ * has a field `loanAmount` that is equal to `99999`
+(5) - with header `Content-Type` equal to `application/json`
+(6) - then the test will assert if the response has been sent with
+(7) - status equal `200`
+(8) - and JSON body equal to
+ { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+(9) - with header `Content-Type` matching `application/json.*`
+ */
+
+
+
+
YAML
+
+
request: # (1)
+  method: PUT # (2)
+  url: /fraudcheck # (3)
+  body: # (4)
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers: # (5)
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id'] # (6)
+        type: by_regex
+        value: "[0-9]{10}"
+response: # (7)
+  status: 200 # (8)
+  body:  # (9)
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers: # (10)
+    Content-Type: application/json
+
+
+#From the Consumer perspective, when shooting a request in the integration test:
+#
+#(1) - If the consumer sends a request
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
+#(7) - then the response will be sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+#
+#From the Producer perspective, in the autogenerated producer-side test:
+#
+#(1) - A request will be sent to the producer
+#(2) - With the "PUT" method
+#(3) - to the URL "/fraudcheck"
+#(4) - with the JSON body that
+# * has a field `client.id` `1234567890`
+# * has a field `loanAmount` that is equal to `99999`
+#(5) - with header `Content-Type` equal to `application/json`
+#(7) - then the test will assert if the response has been sent with
+#(8) - status equal `200`
+#(9) - and JSON body equal to
+# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
+#(10) - with header `Content-Type` equal to `application/json`
+
+
+
+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the Contract DSL section for more information. We highly recommend using the map notation!

+
+
+ + + + + +
+ + +You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON. +
+
+
+

The previously shown contract is an agreement between two sides that:

+
+
+
    +
  • +

    if an HTTP request is sent with all of

    +
    +
      +
    • +

      a PUT method on the /fraudcheck endpoint,

      +
    • +
    • +

      a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json,

      +
    • +
    +
    +
  • +
  • +

    then an HTTP response is sent to the consumer that

    +
    +
      +
    • +

      has status 200,

      +
    • +
    • +

      contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json.

      +
    • +
    +
    +
  • +
+
+
+

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

+
+
+

Add the Spring Cloud Contract Verifier plugin.

+
+
+

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

+
+
+
    +
  • +

    generate and run tests

    +
  • +
  • +

    produce and install stubs

    +
  • +
+
+
+

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

+
+
+
+
$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests
+
+
+
+

In the logs, you see something like this:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

The following line is extremely important:

+
+
+
+
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

It confirms that the stubs of the http-server have been installed in the local +repository.

+
+
+

Run the integration tests.

+
+
+

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

+
+
+

Add the Spring Cloud Contract BOM:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release-train.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {
+		"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+

Now, when you run your tests, you see something like this:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

+
+
+

File a pull request.

+
+
+

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

+
+
+

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

+
+
+
+

2.5.3. Producer side (Fraud Detection server)

+
+

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

+
+
+

Create an initial implementation.

+
+
+

As a reminder, you can see the initial implementation here:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

Take over the pull request.

+
+
+
+
$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
+
+
+
+

You must add the dependencies needed by the autogenerated tests:

+
+
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+
+ + + + + +
+ + +This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name. +
+
+
+

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

+
+
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+
+public class FraudBase {
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
+				new FraudStatsController(stubbedStatsProvider()));
+	}
+
+	private StatsProvider stubbedStatsProvider() {
+		return fraudType -> {
+			switch (fraudType) {
+			case DRUNKS:
+				return 100;
+			case ALL:
+				return 200;
+			}
+			return 0;
+		};
+	}
+
+	public void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

Now, if you run the ./mvnw clean install, you get something like this:

+
+
+
+
Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
+
+
+
+

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

+
+
+

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

+
+
+

Write the missing implementation.

+
+
+

Because you know the expected input and expected output, you can write the missing +implementation:

+
+
+
+
@RequestMapping(value = "/fraudcheck", method = PUT)
+public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
+if (amountGreaterThanThreshold(fraudCheck)) {
+	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
+}
+return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
+}
+
+
+
+

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

+
+
+

Deploy your app.

+
+
+

Once you finish your work, you can deploy your change. First, merge the branch:

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master
+
+
+
+

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

+
+
+
+

2.5.4. Consumer Side (Loan Issuance) Final Step

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

+
+
+

Merge branch to master.

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+
+
+
+

Work online.

+
+
+

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

+
+
+
+
stubrunner:
+  ids: 'com.example:http-server-dsl:+:stubs:8080'
+  repositoryRoot: https://repo.spring.io/libs-snapshot
+
+
+
+

That’s it!

+
+
+
+
+

2.6. Dependencies

+
+

The best way to add dependencies is to use the proper starter dependency.

+
+
+

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

+
+
+
+ +
+

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

+
+
+

2.7.1. Spring Cloud Contract video

+
+

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

+
+
+
+ +
+
+
+ +
+
+

2.8. Samples

+
+

You can find some samples at +samples.

+
+
+
+
+
+

3. Spring Cloud Contract FAQ

+
+
+

3.1. Why use Spring Cloud Contract Verifier and not X ?

+
+

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

+
+
+
    +
  • +

    Possibility to do CDC with messaging

    +
  • +
  • +

    Clear and easy to use, statically typed DSL

    +
  • +
  • +

    Possibility to copy paste your current JSON file to the contract and only edit its elements

    +
  • +
  • +

    Automatic generation of tests from the defined Contract

    +
  • +
  • +

    Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory

    +
  • +
  • +

    Spring Cloud integration - no discovery service is needed for integration tests

    +
  • +
  • +

    Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality

    +
  • +
  • +

    Via Docker adds support for any language & framework used

    +
  • +
+
+
+
+

3.2. I don’t want to write a contract in Groovy!

+
+

No problem. You can write a contract in YAML!

+
+
+
+

3.3. What is this value(consumer(), producer()) ?

+
+

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

and JSON response

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

+
+
+

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}
+
+
+
+

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}
+
+
+
+

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

+
+
+

Either via the value method

+
+
+
+
value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

or using the $() method

+
+
+
+
$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

You can read more about this in the Contract DSL section.

+
+
+

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

+
+
+ + + + + +
+ + +If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated. +
+
+
+

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

+
+
+

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
+
+
+
+ + + + + +
+ + +Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies. +
+
+
+
+

3.4. How to do Stubs versioning?

+
+

3.4.1. API Versioning

+
+

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

+
+
+
    +
  • +

    use Hypermedia, links and do not version your API by any means

    +
  • +
  • +

    pass versions through headers / urls

    +
  • +
+
+
+

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

+
+
+

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

+
+
+
+

3.4.2. JAR versioning

+
+

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

+
+
+

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

+
+
+
+
1.0.0.20161020-201521-RELEASE
+
+
+
+

In that case your generated stub jar will look like this.

+
+
+
+
1.0.0.20161020-201521-RELEASE-stubs.jar
+
+
+
+

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
+
+
+
+
+

3.4.3. Dev or prod stubs

+
+

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

+
+
+

Example of tests using development version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

Example of tests using production version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
+
+
+
+

You can pass those values also via properties from your deployment pipeline.

+
+
+
+
+

3.5. Common repo with contracts

+
+

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

+
+
+

3.5.1. Repo structure

+
+

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

+
+
+
+
├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml
+
+
+
+

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

+
+
+

Example of a pom.xml inside the server folder.

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.2.0.M4</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>
+
+
+
+

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

+
+
+

The pom.xml in the root folder can look like this:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>
+
+
+
+

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

+
+
+
+
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
+

3.5.2. Workflow

+
+

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

+
+
+
+

3.5.3. Consumer

+
+

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

+
+
+ + + + + +
+ + +You need to have Maven installed locally +
+
+
+
+

3.5.4. Producer

+
+

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>
+
+
+
+

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from https://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

+
+
+

The rest of the flow looks the same.

+
+
+
+

3.5.5. How can I define messaging contracts per topic not per producer?

+
+

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

+
+
+
For Maven Project
+
+

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

+
+
+
+
<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>
+
+
+
+
+
For Gradle Project
+
+
    +
  • +

    Add a custom configuration for the common-repo dependency:

    +
  • +
+
+
+
+
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
+
+
+
+
    +
  • +

    Add the common-repo dependency to your classpath:

    +
  • +
+
+
+
+
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
+
+
+
+
    +
  • +

    Download the dependency to an appropriate folder:

    +
  • +
+
+
+
+
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
+
+
+
+
    +
  • +

    Unzip JAR:

    +
  • +
+
+
+
+
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
+
+
+
+
    +
  • +

    Cleanup unused contracts:

    +
  • +
+
+
+
+
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
+
+
+
+
    +
  • +

    Create task dependencies:

    +
  • +
+
+
+
+
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
+
+
+
+
    +
  • +

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

    +
  • +
+
+
+
+
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}
+
+
+
+
+
+
+

3.6. Do I need a Binary Storage? Can’t I use Git?

+
+

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

+
+
+

The repository would have to the following setup +(which you can checkout here):

+
+
+
+
.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json
+
+
+
+

Under META-INF folder:

+
+
+
    +
  • +

    we group applications via groupId (e.g. com.example)

    +
  • +
  • +

    then each application is represented via the artifactId (e.g. beer-api-producer-git)

    +
  • +
  • +

    next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    +
    +
      +
    • +

      + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT

        +
      • +
      • +

        if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called latest or + we will pick that folder

        +
      • +
      +
      +
    • +
    • +

      release - to find the latest release version of your stubs. That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called release we will pick that folder

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    finally, there are two folders:

    +
    +
      +
    • +

      contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.

      +
    • +
    • +

      mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

      +
    • +
    +
    +
  • +
+
+
+

3.6.1. Protocol convention

+
+

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

+
+
+

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

+
+
+
+
git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+
+
+
+
+

3.6.2. Producer

+
+

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

+
+
+ + + + + +
+ + +You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass, the stubs will be committed in the cloned repository

    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
+

3.6.3. Producer with contracts stored locally

+
+

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<!-- In the default configuration, we want to use the contracts stored locally -->
+	<configuration>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*messaging.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
+			</baseClassMapping>
+			<baseClassMapping>
+				<contractPackageRegex>.*rest.*</contractPackageRegex>
+				<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+		<basePackageForTests>com.example</basePackageForTests>
+	</configuration>
+	<executions>
+		<execution>
+			<phase>package</phase>
+			<goals>
+				<!-- By default we will not push the stubs back to SCM,
+				you have to explicitly add it as a goal -->
+				<goal>pushStubsToScm</goal>
+			</goals>
+			<configuration>
+				<!-- We want to pick contracts from a Git repository -->
+				<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
+				</contractsRepositoryUrl>
+				<!-- Example of URL via git protocol -->
+				<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- Example of URL via http protocol -->
+				<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
+				<!-- We reuse the contract dependency section to set up the path
+				to the folder that contains the contract definitions. In our case the
+				path will be /groupId/artifactId/version/contracts -->
+				<contractDependency>
+					<groupId>${project.groupId}</groupId>
+					<artifactId>${project.artifactId}</artifactId>
+					<version>${project.version}</version>
+				</contractDependency>
+				<!-- The mode can't be classpath -->
+				<contractsMode>LOCAL</contractsMode>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		// Base package for generated tests
+	basePackageForTests = "com.example"
+	baseClassMappings {
+		baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
+		baseClassMapping(".*rest.*", "com.example.BeerRestBase")
+	}
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publishStubsToScm {
+	// We want to modify the default set up of the plugin when publish stubs to scm is called
+	customize {
+		// We want to pick contracts from a Git repository
+		contractDependency {
+			stringNotation = "${project.group}:${project.name}:${project.version}"
+		}
+		/*
+		We reuse the contract dependency section to set up the path
+		to the folder that contains the contract definitions. In our case the
+		path will be /groupId/artifactId/version/contracts
+		 */
+		contractRepository {
+			repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
+		}
+		// The mode can't be classpath
+		contractsMode = "LOCAL"
+	}
+}
+
+publish.dependsOn("publishStubsToScm")
+publishToMavenLocal.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Contracts from the default src/test/resources/contracts directory will be picked

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass

    +
    +
      +
    • +

      Git project will be cloned to a temporary directory

      +
    • +
    • +

      The stubs and contracts will be committed in the cloned repository

      +
    • +
    +
    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
Keeping contracts with the producer and stubs in an external repository
+
+

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

+
+
+

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

+
+
+
+
+

3.6.4. Consumer

+
+

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

+
+
+
+
@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/

    +
  • +
  • +

    Stub servers will be started and fed with mappings

    +
  • +
  • +

    Messaging definitions will be read and used in the messaging tests

    +
  • +
+
+
+
+
+

3.7. Can I use the Pact Broker?

+
+

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

+
+
+

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the Pact Converter section.

+
+
+ + + + + +
+ + +Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met. +
+
+
+

3.7.1. Pact Consumer

+
+

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

+
+
+
+

3.7.2. Producer

+
+

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into tests and stubs

    +
  • +
  • +

    The JAR with the stubs gets automatically created as usual

    +
  • +
+
+
+
+

3.7.3. Pact Consumer (Producer Contract approach)

+
+

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

+
+
+

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

+
+
+
Maven
+
+
<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+
Gradle
+
+
dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}
+
+
+
+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into stub definitions

    +
  • +
  • +

    The stub servers will be started and fed with stubs

    +
  • +
+
+
+

For more information about Pact support you can go to +the Using the Pact Stub Downloader section.

+
+
+
+
+

3.8. How can I debug the request/response being sent by the generated tests client?

+
+

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

+
+
+
+
logging.level.org.apache.http.wire=DEBUG
+
+
+
+

3.8.1. How can I debug the mapping/request/response being sent by WireMock?

+
+

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

+
+
+

To turn off this feature just bump WireMock logging to ERROR

+
+
+
+
logging.level.com.github.tomakehurst.wiremock=ERROR
+
+
+
+
+

3.8.2. How can I see what got registered in the HTTP server stub?

+
+

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

+
+
+
+

3.8.3. Can I reference text from file?

+
+

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

+
+
+
+
+
+
+

4. Spring Cloud Contract Verifier Setup

+
+
+

You can set up Spring Cloud Contract Verifier in the following ways:

+
+ +
+

4.1. Gradle Project

+
+

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

4.1.1. Prerequisites

+
+

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

+
+
+ + + + + +
+ + +If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information +
+
+
+
+

4.1.2. Add Gradle Plugin with Dependencies

+
+

To add a Gradle plugin with dependencies, use code similar to this:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}
+
+
+
+
+

4.1.3. Gradle and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}
+
+
+
+

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

4.1.4. Snapshot Versions for Gradle

+
+

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+}
+
+
+
+
+

4.1.5. Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

+
+
+

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

4.1.6. Run the Plugin

+
+

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

+
+
+
+

4.1.7. Default Setup

+
+

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

+
+
+
+
contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}
+
+
+
+
+

4.1.8. Configure Plugin

+
+

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

+
+
+
+
contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}
+
+
+
+
+

4.1.9. Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    +
  • +
  • +

    staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.

    +
  • +
  • +

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.

    +
  • +
  • +

    contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.

    +
  • +
  • +

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

The following properties are used when you want to specify the location of the JAR +containing the contracts:

+
+
+
    +
  • +

    contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.

    +
  • +
  • +

    contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.

    +
  • +
  • +

    contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

4.1.10. Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

+
+
+
+

4.1.11. Different Base Classes for Contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    Provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
packageWithBaseClasses = 'com.example.base'
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
baseClassForTests = "com.example.FooBase"
+baseClassMappings {
+	baseClassMapping('.*/com/.*', 'com.example.ComBase')
+	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
+}
+
+
+
+

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

4.1.12. Invoking Generated Tests

+
+

To ensure that the provider side is compliant with defined contracts, you need to invoke:

+
+
+
+
./gradlew generateContractTests test
+
+
+
+
+

4.1.13. Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

+
+
+
+
$ ./gradlew pushStubsToScm
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

+
+
+
+

4.1.14. Spring Cloud Contract Verifier on the Consumer Side

+
+

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

+
+
+
+
./gradlew generateClientStubs
+
+
+
+ + + + + +
+ + +The stubsOutputDir option has to be set for stub generation to work. +
+
+
+

When present, JSON stubs can be used in automated tests of consuming a service.

+
+
+
+
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}
+
+
+
+

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

+
+
+
+
+

4.2. Maven Project

+
+

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

4.2.1. Add maven plugin

+
+

Add the Spring Cloud Contract BOM in a fashion similar to this:

+
+
+
+
<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>${spring-cloud-release.version}</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>
+
+
+ +
+
+

4.2.2. Maven and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

4.2.3. Snapshot versions for Maven

+
+

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

+
+
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
+

4.2.4. Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

4.2.5. Run plugin

+
+

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

+
+
+
+

4.2.6. Configure plugin

+
+

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>
+
+
+
+
+

4.2.7. Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.

    +
  • +
  • +

    baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

If you want to download your contract definitions from a Maven repository, you can use +the following options:

+
+
+
    +
  • +

    contractDependency: The contract dependency that contains all the packaged contracts.

    +
  • +
  • +

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.

    +
  • +
  • +

    contractsMode: Picks the mode in which stubs will be found and registered

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
  • +

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.

    +
  • +
  • +

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    +
  • +
+
+
+

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

4.2.8. Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}
+
+
+
+

You can also setup the whole context if necessary.

+
+
+
+
import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}
+
+
+
+

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}
+
+
+
+

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

+
+
+
+

4.2.9. Different base classes for contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<packageWithBaseClasses>hello</packageWithBaseClasses>
+	</configuration>
+</plugin>
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<baseClassForTests>com.example.FooBase</baseClassForTests>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*com.*</contractPackageRegex>
+				<baseClassFQN>com.example.TestBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+</plugin>
+
+
+
+

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

4.2.10. Invoking generated tests

+
+

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

+
+
+

For Groovy Spock code, use the following:

+
+
+
+
<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>
+
+
+
+

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

+
+
+
+

4.2.11. Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+

Under Using the SCM Stub Downloader you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

+
+
+
+

4.2.12. Maven Plugin and STS

+
+

If you see the following exception while using STS:

+
+
+
+STS Exception +
+
+
+

When you click on the error marker you should see something like this:

+
+
+
+
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
+
+
+
+

In order to fix this issue, provide the following section in your pom.xml:

+
+
+
+
<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>
+
+
+
+
+

4.2.13. Maven Plugin with Spock Tests

+
+

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

+
+
+

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

+
+
+
+
+
+
+
+

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

+
+
+
+
+
+
+
+
+
+

4.3. Stubs and Transitive Dependencies

+
+

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

+
+
+
+
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...
+
+
+
+

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

+
+
+
    +
  • +

    Mark all application dependencies as optional

    +
  • +
  • +

    Create a separate artifactid for the stubs

    +
  • +
  • +

    Exclude dependencies on the consumer side

    +
  • +
+
+
+

Mark all application dependencies as optional

+
+
+

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

+
+
+

Create a separate artifactid for the stubs

+
+
+

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

+
+
+

Exclude dependencies on the consumer side

+
+
+

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

+
+
+
+

4.4. Scenarios

+
+

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

+
+
+
+
my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy
+
+
+
+

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

+
+
+
    +
  1. +

    login marked as Started pointing to…​

    +
  2. +
  3. +

    showCart marked as Step1 pointing to…​

    +
  4. +
  5. +

    logout marked as Step2 which will close the scenario.

    +
  6. +
+
+
+

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

+
+
+

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

+
+
+
+

4.5. Docker Project

+
+

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

+
+
+ + + + + +
+ + +The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones. +
+
+
+

4.5.1. Short intro to Maven, JARs and Binary storage

+
+

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

+
+
+

Part of the following definitions were taken from the Maven Glossary

+
+
+
    +
  • +

    Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.

    +
  • +
  • +

    Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.

    +
  • +
  • +

    JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.

    +
  • +
  • +

    GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.

    +
  • +
  • +

    Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.

    +
  • +
  • +

    Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

    +
  • +
+
+
+
+

4.5.2. How it works

+
+

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

+
+
+

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

+
+
+
    +
  • +

    generate the contract tests

    +
  • +
  • +

    execute the tests against the provided URL

    +
  • +
  • +

    generate the WireMock stubs

    +
  • +
  • +

    (optional - turned on by default) publish the stubs to a Artifact Manager

    +
  • +
+
+
+
Environment Variables
+
+

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

+
+
+
    +
  • +

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    +
  • +
  • +

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    +
  • +
  • +

    PROJECT_NAME - artifact id. Defaults to example

    +
  • +
  • +

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    +
  • +
  • +

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    +
  • +
  • +

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    +
  • +
  • +

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    +
  • +
+
+
+

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

+
+
+
    +
  • +

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    +
  • +
  • +

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    +
  • +
  • +

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    +
  • +
+
+
+

These environment variables are used when tests are executed:

+
+
+
    +
  • +

    APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)

    +
  • +
  • +

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    +
  • +
  • +

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    +
  • +
+
+
+
+
+

4.5.3. Example of usage

+
+

Let’s take a look at a simple MVC application

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

The contracts are available under /contracts folder.

+
+
+
+

4.5.4. Server side (nodejs)

+
+

Since we want to run tests, we could just execute:

+
+
+
+
$ npm test
+
+
+
+

however, for learning purposes, let’s split it into pieces:

+
+
+
+
# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"
+
+
+
+

What will happen is that via bash scripts:

+
+
+
    +
  • +

    infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.

    +
  • +
  • +

    due to those constraints the contracts also represent the +stateful situation

    +
    +
      +
    • +

      first request is a POST that causes data to get inserted to the database

      +
    • +
    • +

      second request is a GET that returns a list of data with 1 previously inserted element

      +
    • +
    +
    +
  • +
  • +

    the NodeJS application will be started (on port 3000)

    +
  • +
  • +

    contract tests will be generated via Docker and tests +will be executed against the running application

    +
    +
      +
    • +

      the contracts will be taken from /contracts folder.

      +
    • +
    • +

      the output of the test execution is available under +node_modules/spring-cloud-contract/output.

      +
    • +
    +
    +
  • +
  • +

    the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    +
  • +
+
+
+

To see how the client side looks like check out the Stub Runner Docker section.

+
+
+
+
+
+
+

5. Spring Cloud Contract Verifier Messaging

+
+
+

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

+
+
+

5.1. Integrations

+
+

You can use one of the following four integration configurations:

+
+
+
    +
  • +

    Apache Camel

    +
  • +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

+
+
+ + + + + +
+ + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here: +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+
+

5.2. Manual Integration Testing

+
+

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

+
+
+

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

+
+
+
+
@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
+
+
+
+ + + + + +
+ + +If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation. +
+
+
+
+

5.3. Publisher-Side Test Generation

+
+

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5, TestNG or Spock tests.

+
+
+

There are 3 main scenarios that we should take into consideration:

+
+
+
    +
  • +

    Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).

    +
  • +
  • +

    Scenario 2: The input message triggers an output message.

    +
  • +
  • +

    Scenario 3: The input message is consumed and there is no output message.

    +
  • +
+
+
+ + + + + +
+ + +The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms). +
+
+
+

5.3.1. Scenario 1: No Input Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					triggeredBy('bookReturnedTriggered()')
+				}
+				outputMessage {
+					sentTo('activemq:output')
+					body('''{ "bookName" : "foo" }''')
+					headers {
+						header('BOOK-NAME', 'foo')
+						messagingContentType(applicationJson())
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  triggeredBy: bookReturnedTriggered
+outputMessage:
+  sentTo: activemq:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+    contentType: application/json
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// when:
+\t\t\tbookReturnedTriggered();
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+\t\t\tassertThat(response.getHeader("contentType")).isNotNull();
+\t\t\tassertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					'''\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\twhen:
+\t\t\tbookReturnedTriggered()
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+\t\t\tresponse.getHeader("contentType") != null
+\t\t\tresponse.getHeader("contentType").toString() == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+'''
+
+
+
+
+

5.3.2. Scenario 2: Output Triggered by Input

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:input')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+				}
+				outputMessage {
+					sentTo('jms:output')
+					body([
+							bookName: 'foo'
+					])
+					headers {
+						header('BOOK-NAME', 'foo')
+					}
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:input
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+outputMessage:
+  sentTo: jms:output
+  body:
+    bookName: foo
+  headers:
+    BOOK-NAME: foo
+
+
+
+

The following JUnit test is created:

+
+
+
+
					'''\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input");
+
+\t\t// then:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
+\t\t\tassertThat(response).isNotNull();
+
+\t\t// and:
+\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
+\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
+\t}
+
+}
+
+'''
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input")
+
+\t\tthen:
+\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output")
+\t\t\tresponse != null
+
+\t\tand:
+\t\t\tresponse.getHeader("BOOK-NAME") != null
+\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
+\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
+\t}
+
+}
+
+"""
+
+
+
+
+

5.3.3. Scenario 3: No Output Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
			def contractDsl = Contract.make {
+				name "foo"
+				label 'some_label'
+				input {
+					messageFrom('jms:delete')
+					messageBody([
+							bookName: 'foo'
+					])
+					messageHeaders {
+						header('sample', 'header')
+					}
+					assertThat('bookWasDeleted()')
+				}
+			}
+
+
+
+
YAML
+
+
label: some_label
+input:
+  messageFrom: jms:delete
+  messageBody:
+    bookName: 'foo'
+  messageHeaders:
+    sample: header
+  assertThat: bookWasDeleted()
+
+
+
+

The following JUnit test is created:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.inject.Inject;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging;
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
+
+\t@Test
+\tpublic void validate_foo() throws Exception {
+\t\t// given:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t);
+
+\t\t// when:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete");
+\t\t\tbookWasDeleted();
+
+\t}
+
+}
+
+"""
+
+
+
+

And the following Spock test would be created:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import javax.inject.Inject
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
+import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+\t@Inject ContractVerifierMessaging contractVerifierMessaging
+\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
+
+\tdef validate_foo() throws Exception {
+\t\tgiven:
+\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+\t\t\t\t\t'''{"bookName":"foo"}'''
+\t\t\t\t\t\t, headers()
+\t\t\t\t\t\t\t.header("sample", "header")
+\t\t\t)
+
+\t\twhen:
+\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete")
+\t\t\tbookWasDeleted()
+
+\t\tthen:
+\t\t\tnoExceptionThrown()
+\t}
+
+}
+"""
+
+
+
+
+
+

5.4. Consumer Stub Generation

+
+

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

+
+
+

For more information, see Stub Runner for Messaging section.

+
+
+
Maven
+
+
<dependencies>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
+	</dependency>
+
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+		<scope>test</scope>
+	</dependency>
+	<dependency>
+		<groupId>org.springframework.cloud</groupId>
+		<artifactId>spring-cloud-stream-test-support</artifactId>
+		<scope>test</scope>
+	</dependency>
+</dependencies>
+
+<dependencyManagement>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-dependencies</artifactId>
+			<version>Hoxton.BUILD-SNAPSHOT</version>
+			<type>pom</type>
+			<scope>import</scope>
+		</dependency>
+	</dependencies>
+</dependencyManagement>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+
+
+

6. Spring Cloud Contract Stub Runner

+
+
+

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

+
+
+

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

+
+
+

6.1. Snapshot versions

+
+

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

+
+
+
Maven
+
+
<repositories>
+	<repository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+	<repository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</repository>
+</repositories>
+<pluginRepositories>
+	<pluginRepository>
+		<id>spring-snapshots</id>
+		<name>Spring Snapshots</name>
+		<url>https://repo.spring.io/snapshot</url>
+		<snapshots>
+			<enabled>true</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-milestones</id>
+		<name>Spring Milestones</name>
+		<url>https://repo.spring.io/milestone</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+	<pluginRepository>
+		<id>spring-releases</id>
+		<name>Spring Releases</name>
+		<url>https://repo.spring.io/release</url>
+		<snapshots>
+			<enabled>false</enabled>
+		</snapshots>
+	</pluginRepository>
+</pluginRepositories>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		mavenCentral()
+		mavenLocal()
+		maven { url "https://repo.spring.io/snapshot" }
+		maven { url "https://repo.spring.io/milestone" }
+		maven { url "https://repo.spring.io/release" }
+	}
+
+
+
+
+

6.2. Publishing Stubs as JARs

+
+

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

+
+
+ + + + + +
+ + +For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. +
+
+
+
Maven
+
+
<!-- First disable the default jar setup in the properties section -->
+<!-- we don't want the verifier to do a jar for us -->
+<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+
+<!-- Next add the assembly plugin to your build -->
+<!-- we want the assembly plugin to generate the JAR -->
+<plugin>
+	<groupId>org.apache.maven.plugins</groupId>
+	<artifactId>maven-assembly-plugin</artifactId>
+	<executions>
+		<execution>
+			<id>stub</id>
+			<phase>prepare-package</phase>
+			<goals>
+				<goal>single</goal>
+			</goals>
+			<inherited>false</inherited>
+			<configuration>
+				<attach>true</attach>
+				<descriptors>
+					${basedir}/src/assembly/stub.xml
+				</descriptors>
+			</configuration>
+		</execution>
+	</executions>
+</plugin>
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>src/main/java</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/classes</directory>
+			<outputDirectory>/</outputDirectory>
+			<includes>
+				<include>**com/example/model/*.*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
Gradle
+
+
ext {
+	contractsDir = file("mappings")
+	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
+}
+
+// Automatically added by plugin:
+// copyContracts - copies contracts to the output folder from which JAR will be created
+// verifierStubsJar - JAR with a provided stub suffix
+// the presented publication is also added by the plugin but you can modify it as you wish
+
+publishing {
+	publications {
+		stubs(MavenPublication) {
+			artifactId "${project.name}-stubs"
+			artifact verifierStubsJar
+		}
+	}
+}
+
+
+
+
+

6.3. Stub Runner Core

+
+

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +Consumer Driven Contracts.

+
+
+

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. +For messaging, special stub routes are defined.

+
+
+

6.3.1. Retrieving stubs

+
+

You can pick the following options of acquiring stubs

+
+
+
    +
  • +

    Aether based solution that downloads JARs with stubs from Artifactory / Nexus

    +
  • +
  • +

    Classpath scanning solution that searches classpath via pattern to retrieve stubs

    +
  • +
  • +

    Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    +
  • +
+
+
+

The latter example is described in the Custom Stub Runner section.

+
+
+
Stub downloading
+
+

You can control the stub downloading via the stubsMode switch. It picks value from the +StubRunnerProperties.StubsMode enum. You can use the following options

+
+
+
    +
  • +

    StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath

    +
  • +
  • +

    StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)

    +
  • +
  • +

    StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

    +
  • +
+
+
+

Example:

+
+
+
+
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+
+
+
+
+
Classpath scanning
+
+

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH +(or set nothing since CLASSPATH is the default value) then classpath will get scanned. +Let’s look at the following example:

+
+
+
+
@AutoConfigureStubRunner(ids = {
+    "com.example:beer-api-producer:+:stubs:8095",
+    "com.example.foo:bar:1.0.0:superstubs:8096"
+})
+
+
+
+

If you’ve added the dependencies to your classpath

+
+
+
Maven
+
+
<dependency>
+    <groupId>com.example</groupId>
+    <artifactId>beer-api-producer-restdocs</artifactId>
+    <classifier>stubs</classifier>
+    <version>0.0.1-SNAPSHOT</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+<dependency>
+    <groupId>com.example.foo</groupId>
+    <artifactId>bar</artifactId>
+    <classifier>superstubs</classifier>
+    <version>1.0.0</version>
+    <scope>test</scope>
+    <exclusions>
+        <exclusion>
+            <groupId>*</groupId>
+            <artifactId>*</artifactId>
+        </exclusion>
+    </exclusions>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
+    transitive = false
+}
+testCompile("com.example.foo:bar:1.0.0:superstubs") {
+    transitive = false
+}
+
+
+
+

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

+
+
+
    +
  • +

    /META-INF/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /contracts/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
  • +

    /mappings/com.example/beer-api-producer-restdocs/*/.*

    +
  • +
+
+
+

and com.example.foo:bar

+
+
+
    +
  • +

    /META-INF/com.example.foo/bar/*/.*

    +
  • +
  • +

    /contracts/com.example.foo/bar/*/.*

    +
  • +
  • +

    /mappings/com.example.foo/bar/*/.*

    +
  • +
+
+
+ + + + + +
+ + +As you can see you have to explicitly provide the group and artifact ids when packaging the +producer stubs. +
+
+
+

The producer would setup the contracts like this:

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                └── com.example
+                    └── beer-api-producer-restdocs
+                        └── nested
+                            └── contract3.groovy
+
+
+
+

To achieve proper stub packaging.

+
+
+

Or using the Maven assembly plugin or +Gradle Jar task you have to create the following +structure in your stubs jar.

+
+
+
+
└── META-INF
+    └── com.example
+        └── beer-api-producer-restdocs
+            └── 2.0.0
+                ├── contracts
+                │   └── nested
+                │       └── contract2.groovy
+                └── mappings
+                    └── mapping.json
+
+
+
+

By maintaining this structure classpath gets scanned and you can profit from the messaging / +HTTP stubs without the need to download artifacts.

+
+
+
+
Configuring HTTP Server Stubs
+
+

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying +concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). +Sometimes, you need to perform some additional tuning of the stub servers, +that is concrete for the given implementation. To do that, Stub Runner gives you +the httpServerStubConfigurer property that is available in the annotation, +JUnit rule, and is accessible via system properties, where you can provide +your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter +the configuration files for the given HTTP server stub.

+
+
+

Spring Cloud Contract Stub Runner comes with an implementation that you +can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method +you can provide your own, custom configuration for the given stub. The use +case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

+
+
+
WireMockHttpServerStubConfigurer implementation
+
+
@CompileStatic
+static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+	@Override
+	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+			int httpsPort = SocketUtils.findAvailableTcpPort()
+			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+			return httpStubConfiguration
+					.httpsPort(httpsPort)
+		}
+		return httpStubConfiguration
+	}
+}
+
+
+
+

You can then reuse it via the annotation

+
+
+
+
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+
+
+
+

Whenever an https port is found, it will take precedence over the http one.

+
+
+
+
+

6.3.2. Running stubs

+
+
Running using main app
+
+

You can set the following options to the main class:

+
+
+
+
-c, --classifier                Suffix for the jar containing stubs (e.
+                                  g. 'stubs' if the stub jar would
+                                  have a 'stubs' classifier for stubs:
+                                  foobar-stubs ). Defaults to 'stubs'
+                                  (default: stubs)
+--maxPort, --maxp <Integer>     Maximum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  15000 (default: 15000)
+--minPort, --minp <Integer>     Minimum port value to be assigned to
+                                  the WireMock instance. Defaults to
+                                  10000 (default: 10000)
+-p, --password                  Password to user when connecting to
+                                  repository
+--phost, --proxyHost            Proxy host to use for repository
+                                  requests
+--pport, --proxyPort [Integer]  Proxy port to use for repository
+                                  requests
+-r, --root                      Location of a Jar containing server
+                                  where you keep your stubs (e.g. http:
+                                  //nexus.
+                                  net/content/repositories/repository)
+-s, --stubs                     Comma separated list of Ivy
+                                  representation of jars with stubs.
+                                  Eg. groupid:artifactid1,groupid2:
+                                  artifactid2:classifier
+--sm, --stubsMode               Stubs mode to be used. Acceptable values
+                                  [CLASSPATH, LOCAL, REMOTE]
+-u, --username                  Username to user when connecting to
+                                  repository
+
+
+
+
+
HTTP Stubs
+
+

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

+
+
+

Example:

+
+
+
+
{
+    "request": {
+        "method": "GET",
+        "url": "/ping"
+    },
+    "response": {
+        "status": 200,
+        "body": "pong",
+        "headers": {
+            "Content-Type": "text/plain"
+        }
+    }
+}
+
+
+
+
+
Viewing registered mappings
+
+

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

+
+
+

You can also use the mappingsOutputFolder property to dump the mappings to files. + For annotation based approach it would look like this

+
+
+
+
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
+mappingsOutputFolder = "target/outputmappings/")
+
+
+
+

and for the JUnit approach like this:

+
+
+
+
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
+			.repoRoot("https://some_url")
+			.downloadStub("a.b.c", "loanIssuance")
+			.downloadStub("a.b.c:fraudDetectionServer")
+			.withMappingsOutputFolder("target/outputmappings")
+
+
+
+

Then if you check out the folder target/outputmappings you would see the following structure

+
+
+
+
.
+├── fraudDetectionServer_13705
+└── loanIssuance_12255
+
+
+
+

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 +and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) +mappings available for the given server:

+
+
+
+
[{
+  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
+  "request" : {
+    "url" : "/name",
+    "method" : "GET"
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "fraudDetectionServer"
+  },
+  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
+},
+...
+]
+
+
+
+
+
Messaging Stubs
+
+

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

+
+
+
+
+
+

6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

+
+

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very +similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

+
+
+
    +
  • +

    download them

    +
  • +
  • +

    cache them locally

    +
  • +
  • +

    unzip them to a temporary folder

    +
  • +
  • +

    start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port

    +
  • +
  • +

    feed the WireMock server with all JSON files that are valid WireMock definitions

    +
  • +
  • +

    can also send messages (remember to pass an implementation of MessageVerifier interface)

    +
  • +
+
+
+

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. +Check their docs for more information.

+
+
+

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+
+import org.springframework.cloud.contract.spec.Contract;
+
+/**
+ * Contract for finding registered stubs.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubFinder extends StubTrigger {
+
+	/**
+	 * For the given groupId and artifactId tries to find the matching URL of the running
+	 * stub.
+	 * @param groupId - might be null. In that case a search only via artifactId takes
+	 * place
+	 * @param artifactId - artifact id of the stub
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
+
+	/**
+	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
+	 * tries to find the matching URL of the running stub. You can also pass only
+	 * {@code artifactId}.
+	 * @param ivyNotation - Ivy representation of the Maven artifact
+	 * @return URL of a running stub or throws exception if not found
+	 * @throws StubNotFoundException in case of not finding a stub
+	 */
+	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
+
+	/**
+	 * @return all running stubs
+	 */
+	RunningStubs findAllRunningStubs();
+
+	/**
+	 * @return the list of Contracts
+	 */
+	Map<StubConfiguration, Collection<Contract>> getContracts();
+
+}
+
+
+
+

Example of usage in Spock tests:

+
+
+
+
@ClassRule
+@Shared
+StubRunnerRule rule = new StubRunnerRule()
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule")
+
+
+def 'should start WireMock servers'() {
+	expect: 'WireMocks are running'
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+		rule.findStubUrl('loanIssuance') != null
+		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+	and:
+		rule.findAllRunningStubs().isPresent('loanIssuance')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+	and: 'Stubs were registered'
+		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+}
+
+def 'should output mappings to output folder'() {
+	when:
+		def url = rule.findStubUrl('fraudDetectionServer')
+	then:
+		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
+}
+
+
+
+

Example of usage in JUnit tests:

+
+
+
+
	@Test
+	public void should_start_wiremock_servers() throws Exception {
+		// expect: 'WireMocks are running'
+		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isNotNull();
+		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
+		then(rule.findStubUrl(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isNotNull();
+		// and:
+		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs",
+				"fraudDetectionServer")).isTrue();
+		then(rule.findAllRunningStubs().isPresent(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
+						.isTrue();
+		// and: 'Stubs were registered'
+		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
+				.isEqualTo("loanIssuance");
+		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
+				.isEqualTo("fraudDetectionServer");
+	}
+
+	private String httpGet(String url) throws Exception {
+		try (InputStream stream = URI.create(url).toURL().openStream()) {
+			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
+		}
+	}
+
+}
+
+
+
+

JUnit 5 Extension example:

+
+
+
+
// Visible for Junit
+@RegisterExtension
+static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
+		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+		.withMappingsOutputFolder("target/outputmappingsforrule");
+
+@BeforeAll
+@AfterAll
+static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+private static String repoRoot() {
+	try {
+		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
+				.toURI().toString();
+	}
+	catch (Exception e) {
+		return "";
+	}
+}
+
+
+
+

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

+
+
+ + + + + +
+ + +To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the +MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). +If you don’t do this, then whenever you try to send a message an exception will be thrown. +
+
+
+

6.4.1. Maven settings

+
+

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

+
+
+
+

6.4.2. Providing fixed ports

+
+

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

+
+
+
+

6.4.3. Fluent API

+
+

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

+
+
+
+
@ClassRule
+public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
+		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
+		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
+				"loanIssuance")
+		.withPort(12345).downloadStub(
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
+
+@BeforeClass
+@AfterClass
+public static void setupProps() {
+	System.clearProperty("stubrunner.repository.root");
+	System.clearProperty("stubrunner.classifier");
+}
+
+
+
+

You can see that for this example the following test is valid:

+
+
+
+
then(rule.findStubUrl("loanIssuance"))
+		.isEqualTo(URI.create("http://localhost:12345").toURL());
+then(rule.findStubUrl("fraudDetectionServer"))
+		.isEqualTo(URI.create("http://localhost:12346").toURL());
+
+
+
+
+

6.4.4. Stub Runner with Spring

+
+

Sets up Spring configuration of the Stub Runner project.

+
+
+

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads +and registers in WireMock the selected stubs.

+
+
+

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use +its methods as presented below:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
+		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
+		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
+@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
+		httpServerStubConfigurer = HttpsForFraudDetection)
+@ActiveProfiles("test")
+class StubRunnerConfigurationSpec extends Specification {
+
+	@Autowired
+	StubFinder stubFinder
+	@Autowired
+	Environment environment
+	@StubRunnerPort("fraudDetectionServer")
+	int fraudDetectionServerPort
+	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
+	int fraudDetectionServerPortWithGroupId
+	@Value('${foo}')
+	Integer foo
+
+	@BeforeClass
+	@AfterClass
+	void setupProps() {
+		System.clearProperty("stubrunner.repository.root")
+		System.clearProperty("stubrunner.classifier")
+	}
+
+	def 'should start WireMock servers'() {
+		expect: 'WireMocks are running'
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') != null
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
+			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
+			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
+		and:
+			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
+			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
+		and: 'Stubs were registered'
+			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+		and: 'Fraud Detection is an HTTPS endpoint'
+			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
+	}
+
+	def 'should throw an exception when stub is not found'() {
+		when:
+			stubFinder.findStubUrl('nonExistingService')
+		then:
+			thrown(StubNotFoundException)
+		when:
+			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
+		then:
+			thrown(StubNotFoundException)
+	}
+
+	def 'should register started servers as environment variables'() {
+		expect:
+			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
+			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
+		and:
+			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
+			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
+	}
+
+	def 'should be able to interpolate a running stub in the passed test property'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			environment.getProperty("foo", Integer) == fraudPort
+			environment.getProperty("fooWithGroup", Integer) == fraudPort
+			foo == fraudPort
+	}
+
+	@Issue("#573")
+	def 'should be able to retrieve the port of a running stub via an annotation'() {
+		given:
+			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
+		expect:
+			fraudPort > 0
+			fraudDetectionServerPort == fraudPort
+			fraudDetectionServerPortWithGroupId == fraudPort
+	}
+
+	def 'should dump all mappings to a file'() {
+		when:
+			def url = stubFinder.findStubUrl("fraudDetectionServer")
+		then:
+			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
+	}
+
+	@Configuration
+	@EnableAutoConfiguration
+	static class Config {}
+
+	@CompileStatic
+	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
+
+		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
+
+		@Override
+		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
+			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
+				int httpsPort = SocketUtils.findAvailableTcpPort()
+				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
+				return httpStubConfiguration
+						.httpsPort(httpsPort)
+			}
+			return httpStubConfiguration
+		}
+	}
+}
+
+
+
+

for the following configuration file:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids:
+    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
+    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
+    - org.springframework.cloud.contract.verifier.stubs:bootService
+  stubs-mode: remote
+
+
+
+

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. +Below you can find an example of achieving the same result by setting values on the annotation.

+
+
+
+
@AutoConfigureStubRunner(
+		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
+				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
+				"org.springframework.cloud.contract.verifier.stubs:bootService"],
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		repositoryRoot = "classpath:m2repo/repository/")
+
+
+
+

Stub Runner Spring registers environment variables in the following manner +for every registered WireMock server. Example for Stub Runner ids + com.example:foo, com.example:bar.

+
+
+
    +
  • +

    stubrunner.runningstubs.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.foo.port

    +
  • +
  • +

    stubrunner.runningstubs.bar.port

    +
  • +
  • +

    stubrunner.runningstubs.com.example.bar.port

    +
  • +
+
+
+

Which you can reference in your code.

+
+
+

You can also use the @StubRunnerPort annotation to inject the port of a running stub. +Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids +com.example:foo, com.example:bar.

+
+
+
+
@StubRunnerPort("foo")
+int fooPort;
+@StubRunnerPort("com.example:bar")
+int barPort;
+
+
+
+
+
+

6.5. Stub Runner Spring Cloud

+
+

Stub Runner can integrate with Spring Cloud.

+
+
+

For real life examples you can check the

+
+ +
+

6.5.1. Stubbing Service Discovery

+
+

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

+
+
+
    +
  • +

    DiscoveryClient

    +
  • +
  • +

    Ribbon ServerList

    +
  • +
+
+
+

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate +or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

+
+
+

For example this test will pass

+
+
+
+
def 'should make service discovery work'() {
+	expect: 'WireMocks are running'
+		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
+		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
+	and: 'Stubs can be reached via load service discovery'
+		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
+		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
+}
+
+
+
+

for the following configuration file

+
+
+
+
stubrunner:
+  idsToServiceIds:
+    ivyNotation: someValueInsideYourCode
+    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer
+
+
+
+
Test profiles and service discovery
+
+

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) +or Config Server. That’s why you create an additional test configuration in which you want to disable +these features.

+
+
+

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties +via a static block like presented below (example for Eureka)

+
+
+
+
    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
+    static {
+        System.setProperty("eureka.client.enabled", "false");
+        System.setProperty("spring.cloud.config.failFast", "false");
+    }
+
+
+
+
+
+

6.5.2. Additional Configuration

+
+

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. +You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false +You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

+
+
+ + + + + +
+ + +By default all service discovery will be stubbed. That means that regardless of the fact if you have +an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set + stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be + merged with the stubbed ones. +
+
+
+

The default Maven configuration used by Stub Runner can be tweaked either +via the following system properties or environment variables

+
+
+
    +
  • +

    maven.repo.local - path to the custom maven local repository location

    +
  • +
  • +

    org.apache.maven.user-settings - path to custom maven user settings location

    +
  • +
  • +

    org.apache.maven.global-settings - path to maven global settings location

    +
  • +
+
+
+
+
+

6.6. Stub Runner Boot Application

+
+

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +trigger the messaging labels and to access started WireMock servers.

+
+
+

One of the use-cases is to run some smoke (end to end) tests on a deployed application. +You can check out the Spring Cloud Pipelines +project for more information.

+
+
+

6.6.1. How to use it?

+
+
Stub Runner Server
+
+

Just add the

+
+
+
+
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
+
+
+
+

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

+
+
+

For the properties check the Stub Runner Spring section.

+
+
+
+
Stub Runner Server Fat Jar
+
+

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

+
+
+
+
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
+
+
+
+
+
Spring Cloud CLI
+
+

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project you can start Stub Runner Boot by executing spring cloud stubrunner.

+
+
+

In order to pass the configuration just create a stubrunner.yml file in the current working directory +or a subdirectory called config or in ~/.spring-cloud. The file could look like this +(example for running stubs installed locally)

+
+
+
stubrunner.yml
+
+
stubrunner:
+  stubsMode: LOCAL
+  ids:
+    - com.example:beer-api-producer:+:9876
+
+
+
+

and then just call spring cloud stubrunner from your terminal window to start +the Stub Runner server. It will be available at port 8750.

+
+
+
+
+

6.6.2. Endpoints

+
+
HTTP
+
+
    +
  • +

    GET /stubs - returns a list of all running stubs in ivy:integer notation

    +
  • +
  • +

    GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
Messaging
+
+

For Messaging

+
+
+
    +
  • +

    GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation

    +
  • +
  • +

    POST /triggers/{label} - executes a trigger with label

    +
  • +
  • +

    POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    +
  • +
+
+
+
+
+

6.6.3. Example

+
+
+
@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
+@ActiveProfiles("test")
+class StubRunnerBootSpec extends Specification {
+
+	@Autowired
+	StubRunning stubRunning
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
+				new TriggerController(stubRunning))
+	}
+
+	def 'should return a list of running stub servers in "full ivy:port" notation'() {
+		when:
+			String response = RestAssuredMockMvc.get('/stubs').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
+	}
+
+	def 'should return a port on which a [#stubId] stub is running'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
+		then:
+			response.statusCode == 200
+			Integer.valueOf(response.body.asString()) > 0
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
+					   'org.springframework.cloud.contract.verifier.stubs:bootService',
+					   'bootService']
+	}
+
+	def 'should return 404 when missing stub was called'() {
+		when:
+			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
+		then:
+			response.statusCode == 404
+	}
+
+	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
+		when:
+			String response = RestAssuredMockMvc.get('/triggers').body.asString()
+		then:
+			def root = new JsonSlurper().parseText(response)
+			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
+	}
+
+	def 'should trigger a messaging label'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger('delete_book')
+	}
+
+	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
+		given:
+			StubRunning stubRunning = Mock()
+			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
+		when:
+			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
+		then:
+			response.statusCode == 200
+		and:
+			1 * stubRunning.trigger(stubId, 'delete_book')
+		where:
+			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
+	}
+
+	def 'should throw exception when trigger is missing'() {
+		when:
+			RestAssuredMockMvc.post("/triggers/missing_label")
+		then:
+			Exception e = thrown(Exception)
+			e.message.contains("Exception occurred while trying to return [missing_label] label.")
+			e.message.contains("Available labels are")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
+			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
+	}
+
+}
+
+
+
+
+

6.6.4. Stub Runner Boot with Service Discovery

+
+

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? + Let’s assume that you don’t want to deploy 50 microservice to a test environment in order + to check if your application is working fine. You’ve already executed a suite of tests during the build process + but you would also like to ensure that the packaging of your application is fine. What you can do + is to deploy your application to an environment, start it and run a couple of tests on it to see if + it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful + of testing scenarios.

+
+
+

The problem with this approach is such that if you’re doing microservices most likely you’re + using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the + required stubs and register them in a service discovery tool. Let’s take a look at an example of + such a setup with Eureka. Let’s assume that Eureka was already running.

+
+
+
+
@SpringBootApplication
+@EnableStubRunnerServer
+@EnableEurekaClient
+@AutoConfigureStubRunner
+public class StubRunnerBootEurekaExample {
+
+	public static void main(String[] args) {
+		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
+	}
+
+}
+
+
+
+

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient +and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

+
+
+

Now let’s assume that we want to start this application so that the stubs get automatically registered. + We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where + ${SYSTEM_PROPS} would contain the following list of properties

+
+
+
+
* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
+* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
+* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
+* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
+* cloud.contract.verifier.stubs:bootService (3)
+* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
+* someNameThatShouldMapFraudDetectionServer (4)
+*
+* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
+* behaviour where the discovery service is stubbed. That's why the stub registration will
+* be picked (3) - we provide a list of stubs to download (4) - we provide a list of
+
+
+
+

That way your deployed application can send requests to started WireMock servers via the service +discovery. Most likely points 1-3 could be set by default in application.yml cause they are not +likely to change. That way you can provide only the list of stubs to download whenever you start +the Stub Runner Boot.

+
+
+
+
+

6.7. Stubs Per Consumer

+
+

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

+
+
+ + + + + +
+ + +This approach also allows you to immediately know which consumer is using which part of your API. +You can remove part of a response that your API produces and you can see which of your autogenerated tests +fails. If none fails then you can safely delete that part of the response cause nobody is using it. +
+
+
+

Let’s look at the following example for contract defined for the producer called producer. +There are 2 consumers: foo-consumer and bar-consumer.

+
+
+

Consumer foo-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       foo: "foo"
+    }
+}
+
+
+
+

Consumer bar-service

+
+
+
+
request {
+   url '/foo'
+   method GET()
+}
+response {
+    status OK()
+    body(
+       bar: "bar"
+    }
+}
+
+
+
+

You can’t produce for the same request 2 different responses. That’s why you can properly package the +contracts and then profit from the stubsPerConsumer feature.

+
+
+

On the producer side the consumers can have a folder that contains contracts related only to them. +By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that +correspond to the consumer application’s name. In other words we’ll scan the path of every stub and +if it contains the subfolder with name of the consumer in the path only then will it get registered.

+
+
+

On the foo producer side the contracts would look like this

+
+
+
+
.
+└── contracts
+    ├── bar-consumer
+    │   ├── bookReturnedForBar.groovy
+    │   └── shouldCallBar.groovy
+    └── foo-consumer
+        ├── bookReturnedForFoo.groovy
+        └── shouldCallFoo.groovy
+
+
+
+

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer +Or set the test as follows:

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the +src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

Or set the consumer name explicitly

+
+
+
+
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
+@SpringBootTest
+@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
+		repositoryRoot = "classpath:m2repo/repository/",
+		consumerName = "foo-consumer",
+		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		stubsPerConsumer = true)
+class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
+...
+}
+
+
+
+

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the +src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

+
+
+

You can check out issue 224 for more +information about the reasons behind this change.

+
+
+
+

6.8. Common

+
+

This section briefly describes common properties, including:

+
+ +
+

6.8.1. Common Properties for JUnit and Spring

+
+

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

+
+
+

6.8.2. Stub Runner Stubs IDs

+
+

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

+
+
+
+
groupId:artifactId:version:classifier:port
+
+
+
+

Note that version, classifier and port are optional.

+
+
+
    +
  • +

    If you do not provide the port, a random one will be picked.

    +
  • +
  • +

    If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).

    +
  • +
  • +

    If you do not provide the version, then the + will be passed and the latest one is +downloaded.

    +
  • +
+
+
+

port means the port of the WireMock server.

+
+
+ + + + + +
+ + +Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here. +
+
+
+
+
+

6.9. Stub Runner Docker

+
+

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

+
+
+

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here Docker Project.

+
+
+

6.9.1. How to use it

+
+

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

+
+
+
+

6.9.2. Example of client side usage in a non JVM project

+
+

We’d like to use the stubs created in this Server side (nodejs) step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

Let’s run the Stub Runner Boot application with the stubs.

+
+
+
+
# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
+
+
+
+

What’s happening is that

+
+
+
    +
  • +

    a standalone Stub Runner application got started

    +
  • +
  • +

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    +
  • +
  • +

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    +
  • +
  • +

    after a while Stub Runner will be running on port 8083

    +
  • +
  • +

    and the stubs will be running at port 9876

    +
  • +
+
+
+

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

+
+
+
+
# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
+
+
+
+ + + + + +
+ + +If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" +
+
+
+
+
+
+
+

7. Stub Runner for Messaging

+
+
+

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

+
+
+
    +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Apache Camel

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

It also provides entry points to integrate with any other solution on the market.

+
+
+ + + + + +
+ + +If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP. +
+
+
+

7.1. Stub triggering

+
+

To trigger a message, use the StubTrigger interface:

+
+
+
+
package org.springframework.cloud.contract.stubrunner;
+
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Contract for triggering stub messages.
+ *
+ * @author Marcin Grzejszczak
+ */
+public interface StubTrigger {
+
+	/**
+	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
+	 * You can use only {@code artifactId} too.
+	 *
+	 * Feature related to messaging.
+	 * @param ivyNotation ivy notation of a stub
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String ivyNotation, String labelName);
+
+	/**
+	 * Triggers an event by a given label.
+	 *
+	 * Feature related to messaging.
+	 * @param labelName name of the label to trigger
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger(String labelName);
+
+	/**
+	 * Triggers all possible events.
+	 *
+	 * Feature related to messaging.
+	 * @return true - if managed to run a trigger
+	 */
+	boolean trigger();
+
+	/**
+	 * Feature related to messaging.
+	 * @return a mapping of ivy notation of a dependency to all the labels it has.
+	 */
+	Map<String, Collection<String>> labels();
+
+}
+
+
+
+

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

+
+
+

StubTrigger gives you the following options to trigger a message:

+
+ +
+

7.1.1. Trigger by Label

+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+
+

7.1.2. Trigger by Group and Artifact Ids

+
+
+
stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')
+
+
+
+
+

7.1.3. Trigger by Artifact Ids

+
+
+
stubFinder.trigger('streamService', 'return_book_1')
+
+
+
+
+

7.1.4. Trigger All Messages

+
+
+
stubFinder.trigger()
+
+
+
+
+
+

7.2. Stub Runner Camel

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +For the provided artifacts it will automatically download the stubs and register the required +routes.

+
+
+

7.2.1. Adding it to the project

+
+

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.2.2. Disabling the functionality

+
+

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

+
+
+
+

7.2.3. Examples

+
+
Stubs structure
+
+

Let us assume that we have the following Maven repository with a deployed stubs for the +camelService application.

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── camelService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── camelService-0.0.1-SNAPSHOT.pom
+                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

And the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Let’s consider the following contracts (let' number it with 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and number 2

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('jms:input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('jms:output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
+
Scenario 1 (no input message)
+
+

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])
+
+
+
+

Next we’ll want to listen to the output of the message sent to jms:output

+
+
+
+
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
+
+
+
+

And the received message would pass the following assertions

+
+
+
+
receivedMessage != null
+assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
+receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you it’s enough to just send a message to the jms:output destination.

+
+
+
+
producerTemplate.
+		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])
+
+
+
+
+
+
+

7.3. Stub Runner Integration

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes.

+
+
+

7.3.1. Adding the Runner to the Project

+
+

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.3.2. Disabling the functionality

+
+

If you need to disable this functionality, set the +stubrunner.integration.enabled=false property.

+
+
+

Assume that you have the following Maven repository with deployed stubs for the +integrationService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── integrationService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
+                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input {
+		triggeredBy('bookReturnedTriggered()')
+	}
+	outputMessage {
+		sentTo('output')
+		body('''{ "bookName" : "foo" }''')
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('input')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+

and the following Spring Integration Route:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			 xmlns:beans="http://www.springframework.org/schema/beans"
+			 xmlns="http://www.springframework.org/schema/integration"
+			 xsi:schemaLocation="http://www.springframework.org/schema/beans
+			https://www.springframework.org/schema/beans/spring-beans.xsd
+			http://www.springframework.org/schema/integration
+			http://www.springframework.org/schema/integration/spring-integration.xsd">
+
+
+	<!-- REQUIRED FOR TESTING -->
+	<bridge input-channel="output"
+			output-channel="outputTest"/>
+
+	<channel id="outputTest">
+		<queue/>
+	</channel>
+
+</beans:beans>
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTigger interface, as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message would pass the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')
+
+
+
+

To listen to the output of the message sent to output:

+
+
+
+
Message<?> receivedMessage = messaging.receive('outputTest')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the input destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

7.4. Stub Runner Stream

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes.

+
+
+ + + + + +
+ + +If Stub Runner’s integration with Stream the messageFrom or sentTo Strings +are resolved first as a destination of a channel and no such destination exists, the +destination is resolved as a channel name. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream remember, to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support. +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+

7.4.1. Adding the Runner to the Project

+
+

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

+
+
+
+

7.4.2. Disabling the functionality

+
+

If you need to disable this functionality, set the stubrunner.stream.enabled=false +property.

+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +streamService application:

+
+
+
+
└── .m2
+    └── repository
+        └── io
+            └── codearte
+                └── accurest
+                    └── stubs
+                        └── streamService
+                            ├── 0.0.1-SNAPSHOT
+                            │   ├── streamService-0.0.1-SNAPSHOT.pom
+                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
+                            │   └── maven-metadata-local.xml
+                            └── maven-metadata-local.xml
+
+
+
+

Further assume the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── repository
+    ├── accurest
+    │   ├── bookDeleted.groovy
+    │   ├── bookReturned1.groovy
+    │   └── bookReturned2.groovy
+    └── mappings
+
+
+
+

Consider the following contracts (numbered 1):

+
+
+
+
Contract.make {
+	label 'return_book_1'
+	input { triggeredBy('bookReturnedTriggered()') }
+	outputMessage {
+		sentTo('returnBook')
+		body('''{ "bookName" : "foo" }''')
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider 2:

+
+
+
+
Contract.make {
+	label 'return_book_2'
+	input {
+		messageFrom('bookStorage')
+		messageBody([
+				bookName: 'foo'
+		])
+		messageHeaders { header('sample', 'header') }
+	}
+	outputMessage {
+		sentTo('returnBook')
+		body([
+				bookName: 'foo'
+		])
+		headers { header('BOOK-NAME', 'foo') }
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner.repositoryRoot: classpath:m2repo/repository/
+stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
+stubrunner.stubs-mode: remote
+spring:
+  cloud:
+    stream:
+      bindings:
+        output:
+          destination: returnBook
+        input:
+          destination: bookStorage
+
+server:
+  port: 0
+
+debug: true
+
+
+
+

These examples lend themselves to three scenarios:

+
+ +
+
Scenario 1 (no input message)
+
+

To trigger a message via the return_book_1 label, use the StubTrigger interface as +follows:

+
+
+
+
stubFinder.trigger('return_book_1')
+
+
+
+

To listen to the output of the message sent to a channel whose destination is +returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 2 (output triggered by input)
+
+

Since the route is set for you, you can send a message to the bookStorage +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')
+
+
+
+

To listen to the output of the message sent to returnBook:

+
+
+
+
Message<?> receivedMessage = messaging.receive('returnBook')
+
+
+
+

The received message passes the following assertions:

+
+
+
+
receivedMessage != null
+assertJsons(receivedMessage.payload)
+receivedMessage.headers.get('BOOK-NAME') == 'foo'
+
+
+
+
+
Scenario 3 (input with no output)
+
+

Since the route is set for you, you can send a message to the output +destination:

+
+
+
+
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
+
+
+
+
+
+
+

7.5. Stub Runner Spring AMQP

+
+

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes.

+
+
+

The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a RabbitTemplate on the application context and +uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application.

+
+
+

On the message consumer side, the stub runner considers all @RabbitListener annotated +endpoints and all SimpleMessageListenerContainer objects on the application context.

+
+
+

As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners.

+
+
+

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey +messaging header.

+
+
+

7.5.1. Adding the Runner to the Project

+
+

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property stubrunner.amqp.enabled=true. Remember to annotate your test class +with @AutoConfigureStubRunner.

+
+
+ + + + + +
+ + +If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the stubrunner.stream.enabled=false and +stubrunner.integration.enabled=false properties. +
+
+
+

Assume that you have the following Maven repository with a deployed stubs for the +spring-cloud-contract-amqp-test application.

+
+
+
+
└── .m2
+    └── repository
+        └── com
+            └── example
+                └── spring-cloud-contract-amqp-test
+                    ├── 0.4.0-SNAPSHOT
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
+                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
+                    │   └── maven-metadata-local.xml
+                    └── maven-metadata-local.xml
+
+
+
+

Further assume that the stubs contain the following structure:

+
+
+
+
├── META-INF
+│   └── MANIFEST.MF
+└── contracts
+    └── shouldProduceValidPersonData.groovy
+
+
+
+

Consider the following contract:

+
+
+
+
Contract.make {
+	// Human readable description
+	description 'Should produce valid person data'
+	// Label by means of which the output message can be triggered
+	label 'contract-test.person.created.event'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('createPerson()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo 'contract-test.exchange'
+		headers {
+			header('contentType': 'application/json')
+			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
+		}
+		// the body of the output message
+		body([
+				id  : $(consumer(9), producer(regex("[0-9]+"))),
+				name: "me"
+		])
+	}
+}
+
+
+
+

Now consider the following Spring configuration:

+
+
+
+
stubrunner:
+  repositoryRoot: classpath:m2repo/repository/
+  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
+  stubs-mode: remote
+  amqp:
+    enabled: true
+server:
+  port: 0
+
+
+
+
Triggering the message
+
+

To trigger a message using the contract above, use the StubTrigger interface as +follows:

+
+
+
+
stubTrigger.trigger("contract-test.person.created.event")
+
+
+
+

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner +integration looks for bindings related to this exchange.

+
+
+
+
@Bean
+public Binding binding() {
+	return BindingBuilder.bind(new Queue("test.queue"))
+			.to(new DirectExchange("contract-test.exchange")).with("#");
+}
+
+
+
+

The binding definition binds the queue test.queue. As a result, the following listener +definition is matched and invoked with the contract message.

+
+
+
+
@Bean
+public SimpleMessageListenerContainer simpleMessageListenerContainer(
+		ConnectionFactory connectionFactory,
+		MessageListenerAdapter listenerAdapter) {
+	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
+	container.setConnectionFactory(connectionFactory);
+	container.setQueueNames("test.queue");
+	container.setMessageListener(listenerAdapter);
+
+	return container;
+}
+
+
+
+

Also, the following annotated listener matches and is invoked:

+
+
+
+
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
+		exchange = @Exchange(value = "contract-test.exchange",
+				ignoreDeclarationExceptions = "true")))
+public void handlePerson(Person person) {
+	this.person = person;
+}
+
+
+
+ + + + + +
+ + +The message is directly handed over to the onMessage method of the +MessageListener associated with the matching SimpleMessageListenerContainer. +
+
+
+
+
Spring AMQP Test Configuration
+
+

In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock ConnectionFactory.

+
+
+

To disable the mocked ConnectionFactory, set the following property: +stubrunner.amqp.mockConnection=false

+
+
+
+
stubrunner:
+  amqp:
+    mockConnection: false
+
+
+
+
+
+
+
+
+

8. Contract DSL

+
+
+

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

+
+
+

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

+
+
+ + + + + +
+ + +Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }. +
+
+
+ + + + + +
+ + +Spring Cloud Contract supports defining multiple contracts in a single file. +
+
+
+

The following is a complete example of a Groovy contract definition:

+
+
+
+
+
+
+
+

The following is a complete example of a YAML contract definition:

+
+
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+ + + + + +
+ + +You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert +
+
+
+

8.1. Limitations

+
+ + + + + +
+ + +Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. +
+
+
+ + + + + +
+ + +The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration. +
+
+
+ + + + + +
+ + +Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation. +
+
+
+
+

8.2. Common Top-Level elements

+
+

The following sections describe the most common top-level elements:

+
+ +
+

8.2.1. Description

+
+

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

+
+
+
Groovy DSL
+
+
			org.springframework.cloud.contract.spec.Contract.make {
+				description('''
+given:
+	An input
+when:
+	Sth happens
+then:
+	Output
+''')
+			}
+
+
+
+
YAML
+
+
description: Some description
+name: some name
+priority: 8
+ignored: true
+request:
+  url: /foo
+  queryParameters:
+    a: b
+    b: c
+  method: PUT
+  headers:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+
+
+
+
+

8.2.2. Name

+
+

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

+
+
+ + + + + +
+ + +You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. +
+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	name("some_special_name")
+}
+
+
+
+
YAML
+
+
name: some name
+
+
+
+
+

8.2.3. Ignoring Contracts

+
+

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	ignored()
+}
+
+
+
+
YAML
+
+
ignored: true
+
+
+
+
+

8.2.4. Passing Values from Files

+
+

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json
+
+
+
+

Further assume that your contract is as follows:

+
+
+
Groovy DSL
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		method('PUT')
+		headers {
+			contentType(applicationJson())
+		}
+		body(file("request.json"))
+		url("/1")
+	}
+	response {
+		status OK()
+		body(file("response.json"))
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /foo
+  bodyFromFile: request.json
+response:
+  status: 200
+  bodyFromFile: response.json
+
+
+
+

Further assume that the JSON files is as follows:

+
+
+

request.json

+
+
+
+
{
+  "status": "REQUEST"
+}
+
+
+
+

response.json

+
+
+
+
{
+  "status": "RESPONSE"
+}
+
+
+
+

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

+
+
+

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	request {
+		url("/1")
+		method(PUT())
+		headers {
+			contentType(applicationOctetStream())
+		}
+		body(fileAsBytes("request.pdf"))
+	}
+	response {
+		status 200
+		body(fileAsBytes("response.pdf"))
+		headers {
+			contentType(applicationOctetStream())
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  url: /1
+  method: PUT
+  headers:
+    Content-Type: application/octet-stream
+  bodyFromFileAsBytes: request.pdf
+response:
+  status: 200
+  bodyFromFileAsBytes: response.pdf
+  headers:
+    Content-Type: application/octet-stream
+
+
+
+ + + + + +
+ + +You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +
+
+
+
+

8.2.5. HTTP Top-Level Elements

+
+

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	// Definition of HTTP request part of the contract
+	// (this can be a valid request or invalid depending
+	// on type of contract being specified).
+	request {
+		method GET()
+		url "/foo"
+		//...
+	}
+
+	// Definition of HTTP response part of the contract
+	// (a service implementing this contract should respond
+	// with following response after receiving request
+	// specified in "request" part above).
+	response {
+		status 200
+		//...
+	}
+
+	// Contract priority, which can be used for overriding
+	// contracts (1 is highest). Priority is optional.
+	priority 1
+}
+
+
+
+
YAML
+
+
priority: 8
+request:
+...
+response:
+...
+
+
+
+ + + + + +
+ + +If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10. +
+
+
+
+
+

8.3. Request

+
+

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		// HTTP request method (GET/POST/PUT/DELETE).
+		method 'GET'
+
+		// Path component of request URL is specified as follows.
+		urlPath('/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
method: PUT
+url: /foo
+
+
+
+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+
+		// Specifying `url` and `urlPath` in one contract is illegal.
+		url('http://localhost:8888/users')
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  urlPath: /foo
+
+
+
+

request may contain query parameters.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+
+		urlPath('/users') {
+
+			// Each parameter is specified in form
+			// `'paramName' : paramValue` where parameter value
+			// may be a simple literal or one of matcher functions,
+			// all of which are used in this example.
+			queryParameters {
+
+				// If a simple literal is used as value
+				// default matcher function is used (equalTo)
+				parameter 'limit': 100
+
+				// `equalTo` function simply compares passed value
+				// using identity operator (==).
+				parameter 'filter': equalTo("email")
+
+				// `containing` function matches strings
+				// that contains passed substring.
+				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
+
+				// `matching` function tests parameter
+				// against passed regular expression.
+				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
+
+				// `notMatching` functions tests if parameter
+				// does not match passed regular expression.
+				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
+			}
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+  queryParameters:
+    a: b
+    b: c
+  headers:
+    foo: bar
+    fooReq: baz
+  cookies:
+    foo: bar
+    fooReq: baz
+  body:
+    foo: bar
+  matchers:
+    body:
+      - path: $.foo
+        type: by_regex
+        value: bar
+    headers:
+      - key: foo
+        regex: bar
+response:
+  status: 200
+  fixedDelayMilliseconds: 1000
+  headers:
+    foo2: bar
+    foo3: foo33
+    fooRes: baz
+  body:
+    foo2: bar
+    foo3: baz
+    nullValue: null
+  matchers:
+    body:
+      - path: $.foo2
+        type: by_regex
+        value: bar
+      - path: $.foo3
+        type: by_command
+        value: executeMe($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+    headers:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        command: andMeToo($it)
+    cookies:
+      - key: foo2
+        regex: bar
+      - key: foo3
+        predefined:
+
+
+
+

request may contain additional request headers, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each header is added in form `'Header-Name' : 'Header-Value'`.
+		// there are also some helper methods
+		headers {
+			header 'key': 'value'
+			contentType(applicationJson())
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+headers:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain additional request cookies, as shown in the following example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
+		// there are also some helper methods
+		cookies {
+			cookie 'key': 'value'
+			cookie('another_key', 'another_value')
+		}
+
+		//...
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+cookies:
+  foo: bar
+  fooReq: baz
+
+
+
+

request may contain a request body:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+
+		// Currently only JSON format of request body is supported.
+		// Format will be determined from a header or body's content.
+		body '''{ "login" : "john", "name": "John The Contract" }'''
+	}
+
+	response {
+		//...
+		status 200
+	}
+}
+
+
+
+
YAML
+
+
request:
+...
+body:
+  foo: bar
+
+
+
+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: PUT
+  url: /multipart
+  headers:
+    Content-Type: multipart/form-data;boundary=AaB03x
+  multipart:
+    params:
+      # key (parameter name), value (parameter value) pair
+      formParameter: '"formParameterValue"'
+      someBooleanParameter: true
+    named:
+      - paramName: file
+        fileName: filename.csv
+        fileContent: file content
+  matchers:
+    multipart:
+      params:
+        - key: formParameter
+          regex: ".+"
+        - key: someBooleanParameter
+          predefined: any_boolean
+      named:
+        - paramName: file
+          fileName:
+            predefined: non_empty
+          fileContent:
+            predefined: non_empty
+response:
+  status: 200
+
+
+
+

In the preceding example, we define parameters in either of two ways:

+
+
+
Groovy DSL
+
    +
  • +

    Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).

    +
  • +
  • +

    By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

    +
  • +
+
+
+
YAML
+
    +
  • +

    The multipart parameters are set via multipart.params section

    +
  • +
  • +

    The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields

    +
  • +
  • +

    The dynamic bits can be set via the matchers.multipart section

    +
    +
      +
    • +

      for parameters use the params section that can accept +regex or a predefined regular expression

      +
    • +
    • +

      for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

      +
    • +
    +
    +
  • +
+
+
+

From this contract, the generated test is as follows:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+

The WireMock stub is as follows:

+
+
+
+
			'''
+{
+  "request" : {
+	"url" : "/multipart",
+	"method" : "PUT",
+	"headers" : {
+	  "Content-Type" : {
+		"matches" : "multipart/form-data;boundary=AaB03x.*"
+	  }
+	},
+	"bodyPatterns" : [ {
+		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
+  		}, {
+    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
+  		}, {
+	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
+	} ]
+  },
+  "response" : {
+	"status" : 200,
+	"transformers" : [ "response-template", "foo-transformer" ]
+  }
+}
+	'''
+
+
+
+
+

8.4. Response

+
+

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		//...
+		method GET()
+		url "/foo"
+	}
+	response {
+		// Status code sent by the server
+		// in response to request specified above.
+		status OK()
+	}
+}
+
+
+
+
YAML
+
+
response:
+...
+status: 200
+
+
+
+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

+
+
+ + + + + +
+ + +Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400. +
+
+
+
+

8.5. Dynamic properties

+
+

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

+
+
+

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

+
+
+ + + + + +
+ + +Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information. +
+
+
+

For YAML you can only use the matchers section.

+
+
+

8.5.1. Dynamic properties inside the body

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

+
+
+
+
value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

The following example shows how to set dynamic properties with $():

+
+
+
+
$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

+
+
+
+

8.5.2. Regular expressions

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

+
+
+

Make sure that regex matches a whole region of a sequence as internally a call to +Pattern.matches() +is called. For instance, abc pattern doesn’t match aabc string but .abc does. +There are several additional known limitations as well.

+
+
+

The following example shows how to use regular expressions to write a request:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method('GET')
+		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
+	}
+	response {
+		status OK()
+		body(
+				id: $(anyNumber()),
+				surname: $(
+						consumer('Kowalsky'),
+						producer(regex('[a-zA-Z]+'))
+				),
+				name: 'Jan',
+				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
+				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
+						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
+				)
+		)
+		headers {
+			header 'Content-Type': 'text/plain'
+		}
+	}
+}
+
+
+
+

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url value(consumer(regex('/foo/[0-9]{5}')))
+		body([
+				requestElement: $(consumer(regex('[0-9]{5}')))
+		])
+		headers {
+			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
+		}
+	}
+	response {
+		status OK()
+		body([
+				responseElement: $(producer(regex('[0-9]{7}')))
+		])
+		headers {
+			contentType("application/vnd.fraud.v1+json")
+		}
+	}
+}
+
+
+
+

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

+
+
+

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

+
+
+
+
protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
+
+protected static final Pattern ALPHA_NUMERIC = Pattern.compile("[a-zA-Z0-9]+");
+
+protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile("[\\p{L}]*");
+
+protected static final Pattern NUMBER = Pattern.compile("-?(\\d*\\.\\d+|\\d+)");
+
+protected static final Pattern INTEGER = Pattern.compile("-?(\\d+)");
+
+protected static final Pattern POSITIVE_INT = Pattern.compile("([1-9]\\d*)");
+
+protected static final Pattern DOUBLE = Pattern.compile("-?(\\d*\\.\\d+)");
+
+protected static final Pattern HEX = Pattern.compile("[a-fA-F0-9]+");
+
+protected static final Pattern IP_ADDRESS = Pattern.compile(
+		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
+
+protected static final Pattern HOSTNAME_PATTERN = Pattern
+		.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
+
+protected static final Pattern EMAIL = Pattern
+		.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
+
+protected static final Pattern URL = UrlHelper.URL;
+
+protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
+
+protected static final Pattern UUID = Pattern
+		.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
+
+protected static final Pattern ANY_DATE = Pattern
+		.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+
+protected static final Pattern ANY_DATE_TIME = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern ANY_TIME = Pattern
+		.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+
+protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
+
+protected static final Pattern NON_BLANK = Pattern.compile("^\\s*\\S[\\S\\s]*");
+
+protected static final Pattern ISO8601_WITH_OFFSET = Pattern.compile(
+		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d{3})?(Z|[+-][01]\\d:[0-5]\\d)");
+
+protected static Pattern anyOf(String... values) {
+	return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$')
+			.collect(Collectors.joining("|")));
+}
+
+public static String multipartParam(Object name, Object value) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"\r\n(Content-Type: .*\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ value + "\r\n--\\1.*";
+}
+
+public static String multipartFile(Object name, Object filename, Object content,
+		Object contentType) {
+	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+			+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
+			+ toContentType(contentType)
+			+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+			+ content + "\r\n--\\1.*";
+}
+
+private static String toContentType(Object contentType) {
+	if (contentType == null) {
+		return ".*";
+	}
+	if (contentType instanceof RegexProperty) {
+		return ((RegexProperty) contentType).pattern();
+	}
+	return contentType.toString();
+}
+
+public RegexProperty onlyAlphaUnicode() {
+	return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
+}
+
+public RegexProperty alphaNumeric() {
+	return new RegexProperty(ALPHA_NUMERIC).asString();
+}
+
+public RegexProperty number() {
+	return new RegexProperty(NUMBER).asDouble();
+}
+
+public RegexProperty positiveInt() {
+	return new RegexProperty(POSITIVE_INT).asInteger();
+}
+
+public RegexProperty anyBoolean() {
+	return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
+}
+
+public RegexProperty anInteger() {
+	return new RegexProperty(INTEGER).asInteger();
+}
+
+public RegexProperty aDouble() {
+	return new RegexProperty(DOUBLE).asDouble();
+}
+
+public RegexProperty ipAddress() {
+	return new RegexProperty(IP_ADDRESS).asString();
+}
+
+public RegexProperty hostname() {
+	return new RegexProperty(HOSTNAME_PATTERN).asString();
+}
+
+public RegexProperty email() {
+	return new RegexProperty(EMAIL).asString();
+}
+
+public RegexProperty url() {
+	return new RegexProperty(URL).asString();
+}
+
+public RegexProperty httpsUrl() {
+	return new RegexProperty(HTTPS_URL).asString();
+}
+
+public RegexProperty uuid() {
+	return new RegexProperty(UUID).asString();
+}
+
+public RegexProperty isoDate() {
+	return new RegexProperty(ANY_DATE).asString();
+}
+
+public RegexProperty isoDateTime() {
+	return new RegexProperty(ANY_DATE_TIME).asString();
+}
+
+public RegexProperty isoTime() {
+	return new RegexProperty(ANY_TIME).asString();
+}
+
+
+
+

In your contract, you can use it as shown in the following example:

+
+
+
+
Contract dslWithOptionalsInString = Contract.make {
+	priority 1
+	request {
+		method POST()
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123"))),
+				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
+		)
+	}
+}
+
+
+
+

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

+
+
+
+
+
+
+
+

and this is an example of how you can reference those methods:

+
+
+
+
Contract contractDsl = Contract.make {
+	name "foo"
+	label 'trigger_event'
+	input {
+		triggeredBy('toString()')
+	}
+	outputMessage {
+		sentTo 'topic.rateablequote'
+		body([
+				alpha            : $(anyAlphaUnicode()),
+				number           : $(anyNumber()),
+				anInteger        : $(anyInteger()),
+				positiveInt      : $(anyPositiveInt()),
+				aDouble          : $(anyDouble()),
+				aBoolean         : $(aBoolean()),
+				ip               : $(anyIpAddress()),
+				hostname         : $(anyHostname()),
+				email            : $(anyEmail()),
+				url              : $(anyUrl()),
+				httpsUrl         : $(anyHttpsUrl()),
+				uuid             : $(anyUuid()),
+				date             : $(anyDate()),
+				dateTime         : $(anyDateTime()),
+				time             : $(anyTime()),
+				iso8601WithOffset: $(anyIso8601WithOffset()),
+				nonBlankString   : $(anyNonBlankString()),
+				nonEmptyString   : $(anyNonEmptyString()),
+				anyOf            : $(anyOf('foo', 'bar'))
+		])
+	}
+}
+
+
+
+
Limitations
+
+ + + + + +
+ + +Due to certain limitations of Xeger library that generates string out of +regex, do not use $ and ^ signs in your regex if you rely on automatic +generation. Issue 899 +
+
+
+ + + + + +
+ + +Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). +It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. +Issue 900 +
+
+
+
+
+

8.5.3. Passing Optional Parameters

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

+
+
+
    +
  • +

    STUB side of the Request

    +
  • +
  • +

    TEST side of the Response

    +
  • +
+
+
+

The following example shows how to provide optional parameters:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	priority 1
+	name "optionals"
+	request {
+		method 'POST'
+		url '/users/password'
+		headers {
+			contentType(applicationJson())
+		}
+		body(
+				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
+				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
+		)
+	}
+	response {
+		status 404
+		headers {
+			header 'Content-Type': 'application/json'
+		}
+		body(
+				code: value(consumer("123123"), producer(optional("123123")))
+		)
+	}
+}
+
+
+
+

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

+
+
+

If you use Spock for, the following test would be generated from the previous example:

+
+
+
+
					"""\
+package com.example
+
+import com.jayway.jsonpath.DocumentContext
+import com.jayway.jsonpath.JsonPath
+import spock.lang.Specification
+import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
+import io.restassured.response.ResponseOptions
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
+import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
+
+@SuppressWarnings("rawtypes")
+class FooSpec extends Specification {
+
+\tdef validate_optionals() throws Exception {
+\t\tgiven:
+\t\t\tMockMvcRequestSpecification request = given()
+\t\t\t\t\t.header("Content-Type", "application/json")
+\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
+
+\t\twhen:
+\t\t\tResponseOptions response = given().spec(request)
+\t\t\t\t\t.post("/users/password")
+
+\t\tthen:
+\t\t\tresponse.statusCode() == 404
+\t\t\tresponse.header("Content-Type") == 'application/json'
+
+\t\tand:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
+\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
+\t}
+
+}
+"""
+
+
+
+

The following stub would also be generated:

+
+
+
+
					'''
+{
+  "request" : {
+	"url" : "/users/password",
+	"method" : "POST",
+	"bodyPatterns" : [ {
+	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
+	}, {
+	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
+	} ],
+	"headers" : {
+	  "Content-Type" : {
+		"equalTo" : "application/json"
+	  }
+	}
+  },
+  "response" : {
+	"status" : 404,
+	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
+	"headers" : {
+	  "Content-Type" : "application/json"
+	}
+  },
+  "priority" : 1
+}
+'''
+
+
+
+
+

8.5.4. Executing Custom Methods on the Server Side

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

+
+
+
+
+
+
+
+

The following code shows the base class portion of the test case:

+
+
+
+
abstract class BaseMockMvcSpec extends Specification {
+
+	def setup() {
+		RestAssuredMockMvc.standaloneSetup(new PairIdController())
+	}
+
+	void isProperCorrelationId(Integer correlationId) {
+		assert correlationId == 123456
+	}
+
+	void isEmpty(String value) {
+		assert value == null
+	}
+
+}
+
+
+
+ + + + + +
+ + +You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need. +
+
+
+

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

+
+
+
    +
  • +

    String: If you point to a String value in the JSON.

    +
  • +
  • +

    JSONArray: If you point to a List in the JSON.

    +
  • +
  • +

    Map: If you point to a Map in the JSON.

    +
  • +
  • +

    Number: If you point to Integer, Double etc. in the JSON.

    +
  • +
  • +

    Boolean: If you point to a Boolean in the JSON.

    +
  • +
+
+
+

In the request part of the contract, you can specify that the body should be taken from +a method.

+
+
+ + + + + +
+ + +You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it. +
+
+
+

The following example shows how to read an object from JSON:

+
+
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		url '/something'
+		body(
+				$(c('foo'), p(execute('hashCode()')))
+		)
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+
+

8.5.5. Referencing the Request from the Response

+
+

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

+
+
+

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

+
+
+
    +
  • +

    fromRequest().url(): Returns the request URL and query parameters.

    +
  • +
  • +

    fromRequest().query(String key): Returns the first query parameter with a given name.

    +
  • +
  • +

    fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.

    +
  • +
  • +

    fromRequest().path(): Returns the full path.

    +
  • +
  • +

    fromRequest().path(int index): Returns the nth path element.

    +
  • +
  • +

    fromRequest().header(String key): Returns the first header with a given name.

    +
  • +
  • +

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    +
  • +
  • +

    fromRequest().body(): Returns the full request body.

    +
  • +
  • +

    fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

    +
  • +
+
+
+

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

+
+
+
    +
  • +

    {{{ request.url }}}: Returns the request URL and query parameters.

    +
  • +
  • +

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    +
  • +
  • +

    {{{ request.path }}}: Returns the full path.

    +
  • +
  • +

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}

    +
  • +
  • +

    {{{ request.headers.key }}}: Returns the first header with a given name.

    +
  • +
  • +

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    +
  • +
  • +

    {{{ request.body }}}: Returns the full request body.

    +
  • +
  • +

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    +
  • +
+
+
+

Consider the following contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
request:
+  method: GET
+  url: /api/v1/xxxx
+  queryParameters:
+    foo:
+      - bar
+      - bar2
+  headers:
+    Authorization:
+      - secret
+      - secret2
+  body:
+    foo: bar
+    baz: 5
+response:
+  status: 200
+  headers:
+    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
+  body:
+    url: "{{{ request.url }}}"
+    path: "{{{ request.path }}}"
+    pathIndex: "{{{ request.path.1 }}}"
+    param: "{{{ request.query.foo }}}"
+    paramIndex: "{{{ request.query.foo.1 }}}"
+    authorization: "{{{ request.headers.Authorization.0 }}}"
+    authorization2: "{{{ request.headers.Authorization.1 }}"
+    fullBody: "{{{ request.body }}}"
+    responseFoo: "{{{ jsonpath this '$.foo' }}}"
+    responseBaz: "{{{ jsonpath this '$.baz' }}}"
+    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"
+
+
+
+

Running a JUnit test generation leads to a test that resembles the following example:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
+
+
+
+

As you can see, elements from the request have been properly referenced in the response.

+
+
+

The generated WireMock stub should resemble the following example:

+
+
+
+
{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+
+
+
+

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

+
+
+
+
{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
+
+
+
+ + + + + +
+ + +This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions: +
+
+
+
    +
  • +

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    +
  • +
  • +

    jsonpath: For a given parameter, find an object in the request body.

    +
  • +
+
+
+
+

8.5.6. Registering Your Own WireMock Extension

+
+

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

+
+
+
+
org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
+org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
+org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter
+
+
+
+

The following is an example of a custom extension:

+
+
+
TestWireMockExtensions.groovy
+
+
/*
+ * Copyright 2013-2019 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cloud.contract.verifier.dsl.wiremock
+
+import com.github.tomakehurst.wiremock.extension.Extension
+
+/**
+ * Extension that registers the default transformer and the custom one
+ */
+class TestWireMockExtensions implements WireMockExtensions {
+	@Override
+	List<Extension> extensions() {
+		return [
+				new DefaultResponseTransformer(),
+				new CustomExtension()
+		]
+	}
+}
+
+class CustomExtension implements Extension {
+
+	@Override
+	String getName() {
+		return "foo-transformer"
+	}
+}
+
+
+
+ + + + + +
+ + +Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it. +
+
+
+
+

8.5.7. Dynamic Properties in the Matchers Sections

+
+

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

+
+
+

You can use the bodyMatchers section for two reasons:

+
+
+
    +
  • +

    Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.

    +
  • +
  • +

    Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

    +
  • +
+
+
+

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

+
+
+
Groovy DSL
+
    +
  • +

    For the stubs(in tests on the Consumer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      +
    • +
    • +

      byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.

      +
    • +
    +
    +
  • +
  • +

    For the verification(in generated tests on the Producer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.

      +
    • +
    • +

      byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.

      +
    • +
    • +

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      +
    • +
    • +

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      +
      +
        +
      • +

        String: If you point to a String value.

        +
      • +
      • +

        JSONArray: If you point to a List.

        +
      • +
      • +

        Map: If you point to a Map.

        +
      • +
      • +

        Number: If you point to Integer, Double, or other kind of number.

        +
      • +
      • +

        Boolean: If you point to a Boolean.

        +
      • +
      +
      +
    • +
    • +

      byNull(): The value taken from the response via the provided JSON Path must be null

      +
    • +
    +
    +
  • +
+
+
+
YAML
+

Please read the Groovy section for detailed explanation of +what the types mean

+
+
+

For YAML the structure of a matcher looks like this

+
+
+
+
- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string
+
+
+
+

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

+
+
+
+
- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode
+
+
+
+

Below you can find the allowed list of `type`s.

+
+
+
    +
  • +

    For stubMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    For testMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    • +

      by_command

      +
    • +
    • +

      by_null

      +
    • +
    +
    +
  • +
+
+
+

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

+
+
+
    +
  • +

    as_integer

    +
  • +
  • +

    as_double

    +
  • +
  • +

    as_float,

    +
  • +
  • +

    as_long

    +
  • +
  • +

    as_short

    +
  • +
  • +

    as_boolean

    +
  • +
  • +

    as_string

    +
  • +
+
+
+

Consider the following example:

+
+
+
Groovy DSL
+
+
Contract contractDsl = Contract.make {
+	request {
+		method 'GET'
+		urlPath '/get'
+		body([
+				duck                : 123,
+				alpha               : 'abc',
+				number              : 123,
+				aBoolean            : true,
+				date                : '2017-01-01',
+				dateTime            : '2017-01-01T01:23:45',
+				time                : '01:02:34',
+				valueWithoutAMatcher: 'foo',
+				valueWithTypeMatch  : 'string',
+				key                 : [
+						'complex.key': 'foo'
+				]
+		])
+		bodyMatchers {
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			jsonPath('$.duck', byEquality())
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+		}
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status OK()
+		body([
+				duck                 : 123,
+				alpha                : 'abc',
+				number               : 123,
+				positiveInteger      : 1234567890,
+				negativeInteger      : -1234567890,
+				positiveDecimalNumber: 123.4567890,
+				negativeDecimalNumber: -123.4567890,
+				aBoolean             : true,
+				date                 : '2017-01-01',
+				dateTime             : '2017-01-01T01:23:45',
+				time                 : "01:02:34",
+				valueWithoutAMatcher : 'foo',
+				valueWithTypeMatch   : 'string',
+				valueWithMin         : [
+						1, 2, 3
+				],
+				valueWithMax         : [
+						1, 2, 3
+				],
+				valueWithMinMax      : [
+						1, 2, 3
+				],
+				valueWithMinEmpty    : [],
+				valueWithMaxEmpty    : [],
+				key                  : [
+						'complex.key': 'foo'
+				],
+				nullValue            : null
+		])
+		bodyMatchers {
+			// asserts the jsonpath value against manual regex
+			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
+			// asserts the jsonpath value against the provided value
+			jsonPath('$.duck', byEquality())
+			// asserts the jsonpath value against some default regex
+			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
+			jsonPath('$.alpha', byEquality())
+			jsonPath('$.number', byRegex(number()).asInteger())
+			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
+			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
+			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
+			// asserts vs inbuilt time related regex
+			jsonPath('$.date', byDate())
+			jsonPath('$.dateTime', byTimestamp())
+			jsonPath('$.time', byTime())
+			// asserts that the resulting type is the same as in response body
+			jsonPath('$.valueWithTypeMatch', byType())
+			jsonPath('$.valueWithMin', byType {
+				// results in verification of size of array (min 1)
+				minOccurrence(1)
+			})
+			jsonPath('$.valueWithMax', byType {
+				// results in verification of size of array (max 3)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinMax', byType {
+				// results in verification of size of array (min 1 & max 3)
+				minOccurrence(1)
+				maxOccurrence(3)
+			})
+			jsonPath('$.valueWithMinEmpty', byType {
+				// results in verification of size of array (min 0)
+				minOccurrence(0)
+			})
+			jsonPath('$.valueWithMaxEmpty', byType {
+				// results in verification of size of array (max 0)
+				maxOccurrence(0)
+			})
+			// will execute a method `assertThatValueIsANumber`
+			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
+			jsonPath("\$.['key'].['complex.key']", byEquality())
+			jsonPath('$.nullValue', byNull())
+		}
+		headers {
+			contentType(applicationJson())
+			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
+		}
+	}
+}
+
+
+
+
YAML
+
+
request:
+  method: GET
+  urlPath: /get/1
+  headers:
+    Content-Type: application/json
+  cookies:
+    foo: 2
+    bar: 3
+  queryParameters:
+    limit: 10
+    offset: 20
+    filter: 'email'
+    sort: name
+    search: 55
+    age: 99
+    name: John.Doe
+    email: 'bob@email.com'
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    key:
+      "complex.key": 'foo'
+    nullValue: null
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+  matchers:
+    url:
+      regex: /get/[0-9]
+      # predefined:
+      # execute a method
+      #command: 'equals($it)'
+    queryParameters:
+      - key: limit
+        type: equal_to
+        value: 20
+      - key: offset
+        type: containing
+        value: 20
+      - key: sort
+        type: equal_to
+        value: name
+      - key: search
+        type: not_matching
+        value: '^[0-9]{2}$'
+      - key: age
+        type: not_matching
+        value: '^\\w*$'
+      - key: name
+        type: matching
+        value: 'John.*'
+      - key: hello
+        type: absent
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: "$.['key'].['complex.key']"
+        type: by_equality
+      - path: $.nullvalue
+        type: by_null
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+response:
+  status: 200
+  cookies:
+    foo: 1
+    bar: 2
+  body:
+    duck: 123
+    alpha: "abc"
+    number: 123
+    aBoolean: true
+    date: "2017-01-01"
+    dateTime: "2017-01-01T01:23:45"
+    time: "01:02:34"
+    valueWithoutAMatcher: "foo"
+    valueWithTypeMatch: "string"
+    valueWithMin:
+      - 1
+      - 2
+      - 3
+    valueWithMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinMax:
+      - 1
+      - 2
+      - 3
+    valueWithMinEmpty: []
+    valueWithMaxEmpty: []
+    key:
+      'complex.key': 'foo'
+    nulValue: null
+  matchers:
+    headers:
+      - key: Content-Type
+        regex: "application/json.*"
+    cookies:
+      - key: foo
+        regex: '[0-9]'
+      - key: bar
+        command: 'equals($it)'
+    body:
+      - path: $.duck
+        type: by_regex
+        value: "[0-9]{3}"
+      - path: $.duck
+        type: by_equality
+      - path: $.alpha
+        type: by_regex
+        predefined: only_alpha_unicode
+      - path: $.alpha
+        type: by_equality
+      - path: $.number
+        type: by_regex
+        predefined: number
+      - path: $.aBoolean
+        type: by_regex
+        predefined: any_boolean
+      - path: $.date
+        type: by_date
+      - path: $.dateTime
+        type: by_timestamp
+      - path: $.time
+        type: by_time
+      - path: $.valueWithTypeMatch
+        type: by_type
+      - path: $.valueWithMin
+        type: by_type
+        minOccurrence: 1
+      - path: $.valueWithMax
+        type: by_type
+        maxOccurrence: 3
+      - path: $.valueWithMinMax
+        type: by_type
+        minOccurrence: 1
+        maxOccurrence: 3
+      - path: $.valueWithMinEmpty
+        type: by_type
+        minOccurrence: 0
+      - path: $.valueWithMaxEmpty
+        type: by_type
+        maxOccurrence: 0
+      - path: $.duck
+        type: by_command
+        value: assertThatValueIsANumber($it)
+      - path: $.nullValue
+        type: by_null
+        value: null
+  headers:
+    Content-Type: application/json
+
+
+
+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

+
+
+

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

+
+
+
    +
  • +

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    +
  • +
  • +

    For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.

    +
  • +
  • +

    For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.

    +
  • +
  • +

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

    +
  • +
+
+
+

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
+
+
+
+ + + + + +
+ + +Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. +
+
+
+

The resulting WireMock stub is in the following example:

+
+
+
+
					'''
+{
+  "request" : {
+    "urlPath" : "/get",
+    "method" : "POST",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
+    }, {
+      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.duck == 123)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
+    }, {
+      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
+    }, {
+      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
+    "headers" : {
+      "Content-Type" : "application/json"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+'''
+
+
+
+ + + + + +
+ + +If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection. +
+
+
+

Consider the following example:

+
+
+
+
Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}
+
+
+
+

The preceding code leads to creating the following test (the code block shows only the assertion section):

+
+
+
+
and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
+
+
+
+

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

+
+
+
+
+

8.6. JAX-RS Support

+
+

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

+
+
+

In order to use JAX-RS mode, use the following settings:

+
+
+
+
testMode == 'JAXRSCLIENT'
+
+
+
+

The following example shows a generated test API:

+
+
+
+
					"""\
+package com.example;
+
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.junit.Rule;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Response;
+
+import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
+import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static javax.ws.rs.client.Entity.*;
+
+@SuppressWarnings("rawtypes")
+public class FooTest {
+\tWebTarget webTarget;
+
+\t@Test
+\tpublic void validate_() throws Exception {
+
+\t\t// when:
+\t\t\tResponse response = webTarget
+\t\t\t\t\t\t\t.path("/users")
+\t\t\t\t\t\t\t.queryParam("limit", "10")
+\t\t\t\t\t\t\t.queryParam("offset", "20")
+\t\t\t\t\t\t\t.queryParam("filter", "email")
+\t\t\t\t\t\t\t.queryParam("sort", "name")
+\t\t\t\t\t\t\t.queryParam("search", "55")
+\t\t\t\t\t\t\t.queryParam("age", "99")
+\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
+\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
+\t\t\t\t\t\t\t.request()
+\t\t\t\t\t\t\t.build("GET")
+\t\t\t\t\t\t\t.invoke();
+\t\t\tString responseAsString = response.readEntity(String.class);
+
+\t\t// then:
+\t\t\tassertThat(response.getStatus()).isEqualTo(200);
+
+\t\t// and:
+\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
+\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
+\t}
+
+}
+
+"""
+
+
+
+
+

8.7. Async Support

+
+

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}
+
+
+
+
YAML
+
+
response:
+    async: true
+
+
+
+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}
+
+
+
+
YAML
+
+
response:
+    fixedDelayMilliseconds: 1000
+
+
+
+
+

8.8. Working with Context Paths

+
+

Spring Cloud Contract supports context paths.

+
+
+ + + + + +
+ + +The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

+
+
+

Consider the following contract:

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'GET'
+		url '/my-context-path/url'
+	}
+	response {
+		status OK()
+	}
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured:

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.springframework.boot.web.server.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+class ContextPathTestingBaseClass {
+
+	@LocalServerPort int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost";
+		RestAssured.port = this.port;
+	}
+}
+
+
+
+

If you do it this way:

+
+
+
    +
  • +

    All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).

    +
  • +
  • +

    Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

    +
  • +
+
+
+
+

8.9. Working with WebFlux

+
+

Spring Cloud Contract offers two ways of working with WebFlux.

+
+
+

8.9.1. WebFlux with WebTestClient

+
+

One of them is via the WebTestClient mode.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'WEBTESTCLIENT'
+}
+
+
+
+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

+
+
+
+
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}
+
+
+
+
+

8.9.2. WebFlux with Explicit mode

+
+

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured for Web Flux:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(classes = BeerRestBase.Config.class,
+		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+		properties = "server.port=0")
+public abstract class BeerRestBase {
+
+    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+@Configuration
+@EnableAutoConfiguration
+static class Config {
+
+	@Bean
+	PersonCheckingService personCheckingService()  {
+		return personToCheck -> personToCheck.age >= 20;
+	}
+
+	@Bean
+	ProducerController producerController() {
+		return new ProducerController(personCheckingService());
+	}
+}
+
+}
+
+
+
+
+
+

8.10. XML Support for REST

+
+

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

+
+
+

Here is an example of a Groovy DSL contract with XML response body:

+
+
+
+
					Contract.make {
+						request {
+							method GET()
+							urlPath '/get'
+							headers {
+								contentType(applicationXml())
+							}
+						}
+						response {
+							status(OK())
+							headers {
+								contentType(applicationXml())
+							}
+							body """
+<test>
+<duck type='xtype'>123</duck>
+<alpha>abc</alpha>
+<list>
+<elem>abc</elem>
+<elem>def</elem>
+<elem>ghi</elem>
+</list>
+<number>123</number>
+<aBoolean>true</aBoolean>
+<date>2017-01-01</date>
+<dateTime>2017-01-01T01:23:45</dateTime>
+<time>01:02:34</time>
+<valueWithoutAMatcher>foo</valueWithoutAMatcher>
+<key><complex>foo</complex></key>
+</test>"""
+							bodyMatchers {
+								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
+								xPath('/test/duck/text()', byCommand('equals($it)'))
+								xPath('/test/duck/xxx', byNull())
+								xPath('/test/duck/text()', byEquality())
+								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
+								xPath('/test/alpha/text()', byEquality())
+								xPath('/test/number/text()', byRegex(number()))
+								xPath('/test/date/text()', byDate())
+								xPath('/test/dateTime/text()', byTimestamp())
+								xPath('/test/time/text()', byTime())
+								xPath('/test/*/complex/text()', byEquality())
+								xPath('/test/duck/@type', byEquality())
+							}
+						}
+					}
+
+
+
+

And below is an example of a YAML contract with XML request and response bodies:

+
+
+
+
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
+
+
+
+

Here is an example of an automatically generated test for XML response body:

+
+
+
+
@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}
+
+
+
+
+

8.11. Messaging Top-Level Elements

+
+

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

+
+ +
+

8.11.1. Output Triggered by a Method

+
+

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	// Human readable description
+	description 'Some description'
+	// Label by means of which the output message can be triggered
+	label 'some_label'
+	// input to the contract
+	input {
+		// the contract will be triggered by a method
+		triggeredBy('bookReturnedTriggered()')
+	}
+	// output message of the contract
+	outputMessage {
+		// destination to which the output message will be sent
+		sentTo('output')
+		// the body of the output message
+		body('''{ "bookName" : "foo" }''')
+		// the headers of the output message
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+input:
+  # the contract will be triggered by a method
+  triggeredBy: bookReturnedTriggered()
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

+
+
+
+

8.11.2. Output Triggered by a Message

+
+

The output message can be triggered by receiving a message, as shown in the following +example:

+
+
+
Groovy DSL
+
+
def dsl = Contract.make {
+	description 'Some Description'
+	label 'some_label'
+	// input is a message
+	input {
+		// the message was received from this destination
+		messageFrom('input')
+		// has the following body
+		messageBody([
+				bookName: 'foo'
+		])
+		// and the following headers
+		messageHeaders {
+			header('sample', 'header')
+		}
+	}
+	outputMessage {
+		sentTo('output')
+		body([
+				bookName: 'foo'
+		])
+		headers {
+			header('BOOK-NAME', 'foo')
+		}
+	}
+}
+
+
+
+
YAML
+
+
# Human readable description
+description: Some description
+# Label by means of which the output message can be triggered
+label: some_label
+# input is a message
+input:
+  messageFrom: input
+  # has the following body
+  messageBody:
+    bookName: 'foo'
+  # and the following headers
+  messageHeaders:
+    sample: 'header'
+# output message of the contract
+outputMessage:
+  # destination to which the output message will be sent
+  sentTo: output
+  # the body of the output message
+  body:
+    bookName: foo
+  # the headers of the output message
+  headers:
+    BOOK-NAME: foo
+
+
+
+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

+
+
+
+

8.11.3. Consumer/Producer

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. +
+
+
+

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

+
+
+
+
					Contract.make {
+				name "foo"
+						label 'some_label'
+						input {
+							messageFrom value(consumer('jms:output'), producer('jms:input'))
+							messageBody([
+									bookName: 'foo'
+							])
+							messageHeaders {
+								header('sample', 'header')
+							}
+						}
+						outputMessage {
+							sentTo $(consumer('jms:input'), producer('jms:output'))
+							body([
+									bookName: 'foo'
+							])
+						}
+					}
+
+
+
+
+

8.11.4. Common

+
+

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

+
+
+
+
+

8.12. Multiple Contracts in One File

+
+

You can define multiple contracts in one file. Such a contract might resemble the +following example:

+
+
+
Groovy DSL
+
+
import org.springframework.cloud.contract.spec.Contract
+
+[
+	Contract.make {
+		name("should post a user")
+		request {
+			method 'POST'
+			url('/users/1')
+		}
+		response {
+			status OK()
+		}
+	},
+	Contract.make {
+		request {
+			method 'POST'
+			url('/users/2')
+		}
+		response {
+			status OK()
+		}
+	}
+]
+
+
+
+
YAML
+
+
---
+name: should post a user
+request:
+  method: POST
+  url: /users/1
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/2
+response:
+  status: 200
+---
+request:
+  method: POST
+  url: /users/3
+response:
+  status: 200
+
+
+
+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

+
+
+
+
package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}
+
+
+
+

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

+
+
+

The generated stubs is shown in the following example:

+
+
+
+
should post a user.json
+1_WithList.json
+
+
+
+

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

+
+
+ + + + + +
+ + +As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful. +
+
+
+
+

8.13. Generating Spring REST Docs snippets from the contracts

+
+

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
+	<scope>test</scope>
+</dependency>
+<dependency>
+	<groupId>org.springframework.restdocs</groupId>
+	<artifactId>spring-restdocs-mockmvc</artifactId>
+	<optional>true</optional>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
+
+
+
+

Next you need to make some changes to your base class like the following example.

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.context.WebApplicationContext;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = Application.class)
+public abstract class FraudBaseWithWebAppSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Autowired
+	private WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName()))
+				.build());
+	}
+
+	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
+		assert rejectionReason == null;
+	}
+
+}
+
+
+
+

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

+
+
+
+
package com.example.fraud;
+
+import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import org.springframework.restdocs.JUnitRestDocumentation;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
+import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
+
+public abstract class FraudBaseWithStandaloneSetup {
+
+	private static final String OUTPUT = "target/generated-snippets";
+
+	@Rule
+	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
+
+	@Rule
+	public TestName testName = new TestName();
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
+				.standaloneSetup(new FraudDetectionController())
+				.apply(documentationConfiguration(this.restDocumentation))
+				.alwaysDo(document(
+						getClass().getSimpleName() + "_" + testName.getMethodName())));
+	}
+
+}
+
+
+
+ + + + + +
+ + +You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. +
+
+
+
+
+
+

9. Customization

+
+
+ + + + + +
+ + +This section is valid only for Groovy DSL +
+
+
+

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

+
+
+

9.1. Extending the DSL

+
+

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

+
+
+
    +
  • +

    Creating a JAR with reusable classes.

    +
  • +
  • +

    Referencing of these classes in the DSLs.

    +
  • +
+
+
+

You can find the full example +here.

+
+
+

9.1.1. Common JAR

+
+

The following examples show three classes that can be reused in the DSLs.

+
+
+

PatternUtils contains functions used by both the consumer and the producer.

+
+
+
+
package com.example;
+
+import java.util.regex.Pattern;
+
+/**
+ * If you want to use {@link Pattern} directly in your tests
+ * then you can create a class resembling this one. It can
+ * contain all the {@link Pattern} you want to use in the DSL.
+ *
+ * <pre>
+ * {@code
+ * request {
+ *     body(
+ *         [ age: $(c(PatternUtils.oldEnough()))]
+ *     )
+ * }
+ * </pre>
+ *
+ * Notice that we're using both {@code $()} for dynamic values
+ * and {@code c()} for the consumer side.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class PatternUtils {
+
+	public static String tooYoung() {
+		//remove::start[]
+		return "[0-1][0-9]";
+		//remove::end[return]
+	}
+
+	public static Pattern oldEnough() {
+		//remove::start[]
+		return Pattern.compile("[2-9][0-9]");
+		//remove::end[return]
+	}
+
+	/**
+	 * Makes little sense but it's just an example ;)
+	 */
+	public static Pattern ok() {
+		//remove::start[]
+		return Pattern.compile("OK");
+		//remove::end[return]
+	}
+}
+//end::impl[]
+
+
+
+

ConsumerUtils contains functions used by the consumer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the consumer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you can have a regular expression.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you have to have a concrete value.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ConsumerUtils {
+	/**
+	 * Consumer side property. By using the {@link ClientDslProperty}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * request {
+	 *     body(
+	 *         [ age: $(ConsumerUtils.oldEnough())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 *
+	 * @author Marcin Grzejszczak
+	 */
+	public static ClientDslProperty oldEnough() {
+		//remove::start[]
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
+		//remove::end[return]
+	}
+
+}
+//end::impl[]
+
+
+
+

ProducerUtils contains functions used by the producer.

+
+
+
+
package com.example;
+
+import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
+
+/**
+ * DSL Properties passed to the DSL from the producer's perspective.
+ * That means that on the input side {@code Request} for HTTP
+ * or {@code Input} for messaging you have to have a concrete value.
+ * On the {@code Response} for HTTP or {@code Output} for messaging
+ * you can have a regular expression.
+ *
+ * @author Marcin Grzejszczak
+ */
+//tag::impl[]
+public class ProducerUtils {
+
+	/**
+	 * Producer side property. By using the {@link ProducerUtils}
+	 * you can omit most of boilerplate code from the perspective
+	 * of dynamic values. Example
+	 *
+	 * <pre>
+	 * {@code
+	 * response {
+	 *     body(
+	 *         [ status: $(ProducerUtils.ok())]
+	 *     )
+	 * }
+	 * </pre>
+	 *
+	 * That way it's in the implementation that we decide what value we will pass to the consumer
+	 * and which one to the producer.
+	 */
+	public static ServerDslProperty ok() {
+		// this example is not the best one and
+		// theoretically you could just pass the regex instead of `ServerDslProperty` but
+		// it's just to show some new tricks :)
+		return new ServerDslProperty( PatternUtils.ok(), "OK");
+	}
+}
+//end::impl[]
+
+
+
+
+

9.1.2. Adding the Dependency to the Project

+
+

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

+
+
+
+

9.1.3. Test the Dependency in the Project’s Dependencies

+
+

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

+
+
+
Maven
+
+
<dependency>
+	<groupId>com.example</groupId>
+	<artifactId>beer-common</artifactId>
+	<version>${project.version}</version>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")
+
+
+
+
+

9.1.4. Test a Dependency in the Plugin’s Dependencies

+
+

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example</packageWithBaseClasses>
+		<baseClassMappings>
+			<baseClassMapping>
+				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
+				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
+			</baseClassMapping>
+		</baseClassMappings>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>com.example</groupId>
+			<artifactId>beer-common</artifactId>
+			<version>${project.version}</version>
+			<scope>compile</scope>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"
+
+
+
+
+

9.1.5. Referencing classes in DSLs

+
+

You can now reference your classes in your DSL, as shown in the following example:

+
+
+
+
package contracts.beer.rest
+
+import com.example.ConsumerUtils
+import com.example.ProducerUtils
+import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+	description("""
+Represents a successful scenario of getting a beer
+
+```
+given:
+	client is old enough
+when:
+	he applies for a beer
+then:
+	we'll grant him the beer
+```
+
+""")
+	request {
+		method 'POST'
+		url '/check'
+		body(
+				age: $(ConsumerUtils.oldEnough())
+		)
+		headers {
+			contentType(applicationJson())
+		}
+	}
+	response {
+		status 200
+		body("""
+			{
+				"status": "${value(ProducerUtils.ok())}"
+			}
+			""")
+		headers {
+			contentType(applicationJson())
+		}
+	}
+}
+
+
+
+ + + + + +
+ + +You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. +
+
+
+
+
+
+
+

10. Using the Pluggable Architecture

+
+
+

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

+
+
+

10.1. Custom Contract Converter

+
+

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

+
+
+
+
package org.springframework.cloud.contract.spec;
+
+import java.io.File;
+import java.util.Collection;
+
+/**
+ * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
+ * {@link Contract} to {@code T}.
+ *
+ * @param <T> - type to which we want to convert the contract
+ * @author Marcin Grzejszczak
+ * @since 1.1.0
+ */
+public interface ContractConverter<T> extends ContractStorer<T> {
+
+	/**
+	 * Should this file be accepted by the converter. Can use the file extension to check
+	 * if the conversion is possible.
+	 * @param file - file to be considered for conversion
+	 * @return - {@code true} if the given implementation can convert the file
+	 */
+	boolean isAccepted(File file);
+
+	/**
+	 * Converts the given {@link File} to its {@link Contract} representation.
+	 * @param file - file to convert
+	 * @return - {@link Contract} representation of the file
+	 */
+	Collection<Contract> convertFrom(File file);
+
+	/**
+	 * Converts the given {@link Contract} to a {@link T} representation.
+	 * @param contract - the parsed contract
+	 * @return - {@link T} the type to which we do the conversion
+	 */
+	T convertTo(Collection<Contract> contract);
+
+}
+
+
+
+

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

+
+
+ + + + + +
+ + +Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation. +
+
+
+

The following example shows a typical spring.factories file:

+
+
+
+
org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter
+
+
+
+

10.1.1. Pact Converter

+
+

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

+
+
+

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

+
+
+
    +
  • +

    to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    +
  • +
+
+
+
+

10.1.2. Pact Contract

+
+

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

+
+
+
+
{
+  "provider": {
+    "name": "Provider"
+  },
+  "consumer": {
+    "name": "Consumer"
+  },
+  "interactions": [
+    {
+      "description": "",
+      "request": {
+        "method": "PUT",
+        "path": "/fraudcheck",
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "clientId": "1234567890",
+          "loanAmount": 99999
+        },
+        "generators": {
+          "body": {
+            "$.clientId": {
+              "type": "Regex",
+              "regex": "[0-9]{10}"
+            }
+          }
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.clientId": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "[0-9]{10}"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      },
+      "response": {
+        "status": 200,
+        "headers": {
+          "Content-Type": "application/vnd.fraud.v1+json"
+        },
+        "body": {
+          "fraudCheckStatus": "FRAUD",
+          "rejectionReason": "Amount too high"
+        },
+        "matchingRules": {
+          "header": {
+            "Content-Type": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
+                }
+              ],
+              "combine": "AND"
+            }
+          },
+          "body": {
+            "$.fraudCheckStatus": {
+              "matchers": [
+                {
+                  "match": "regex",
+                  "regex": "FRAUD"
+                }
+              ],
+              "combine": "AND"
+            }
+          }
+        }
+      }
+    }
+  ],
+  "metadata": {
+    "pact-specification": {
+      "version": "3.0.0"
+    },
+    "pact-jvm": {
+      "version": "3.5.13"
+    }
+  }
+}
+
+
+
+

The remainder of this section about using Pact refers to the preceding file.

+
+
+
+

10.1.3. Pact for Producers

+
+

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

+
+
+
Maven
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+	</configuration>
+	<dependencies>
+		<dependency>
+			<groupId>org.springframework.cloud</groupId>
+			<artifactId>spring-cloud-contract-pact</artifactId>
+			<version>${spring-cloud-contract.version}</version>
+		</dependency>
+	</dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"
+
+
+
+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}
+
+
+
+

The corresponding generated stub might be as follows:

+
+
+
+
{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}
+
+
+
+
+

10.1.4. Pact for Consumers

+
+

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

+
+
+
Maven
+
+
<dependency>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-pact</artifactId>
+	<scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-contract-pact"
+
+
+
+
+
+

10.2. Using the Custom Test Generator

+
+

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

+
+
+

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.builder;
+
+import java.nio.file.Path;
+import java.util.Collection;
+
+import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
+import org.springframework.cloud.contract.verifier.file.ContractMetadata;
+
+/**
+ * Builds a single test.
+ *
+ * @since 1.1.0
+ */
+public interface SingleTestGenerator {
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param className - the name of the generated test class
+	 * @param classPackage - the name of the package in which the test class should be
+	 * stored
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
+	 */
+	@Deprecated
+	String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles, String className,
+			String classPackage, String includedDirectoryRelativePath);
+
+	/**
+	 * Creates contents of a single test class in which all test scenarios from the
+	 * contract metadata should be placed.
+	 * @param properties - properties passed to the plugin
+	 * @param listOfFiles - list of parsed contracts with additional metadata
+	 * @param generatedClassData - information about the generated class
+	 * @param includedDirectoryRelativePath - relative path to the included directory
+	 * @return contents of a single test class
+	 */
+	default String buildClass(ContractVerifierConfigProperties properties,
+			Collection<ContractMetadata> listOfFiles,
+			String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
+		String className = generatedClassData.className;
+		String classPackage = generatedClassData.classPackage;
+		String path = includedDirectoryRelativePath;
+		return buildClass(properties, listOfFiles, className, classPackage, path);
+	}
+
+	/**
+	 * Extension that should be appended to the generated test class. E.g. {@code .java}
+	 * or {@code .php}
+	 * @param properties - properties passed to the plugin
+	 */
+	String fileExtension(ContractVerifierConfigProperties properties);
+
+	class GeneratedClassData {
+
+		public final String className;
+
+		public final String classPackage;
+
+		public final Path testClassPath;
+
+		public GeneratedClassData(String className, String classPackage,
+				Path testClassPath) {
+			this.className = className;
+			this.classPackage = classPackage;
+			this.testClassPath = testClassPath;
+		}
+
+	}
+
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator
+
+
+
+
+

10.3. Using the Custom Stub Generator

+
+

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

+
+
+
+
package org.springframework.cloud.contract.verifier.converter
+
+import groovy.transform.CompileStatic
+
+import org.springframework.cloud.contract.spec.Contract
+import org.springframework.cloud.contract.verifier.file.ContractMetadata
+
+/**
+ * Converts contracts into their stub representation.
+ *
+ * @since 1.1.0
+ */
+@CompileStatic
+interface StubGenerator {
+
+	/**
+	 * @return {@code true} if the converter can handle the file to convert it into a stub.
+	 */
+	boolean canHandleFileName(String fileName)
+
+	/**
+	 * @return the collection of converted contracts into stubs. One contract can
+	 * result in multiple stubs.
+	 */
+	Map<Contract, String> convertContents(String rootName, ContractMetadata content)
+
+	/**
+	 * @return the name of the converted stub file. If you have multiple contracts
+	 * in a single file then a prefix will be added to the generated file. If you
+	 * provide the {@link Contract#name} field then that field will override the
+	 * generated file name.
+	 *
+	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be
+	 * converted by the implementation to {@code foo.json}. The recursive file
+	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
+	 */
+	String generateOutputFileNameForInput(String inputFileName)
+}
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
# Stub converters
+org.springframework.cloud.contract.verifier.converter.StubGenerator=\
+org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
+
+
+
+

The default implementation is the WireMock stub generation.

+
+
+ + + + + +
+ + +You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. +
+
+
+
+

10.4. Using the Custom Stub Runner

+
+

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

+
+
+

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

+
+
+

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

+
+
+
+
package org.springframework.cloud.contract.stubrunner.provider.moco
+
+import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
+import com.github.dreamhead.moco.runner.JsonRunner
+import com.github.dreamhead.moco.runner.RunnerSetting
+import groovy.util.logging.Commons
+
+import org.springframework.cloud.contract.stubrunner.HttpServerStub
+import org.springframework.util.SocketUtils
+
+@Commons
+class MocoHttpServerStub implements HttpServerStub {
+
+	private boolean started
+	private JsonRunner runner
+	private int port
+
+	@Override
+	int port() {
+		if (!isRunning()) {
+			return -1
+		}
+		return port
+	}
+
+	@Override
+	boolean isRunning() {
+		return started
+	}
+
+	@Override
+	HttpServerStub start() {
+		return start(SocketUtils.findAvailableTcpPort())
+	}
+
+	@Override
+	HttpServerStub start(int port) {
+		this.port = port
+		return this
+	}
+
+	@Override
+	HttpServerStub stop() {
+		if (!isRunning()) {
+			return this
+		}
+		this.runner.stop()
+		return this
+	}
+
+	@Override
+	HttpServerStub registerMappings(Collection<File> stubFiles) {
+		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
+			.collect {
+			log.info("Trying to parse [${it.name}]")
+			try {
+				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
+					build()
+			}
+			catch (Exception e) {
+				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
+				return null
+			}
+		}.findAll { it }
+		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
+			HttpArgs.httpArgs().withPort(this.port).build())
+		this.runner.run()
+		this.started = true
+		return this
+	}
+
+	@Override
+	String registeredMappings() {
+		return ""
+	}
+
+	@Override
+	boolean isAccepted(File file) {
+		return file.name.endsWith(".json")
+	}
+}
+
+
+
+

Then, you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
+
+
+
+

Now you can run stubs with Moco.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. +
+
+
+
+

10.5. Using the Custom Stub Downloader

+
+

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

+
+
+
+
package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}
+
+
+
+

Then you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder
+
+
+
+

Now you can pick a folder with the source of your stubs.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. +
+
+
+
+

10.6. Using the SCM Stub Downloader

+
+

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

+

* stubrunner.properties.git.branch (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

+

* stubrunner.properties.git.username (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

+

* stubrunner.properties.git.password (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

+

* stubrunner.properties.git.no-of-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

+

* stubrunner.properties.git.wait-between-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

+
+
+

10.7. Using the Pact Stub Downloader

+
+

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

+

* stubrunner.properties.pactbroker.host (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

+

* stubrunner.properties.pactbroker.port (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

+

* stubrunner.properties.pactbroker.protocol (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

+

* stubrunner.properties.pactbroker.tags (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

+

* stubrunner.properties.pactbroker.auth.scheme (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

+

* stubrunner.properties.pactbroker.auth.username (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

+

* stubrunner.properties.pactbroker.auth.password (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

+

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

+
+
+
+
+

11. Spring Cloud Contract WireMock

+
+
+

The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details.

+
+
+

If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+	// A service that calls out over HTTP
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:"
+				+ this.environment.getProperty("wiremock.server.port"));
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

+
+
+

11.1. Registering Stubs Automatically

+
+

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureWireMock(stubs="classpath:/stubs")
+public class WiremockImportApplicationTests {
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+ + + + + +
+ + +Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. +
+
+
+

If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

+
+
+
+
@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")
+
+
+
+
+

11.2. Using Files to Specify the Stub Bodies

+
+

WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body.

+
+
+ + + + + +
+ + +When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute. +
+
+
+
+

11.3. Alternative: Using JUnit Rules

+
+

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class WiremockForDocsClassRuleTests {
+
+	// Start WireMock on some dynamic port
+	// for some reason `dynamicPort()` is not working properly
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().dynamicPort());
+
+	// A service that calls out over HTTP to wiremock's port
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:" + wiremock.port());
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

The @ClassRule means that the server shuts down after all the methods in this class +have been run.

+
+
+
+

11.4. Relaxed SSL Validation for Rest Template

+
+

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course).

+
+
+

To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example:

+
+
+
+
@Bean
+public RestTemplate restTemplate(RestTemplateBuilder builder) {
+	return builder.build();
+}
+
+
+
+

You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest("app.baseUrl=https://localhost:6443")
+@AutoConfigureHttpClient
+public class WiremockHttpsServerApplicationTests {
+
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().httpsPort(6443));
+...
+}
+
+
+
+

If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases.

+
+
+

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false.

+
+
+
+

11.5. WireMock and Spring MVC Mocks

+
+

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+public class WiremockForDocsMockServerApplicationTests {
+
+	@Autowired
+	private RestTemplate restTemplate;
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		// will read stubs classpath
+		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
+				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
+				.build();
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World");
+		server.verify();
+	}
+
+}
+
+
+
+

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website.

+
+
+

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one).

+
+
+
+

11.6. Customization of WireMock configuration

+
+

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example:

+
+
+
+
		@Bean
+		WireMockConfigurationCustomizer optionsCustomizer() {
+			return new WireMockConfigurationCustomizer() {
+				@Override
+				public void customize(WireMockConfiguration options) {
+// perform your customization here
+				}
+			};
+		}
+
+
+
+
+

11.7. Generating Stubs using REST Docs

+
+

Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(get("/resource"))
+				.andExpect(content().string("Hello World"))
+				.andDo(document("resource"));
+	}
+}
+
+
+
+

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureWebTestClient
+public class ApplicationTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void contextLoads() throws Exception {
+		client.get().uri("/resource").exchange()
+				.expectBody(String.class).isEqualTo("Hello World")
+ 				.consumeWith(document("resource"));
+	}
+}
+
+
+
+

Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects:

+
+
+
    +
  • +

    Creating a stub that matches only in the way you specify.

    +
  • +
  • +

    Asserting that the request in the test case also matches the same conditions.

    +
  • +
+
+
+

The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example:

+
+
+
+
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
+
+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(post("/resource")
+                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+				.andExpect(status().isOk())
+				.andDo(verify().jsonPath("$.id")
+                        .stub("resource"));
+	}
+}
+
+
+
+

This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place.

+
+
+

Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example:

+
+
+
+
@Test
+public void contextLoads() throws Exception {
+	mockMvc.perform(post("/resource")
+               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+			.andExpect(status().isOk())
+			.andDo(verify()
+					.wiremock(WireMock.post(
+						urlPathEquals("/resource"))
+						.withRequestBody(matchingJsonPath("$.id"))
+                       .stub("post-resource"));
+}
+
+
+
+

The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example:

+
+
+
post-resource.json
+
+
{
+  "request" : {
+    "url" : "/resource",
+    "method" : "POST",
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.id"
+    }]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "Hello World",
+    "headers" : {
+      "X-Application-Context" : "application:-1",
+      "Content-Type" : "text/plain"
+    }
+  }
+}
+
+
+
+ + + + + +
+ + +You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches. +
+
+
+

On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document.

+
+
+
+

11.8. Generating Contracts by Using REST Docs

+
+

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs.

+
+
+

Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them.

+
+
+ + + + + +
+ + +You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. +
+
+
+

Consider the following test:

+
+
+
+
		this.mockMvc
+				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
+						.accept(MediaType.APPLICATION_JSON)
+						.contentType(MediaType.APPLICATION_JSON)
+						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
+				.andExpect(status().isOk()).andExpect(content().string("bar"))
+				// first WireMock
+				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
+						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
+						.contentType(MediaType.valueOf("application/json"))
+						.stub("shouldGrantABeerIfOldEnough"))
+				// then Contract DSL documentation
+				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));
+
+
+
+

The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file.

+
+
+

The contract is called index.groovy and might look like the following example:

+
+
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+    request {
+        method 'POST'
+        url '/foo'
+        body('''
+            {"foo": 23 }
+        ''')
+        headers {
+            header('''Accept''', '''application/json''')
+            header('''Content-Type''', '''application/json''')
+        }
+    }
+    response {
+        status OK()
+        body('''
+        bar
+        ''')
+        headers {
+            header('''Content-Type''', '''application/json;charset=UTF-8''')
+            header('''Content-Length''', '''3''')
+        }
+        testMatchers {
+            jsonPath('$[?(@.foo >= 20)]', byType())
+        }
+    }
+}
+
+
+
+

The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc.

+
+
+
+
+
+

12. Migrations

+
+
+ + + + + +
+ + +For up to date migration guides please visit +the project’s wiki page. +
+
+
+

This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths:

+
+
+

12.1. 1.0.x → 1.1.x

+
+

This section covers upgrading from version 1.0 to version 1.1.

+
+
+

12.1.1. New structure of generated stubs

+
+

In 1.1.x we have introduced a change to the structure of generated stubs. If you have +been using the @AutoConfigureWireMock notation to use the stubs from the classpath, +it no longer works. The following example shows how the @AutoConfigureWireMock notation +used to work:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
+
+
+
+

You must either change the location of the stubs to: +classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new +classpath-based @AutoConfigureStubRunner, as shown in the following example:

+
+
+
+
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
+
+
+
+

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet.

+
+
+
Maven
+
+
<!-- start of pom.xml -->
+
+<properties>
+    <!-- we don't want the verifier to do a jar for us -->
+    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
+</properties>
+
+<!-- ... -->
+
+<!-- You need to set up the assembly plugin -->
+<build>
+    <plugins>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-assembly-plugin</artifactId>
+            <executions>
+                <execution>
+                    <id>stub</id>
+                    <phase>prepare-package</phase>
+                    <goals>
+                        <goal>single</goal>
+                    </goals>
+                    <inherited>false</inherited>
+                    <configuration>
+                        <attach>true</attach>
+                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
+                    </configuration>
+                </execution>
+            </executions>
+        </plugin>
+    </plugins>
+</build>
+<!-- end of pom.xml -->
+
+<!-- start of stub.xml-->
+
+<assembly
+	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>stubs</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.build.directory}/snippets/stubs</directory>
+			<outputDirectory>customer-stubs/mappings</outputDirectory>
+			<includes>
+				<include>**/*</include>
+			</includes>
+		</fileSet>
+		<fileSet>
+			<directory>${basedir}/src/test/resources/contracts</directory>
+			<outputDirectory>customer-stubs/contracts</outputDirectory>
+			<includes>
+				<include>**/*.groovy</include>
+			</includes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+<!-- end of stub.xml-->
+
+
+
+
Gradle
+
+
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
+//    Preserve directory structure from 1.0.X of spring-cloud-contract
+    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
+    into "${project.buildDir}/resources/main/customer-stubs"
+}
+
+
+
+
+
+

12.2. 1.1.x → 1.2.x

+
+

This section covers upgrading from version 1.1 to version 1.2.

+
+
+

12.2.1. Custom HttpServerStub

+
+

HttpServerStub includes a method that was not in version 1.1. The method is +String registeredMappings() If you have classes that implement HttpServerStub, you +now have to implement the registeredMappings() method. It should return a String +representing all mappings available in a single HttpServerStub.

+
+
+

See issue 355 for more +detail.

+
+
+
+

12.2.2. New packages for generated tests

+
+

The flow for setting the generated tests package name will look like this:

+
+
+
    +
  • +

    Set basePackageForTests

    +
  • +
  • +

    If basePackageForTests was not set, pick the package from baseClassForTests

    +
  • +
  • +

    If baseClassForTests was not set, pick packageWithBaseClasses

    +
  • +
  • +

    If nothing got set, pick the default value: +org.springframework.cloud.contract.verifier.tests

    +
  • +
+
+
+

See issue 260 for more +detail.

+
+
+
+

12.2.3. New Methods in TemplateProcessor

+
+

In order to add support for fromRequest.path, the following methods had to be added to the +TemplateProcessor interface:

+
+
+
    +
  • +

    path()

    +
  • +
  • +

    path(int index)

    +
  • +
+
+
+

See issue 388 for more +detail.

+
+
+
+

12.2.4. RestAssured 3.0

+
+

Rest Assured, used in the generated test classes, got bumped to 3.0. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception:

+
+
+
+
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
+[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist
+
+
+
+

This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa).

+
+
+

Done via issue 267

+
+
+
+ +
+
+
+ +
+
+

The following links may be helpful when working with Spring Cloud Contract:

+
+ +
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/spring-cloud-wiremock.html b/reference/html/spring-cloud-wiremock.html new file mode 100644 index 0000000000..f1d35e0e99 --- /dev/null +++ b/reference/html/spring-cloud-wiremock.html @@ -0,0 +1,700 @@ + + + + + + + +Spring Cloud Contract WireMock + + + + + + + + + + +
+
+

Spring Cloud Contract WireMock

+
+
+

The Spring Cloud Contract WireMock modules let you use WireMock in a +Spring Boot application. Check out the +samples +for more details.

+
+
+

If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with spring-boot-starter-web), you can add +spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+	// A service that calls out over HTTP
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:"
+				+ this.environment.getProperty("wiremock.server.port"));
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

To start the stub server on a different port use (for example), +@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

+
+
+

Registering Stubs Automatically

+
+

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +system or classpath (by default, from file:src/test/resources/mappings). You can +customize the locations using the stubs attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, */.json is +appended. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureWireMock(stubs="classpath:/stubs")
+public class WiremockImportApplicationTests {
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+ + + + + +
+ + +Actually, WireMock always loads mappings from src/test/resources/mappings as +well as the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. +
+
+
+

If you’re using Spring Cloud Contract’s default stub jars, then your +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

+
+
+
+
@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")
+
+
+
+
+

Using Files to Specify the Stub Bodies

+
+

WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a bodyFileName instead of a +(literal) body. The files are resolved relative to a root directory (by default, +src/test/resources/__files). To customize this location you can set the files +attribute in the @AutoConfigureWireMock annotation to the location of the parent +directory (in other words, __files is a subdirectory). You can use Spring resource +notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body.

+
+
+ + + + + +
+ + +When you configure the files root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of files has no +effect on the stubs loaded explicitly from the stubs attribute. +
+
+
+
+

Alternative: Using JUnit Rules

+
+

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +the server. To do so, use the WireMockSpring convenience class to obtain an Options +instance, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+public class WiremockForDocsClassRuleTests {
+
+	// Start WireMock on some dynamic port
+	// for some reason `dynamicPort()` is not working properly
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().dynamicPort());
+
+	// A service that calls out over HTTP to wiremock's port
+	@Autowired
+	private Service service;
+
+	@Before
+	public void setup() {
+		this.service.setBase("http://localhost:" + wiremock.port());
+	}
+
+	// Using the WireMock APIs in the normal way:
+	@Test
+	public void contextLoads() throws Exception {
+		// Stubbing WireMock
+		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World!");
+	}
+
+}
+
+
+
+

The @ClassRule means that the server shuts down after all the methods in this class +have been run.

+
+
+
+

Relaxed SSL Validation for Rest Template

+
+

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that’s not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course).

+
+
+

To make this work with minimum fuss, you need to be using the Spring Boot +RestTemplateBuilder in your app, as shown in the following example:

+
+
+
+
@Bean
+public RestTemplate restTemplate(RestTemplateBuilder builder) {
+	return builder.build();
+}
+
+
+
+

You need RestTemplateBuilder because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the @AutoConfigureWireMock +annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the +@AutoConfigureHttpClient annotation as well, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest("app.baseUrl=https://localhost:6443")
+@AutoConfigureHttpClient
+public class WiremockHttpsServerApplicationTests {
+
+	@ClassRule
+	public static WireMockClassRule wiremock = new WireMockClassRule(
+			WireMockSpring.options().httpsPort(6443));
+...
+}
+
+
+
+

If you are using spring-boot-starter-test, you have the Apache HTTP client on the +classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL +errors. If you use the default java.net client, you do not need the annotation (but it +won’t do any harm). There is no support currently for other clients, but it may be added +in future releases.

+
+
+

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled +property to false.

+
+
+
+

WireMock and Spring MVC Mocks

+
+

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring MockRestServiceServer. The following code shows an example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.NONE)
+public class WiremockForDocsMockServerApplicationTests {
+
+	@Autowired
+	private RestTemplate restTemplate;
+
+	@Autowired
+	private Service service;
+
+	@Test
+	public void contextLoads() throws Exception {
+		// will read stubs classpath
+		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
+				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
+				.build();
+		// We're asserting if WireMock responded properly
+		assertThat(this.service.go()).isEqualTo("Hello World");
+		server.verify();
+	}
+
+}
+
+
+
+

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to +visit https://example.org/, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +WireMock website.

+
+
+

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one).

+
+
+
+

Customization of WireMock configuration

+
+

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +in order to customize the WireMock configuration (e.g. add custom transformers). +Example:

+
+
+
+
		@Bean
+		WireMockConfigurationCustomizer optionsCustomizer() {
+			return new WireMockConfigurationCustomizer() {
+				@Override
+				public void customize(WireMockConfiguration options) {
+// perform your customization here
+				}
+			};
+		}
+
+
+
+
+

Generating Stubs using REST Docs

+
+

Spring REST Docs can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc +or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example using MockMvc:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(get("/resource"))
+				.andExpect(content().string("Hello World"))
+				.andDo(document("resource"));
+	}
+}
+
+
+
+

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. The same example with WebTestClient (used +for testing Spring WebFlux applications) would look like this:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureWebTestClient
+public class ApplicationTests {
+
+	@Autowired
+	private WebTestClient client;
+
+	@Test
+	public void contextLoads() throws Exception {
+		client.get().uri("/resource").exchange()
+				.expectBody(String.class).isEqualTo("Hello World")
+ 				.consumeWith(document("resource"));
+	}
+}
+
+
+
+

Without any additional configuration, these tests create a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects:

+
+
+
    +
  • +

    Creating a stub that matches only in the way you specify.

    +
  • +
  • +

    Asserting that the request in the test case also matches the same conditions.

    +
  • +
+
+
+

The main entry point for this feature is WireMockRestDocs.verify(), which can be used +as a substitute for the document() convenience method, as shown in the following +example:

+
+
+
+
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
+
+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureRestDocs(outputDir = "target/snippets")
+@AutoConfigureMockMvc
+public class ApplicationTests {
+
+	@Autowired
+	private MockMvc mockMvc;
+
+	@Test
+	public void contextLoads() throws Exception {
+		mockMvc.perform(post("/resource")
+                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+				.andExpect(status().isOk())
+				.andDo(verify().jsonPath("$.id")
+                        .stub("resource"));
+	}
+}
+
+
+
+

This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to .jsonPath() to add additional +matchers. If JSON Path is unfamiliar, The JayWay +documentation can help you get up to speed. The WebTestClient version of this test +has a similar verify() static helper that you insert in the same place.

+
+
+

Instead of the jsonPath and contentType convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example:

+
+
+
+
@Test
+public void contextLoads() throws Exception {
+	mockMvc.perform(post("/resource")
+               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
+			.andExpect(status().isOk())
+			.andDo(verify()
+					.wiremock(WireMock.post(
+						urlPathEquals("/resource"))
+						.withRequestBody(matchingJsonPath("$.id"))
+                       .stub("post-resource"));
+}
+
+
+
+

The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example:

+
+
+
post-resource.json
+
+
{
+  "request" : {
+    "url" : "/resource",
+    "method" : "POST",
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$.id"
+    }]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "Hello World",
+    "headers" : {
+      "X-Application-Context" : "application:-1",
+      "Content-Type" : "text/plain"
+    }
+  }
+}
+
+
+
+ + + + + +
+ + +You can use either the wiremock() method or the jsonPath() and contentType() +methods to create request matchers, but you can’t use both approaches. +
+
+
+

On the consumer side, you can make the resource.json generated earlier in this section +available on the classpath (by +<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this +document.

+
+
+
+

Generating Contracts by Using REST Docs

+
+

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs.

+
+
+

Why would you want to use this feature? Some people in the community asked questions +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them.

+
+
+ + + + + +
+ + +You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. +
+
+
+

Consider the following test:

+
+
+
+
		this.mockMvc
+				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
+						.accept(MediaType.APPLICATION_JSON)
+						.contentType(MediaType.APPLICATION_JSON)
+						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
+				.andExpect(status().isOk()).andExpect(content().string("bar"))
+				// first WireMock
+				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
+						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
+						.contentType(MediaType.valueOf("application/json"))
+						.stub("shouldGrantABeerIfOldEnough"))
+				// then Contract DSL documentation
+				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));
+
+
+
+

The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file.

+
+
+

The contract is called index.groovy and might look like the following example:

+
+
+
+
import org.springframework.cloud.contract.spec.Contract
+
+Contract.make {
+    request {
+        method 'POST'
+        url '/foo'
+        body('''
+            {"foo": 23 }
+        ''')
+        headers {
+            header('''Accept''', '''application/json''')
+            header('''Content-Type''', '''application/json''')
+        }
+    }
+    response {
+        status OK()
+        body('''
+        bar
+        ''')
+        headers {
+            header('''Content-Type''', '''application/json;charset=UTF-8''')
+            header('''Content-Length''', '''3''')
+        }
+        testMatchers {
+            jsonPath('$[?(@.foo >= 20)]', byType())
+        }
+    }
+}
+
+
+
+

The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be index/dsl-contract.adoc.

+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_contract.html b/reference/html/verifier_contract.html new file mode 100644 index 0000000000..6657dc32b1 --- /dev/null +++ b/reference/html/verifier_contract.html @@ -0,0 +1,2993 @@ + + + + + + + +Contract DSL + + + + + + + + + + +
+
+

Contract DSL

+
+
+

Spring Cloud Contract supports out of the box 2 types of DSL. One written in +Groovy and one written in YAML.

+
+
+

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself.

+
+
+ + + + + +
+ + +Remember that, inside the Groovy contract file, you have to provide the fully +qualified name to the Contract class and make static imports, such as +org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to +the Contract class: import org.springframework.cloud.spec.Contract and then call +Contract.make { …​ }. +
+
+
+ + + + + +
+ + +Spring Cloud Contract supports defining multiple contracts in a single file. +
+
+
+

The following is a complete example of a Groovy contract definition:

+
+
+
+
+
+
+
+

The following is a complete example of a YAML contract definition:

+
+
+
+
+
+
+
+ + + + + +
+ + +You can compile contracts to stubs mapping using standalone maven command: +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert +
+
+
+

Limitations

+
+ + + + + +
+ + +Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. +
+
+
+ + + + + +
+ + +The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to true: +spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. +You can also provide the assertJsonSize property in the plugin configuration. +
+
+
+ + + + + +
+ + +Because JSON structure can have any form, it can be impossible to parse it +properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That +is why you should use the Groovy Map notation. +
+
+
+
+

Common Top-Level elements

+
+

The following sections describe the most common top-level elements:

+
+ +
+

Description

+
+

You can add a description to your contract. The description is arbitrary text. The +following code shows an example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+
+

Name

+
+

You can provide a name for your contract. Assume that you provided the following name: +should register a user. If you do so, the name of the autogenerated test is +validate_should_register_a_user. Also, the name of the stub in a WireMock stub is +should_register_a_user.json.

+
+
+ + + + + +
+ + +You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. +
+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+
+

Ignoring Contracts

+
+

If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the ignored property on the contract itself:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+
+

Passing Values from Files

+
+

Starting with version 1.2.0, you can pass values from files. Assume that you have the +following resources in our project.

+
+
+
+
└── src
+    └── test
+        └── resources
+            └── contracts
+                ├── readFromFile.groovy
+                ├── request.json
+                └── response.json
+
+
+
+

Further assume that your contract is as follows:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

Further assume that the JSON files is as follows:

+
+
+

request.json

+
+
+
+
+
+
+
+

response.json

+
+
+
+
+
+
+
+

When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. The name of the file needs to be a file with location +relative to the folder in which the contract lays.

+
+
+

If you need to pass the contents of a file in a binary form +it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+ + + + + +
+ + +You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. +
+
+
+
+

HTTP Top-Level Elements

+
+

The following methods can be called in the top-level closure of a contract definition. +request and response are mandatory. priority is optional.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+...
+
+
+
+ + + + + +
+ + +If you want to make your contract have a higher value of priority +you need to pass a lower number to the priority tag / method. E.g. priority with +value 5 has higher priority than priority with value 10. +
+
+
+
+
+

Request

+
+

The HTTP protocol requires only method and url to be specified in a request. The +same information is mandatory in request definition of the Contract.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

It is possible to specify an absolute rather than relative url, but using urlPath is +the recommended way, as doing so makes the tests host-independent.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

request may contain query parameters.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+
+
+
+

request may contain additional request headers, as shown in the following example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+
+
+
+

request may contain additional request cookies, as shown in the following example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+
+
+
+

request may contain a request body:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+
+
+
+

request may contain multipart elements. To include multipart elements, use the +multipart method/section, as shown in the following examples

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

In the preceding example, we define parameters in either of two ways:

+
+
+
Groovy DSL
+
    +
  • +

    Directly, by using the map notation, where the value can be a dynamic property (such as +formParameter: $(consumer(…​), producer(…​))).

    +
  • +
  • +

    By using the named(…​) method that lets you set a named parameter. A named parameter +can set a name and content. You can call it either via a method with two arguments, +such as named("fileName", "fileContent"), or via a map notation, such as +named(name: "fileName", content: "fileContent").

    +
  • +
+
+
+
YAML
+
    +
  • +

    The multipart parameters are set via multipart.params section

    +
  • +
  • +

    The named parameters (the fileName and fileContent for a given parameter name) +can be set via the multipart.named section. That section contains +the paramName (name of the parameter), fileName (name of the file), +fileContent (content of the file) fields

    +
  • +
  • +

    The dynamic bits can be set via the matchers.multipart section

    +
    +
      +
    • +

      for parameters use the params section that can accept +regex or a predefined regular expression

      +
    • +
    • +

      for named params use the named section where first you +define the parameter name via paramName and then you can pass the +parametrization of either fileName or fileContent via +regex or a predefined regular expression

      +
    • +
    +
    +
  • +
+
+
+

From this contract, the generated test is as follows:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
+   .param("formParameter", "\"formParameterValue\"")
+   .param("someBooleanParameter", "true")
+   .multiPart("file", "filename.csv", "file content".getBytes());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .put("/multipart");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+

The WireMock stub is as follows:

+
+
+
+
+
+
+
+
+

Response

+
+

The response must contain an HTTP status code and may contain other information. The +following code shows an example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
...
+
+
+
+

Besides status, the response may contain headers, cookies and a body, both of which are +specified the same way as in the request (see the previous paragraph).

+
+
+ + + + + +
+ + +Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus +methods to provide a meaningful status instead of a digit. E.g. you can call +OK() for a status 200 or BAD_REQUEST() for 400. +
+
+
+
+

Dynamic properties

+
+

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub.

+
+
+

For Groovy DSL you can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in a separate section called +bodyMatchers.

+
+
+ + + + + +
+ + +Before 2.0.0 these were set using testMatchers and stubMatchers, +check out the migration guide for more information. +
+
+
+

For YAML you can only use the matchers section.

+
+
+

Dynamic properties inside the body

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can set the properties inside the body either with the value method or, if you use +the Groovy map notation, with $(). The following example shows how to set dynamic +properties with the value method:

+
+
+
+
value(consumer(...), producer(...))
+value(c(...), p(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

The following example shows how to set dynamic properties with $():

+
+
+
+
$(consumer(...), producer(...))
+$(c(...), p(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

Both approaches work equally well. stub and client methods are aliases over the consumer +method. Subsequent sections take a closer look at what you can do with those values.

+
+
+
+

Regular expressions

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests.

+
+
+

Make sure that regex matches a whole region of a sequence as internally a call to +Pattern.matches() +is called. For instance, abc pattern doesn’t match aabc string but .abc does. +There are several additional known limitations as well.

+
+
+

The following example shows how to use regular expressions to write a request:

+
+
+
+
+
+
+
+

You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example:

+
+
+
+
+
+
+
+

In the preceding example, the opposite side of the communication has the respective data +generated for request and response.

+
+
+

Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example:

+
+
+
+
+
+
+
+

In your contract, you can use it as shown in the following example:

+
+
+
+
+
+
+
+

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. +All of those methods start with any prefix:

+
+
+
+
+
+
+
+

and this is an example of how you can reference those methods:

+
+
+
+
+
+
+
+
Limitations
+
+ + + + + +
+ + +Due to certain limitations of Xeger library that generates string out of +regex, do not use $ and ^ signs in your regex if you rely on automatic +generation. Issue 899 +
+
+
+ + + + + +
+ + +Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). +It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. +Issue 900 +
+
+
+
+
+

Passing Optional Parameters

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following:

+
+
+
    +
  • +

    STUB side of the Request

    +
  • +
  • +

    TEST side of the Response

    +
  • +
+
+
+

The following example shows how to provide optional parameters:

+
+
+
+
+
+
+
+

By wrapping a part of the body with the optional() method, you create a regular +expression that must be present 0 or more times.

+
+
+

If you use Spock for, the following test would be generated from the previous example:

+
+
+
+
+
+
+
+

The following stub would also be generated:

+
+
+
+
+
+
+
+
+

Executing Custom Methods on the Server Side

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. Check out the +Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. +
+
+
+

You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case:

+
+
+
+
+
+
+
+

The following code shows the base class portion of the test case:

+
+
+
+
+
+
+
+ + + + + +
+ + +You cannot use both a String and execute to perform concatenation. For +example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to +improper results. Instead, call header('Authorization', execute('authToken()')) and +ensure that the authToken() method returns everything you need. +
+
+
+

The type of the object read from the JSON can be one of the following, depending on the +JSON path:

+
+
+
    +
  • +

    String: If you point to a String value in the JSON.

    +
  • +
  • +

    JSONArray: If you point to a List in the JSON.

    +
  • +
  • +

    Map: If you point to a Map in the JSON.

    +
  • +
  • +

    Number: If you point to Integer, Double etc. in the JSON.

    +
  • +
  • +

    Boolean: If you point to a Boolean in the JSON.

    +
  • +
+
+
+

In the request part of the contract, you can specify that the body should be taken from +a method.

+
+
+ + + + + +
+ + +You must provide both the consumer and the producer side. The execute part +is applied for the whole body - not for parts of it. +
+
+
+

The following example shows how to read an object from JSON:

+
+
+
+
+
+
+
+

The preceding example results in calling the hashCode() method in the request body. +It should resemble the following code:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .body(hashCode());
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/something");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+
+
+
+
+

Referencing the Request from the Response

+
+

The best situation is to provide fixed values, but sometimes you need to reference a +request in your response.

+
+
+

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options:

+
+
+
    +
  • +

    fromRequest().url(): Returns the request URL and query parameters.

    +
  • +
  • +

    fromRequest().query(String key): Returns the first query parameter with a given name.

    +
  • +
  • +

    fromRequest().query(String key, int index): Returns the nth query parameter with a +given name.

    +
  • +
  • +

    fromRequest().path(): Returns the full path.

    +
  • +
  • +

    fromRequest().path(int index): Returns the nth path element.

    +
  • +
  • +

    fromRequest().header(String key): Returns the first header with a given name.

    +
  • +
  • +

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    +
  • +
  • +

    fromRequest().body(): Returns the full request body.

    +
  • +
  • +

    fromRequest().body(String jsonPath): Returns the element from the request that +matches the JSON Path.

    +
  • +
+
+
+

If you’re using the YAML contract definition you have to use the +Handlebars {{{ }}} notation with custom, Spring Cloud Contract + functions to achieve this.

+
+
+
    +
  • +

    {{{ request.url }}}: Returns the request URL and query parameters.

    +
  • +
  • +

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. +E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    +
  • +
  • +

    {{{ request.path }}}: Returns the full path.

    +
  • +
  • +

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. +for first entry `{{{ request.path.[0] }}}

    +
  • +
  • +

    {{{ request.headers.key }}}: Returns the first header with a given name.

    +
  • +
  • +

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    +
  • +
  • +

    {{{ request.body }}}: Returns the full request body.

    +
  • +
  • +

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that +matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    +
  • +
+
+
+

Consider the following contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

Running a JUnit test generation leads to a test that resembles the following example:

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Authorization", "secret")
+   .header("Authorization", "secret2")
+   .body("{\"foo\":\"bar\",\"baz\":5}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .queryParam("foo","bar")
+   .queryParam("foo","bar2")
+   .get("/api/v1/xxxx");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
+ assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
+ assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
+ assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
+ assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
+ assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
+ assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
+ assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
+ assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
+
+
+
+

As you can see, elements from the request have been properly referenced in the response.

+
+
+

The generated WireMock stub should resemble the following example:

+
+
+
+
{
+  "request" : {
+    "urlPath" : "/api/v1/xxxx",
+    "method" : "POST",
+    "headers" : {
+      "Authorization" : {
+        "equalTo" : "secret2"
+      }
+    },
+    "queryParameters" : {
+      "foo" : {
+        "equalTo" : "bar2"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
+    "headers" : {
+      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
+    },
+    "transformers" : [ "response-template" ]
+  }
+}
+
+
+
+

Sending a request such as the one presented in the request part of the contract results +in sending the following response body:

+
+
+
+
{
+  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
+  "path" : "/api/v1/xxxx",
+  "pathIndex" : "v1",
+  "param" : "bar",
+  "paramIndex" : "bar2",
+  "authorization" : "secret",
+  "authorization2" : "secret2",
+  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
+  "responseFoo" : "bar",
+  "responseBaz" : 5,
+  "responseBaz2" : "Bla bla bar bla bla"
+}
+
+
+
+ + + + + +
+ + +This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s +response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into +proper values. Additionally, it registers two helper functions: +
+
+
+
    +
  • +

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    +
  • +
  • +

    jsonpath: For a given parameter, find an object in the request body.

    +
  • +
+
+
+
+

Registering Your Own WireMock Extension

+
+

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +the transformer, which lets you reference a request from a response. If you want to +provide your own extensions, you can register an implementation of the +org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. +Since we use the spring.factories extension approach, you can create an entry in +META-INF/spring.factories file similar to the following:

+
+
+
+
+
+
+
+

The following is an example of a custom extension:

+
+
+
TestWireMockExtensions.groovy
+
+
+
+
+
+ + + + + +
+ + +Remember to override the applyGlobally() method and set it to false if you +want the transformation to be applied only for a mapping that explicitly requires it. +
+
+
+
+

Dynamic Properties in the Matchers Sections

+
+

If you work with Pact, the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract.

+
+
+

You can use the bodyMatchers section for two reasons:

+
+
+
    +
  • +

    Define the dynamic values that should end up in a stub. +You can set it in the request or inputMessage part of your contract.

    +
  • +
  • +

    Verify the result of your test. +This section is present in the response or outputMessage side of the +contract.

    +
  • +
+
+
+

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities:

+
+
+
Groovy DSL
+
    +
  • +

    For the stubs(in tests on the Consumer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be +equal to the value provided in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must +match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      +
    • +
    • +

      byDate(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the consumer’s request via the provided JSON Path must +match the regex for an ISO Time value.

      +
    • +
    +
    +
  • +
  • +

    For the verification(in generated tests on the Producer’s side):

    +
    +
      +
    • +

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be +equal to the provided value in the contract.

      +
    • +
    • +

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must +match the regex.

      +
    • +
    • +

      byDate(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Date value.

      +
    • +
    • +

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must +match the regex for an ISO DateTime value.

      +
    • +
    • +

      byTime(): The value taken from the producer’s response via the provided JSON Path must match +the regex for an ISO Time value.

      +
    • +
    • +

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      +
    • +
    • +

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +byCommand('foo($it)') results in calling a foo method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path:

      +
      +
        +
      • +

        String: If you point to a String value.

        +
      • +
      • +

        JSONArray: If you point to a List.

        +
      • +
      • +

        Map: If you point to a Map.

        +
      • +
      • +

        Number: If you point to Integer, Double, or other kind of number.

        +
      • +
      • +

        Boolean: If you point to a Boolean.

        +
      • +
      +
      +
    • +
    • +

      byNull(): The value taken from the response via the provided JSON Path must be null

      +
    • +
    +
    +
  • +
+
+
+
YAML
+

Please read the Groovy section for detailed explanation of +what the types mean

+
+
+

For YAML the structure of a matcher looks like this

+
+
+
+
- path: $.foo
+  type: by_regex
+  value: bar
+  regexType: as_string
+
+
+
+

Or if you want to use one of the predefined regular expressions +[only_alpha_unicode, number, any_boolean, ip_address, hostname, +email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

+
+
+
+
- path: $.foo
+  type: by_regex
+  predefined: only_alpha_unicode
+
+
+
+

Below you can find the allowed list of `type`s.

+
+
+
    +
  • +

    For stubMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    For testMatchers:

    +
    +
      +
    • +

      by_equality

      +
    • +
    • +

      by_regex

      +
    • +
    • +

      by_date

      +
    • +
    • +

      by_timestamp

      +
    • +
    • +

      by_time

      +
    • +
    • +

      by_type

      +
      +
        +
      • +

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        +
      • +
      +
      +
    • +
    • +

      by_command

      +
    • +
    • +

      by_null

      +
    • +
    +
    +
  • +
+
+
+

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

+
+
+
    +
  • +

    as_integer

    +
  • +
  • +

    as_double

    +
  • +
  • +

    as_float,

    +
  • +
  • +

    as_long

    +
  • +
  • +

    as_short

    +
  • +
  • +

    as_boolean

    +
  • +
  • +

    as_string

    +
  • +
+
+
+

Consider the following example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

In the preceding example, you can see the dynamic portions of the contract in the +matchers sections. For the request part, you can see that, for all fields but +valueWithoutAMatcher, the values of the regular expressions that the stub should +contain are explicitly set. For the valueWithoutAMatcher, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check.

+
+
+

For the response side in the bodyMatchers section, we define the dynamic parts in a +similar manner. The only difference is that the byType matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called):

+
+
+
    +
  • +

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    +
  • +
  • +

    For $.valueWithMin, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence.

    +
  • +
  • +

    For $.valueWithMax, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence.

    +
  • +
  • +

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is +between the min and maximum occurrence.

    +
  • +
+
+
+

The resulting test would resemble the following example (note that an and section +separates the autogenerated assertions and the assertion from matchers):

+
+
+
+
// given:
+ MockMvcRequestSpecification request = given()
+   .header("Content-Type", "application/json")
+   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
+
+// when:
+ ResponseOptions response = given().spec(request)
+   .get("/get");
+
+// then:
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.header("Content-Type")).matches("application/json.*");
+// and:
+ DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+ assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
+// and:
+ assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
+ assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
+ assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
+ assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
+ assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
+ assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
+ assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
+ assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
+ assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
+ assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
+ assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
+ assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
+ assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
+ assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
+ assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
+ assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
+
+
+
+ + + + + +
+ + +Notice that, for the byCommand method, the example calls the +assertThatValueIsANumber. This method must be defined in the test base class or be +statically imported to your tests. Notice that the byCommand call was converted to +assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. +
+
+
+

The resulting WireMock stub is in the following example:

+
+
+
+
+
+
+
+ + + + + +
+ + +If you use a matcher, then the part of the request and response that the +matcher addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for all the elements of the +collection. +
+
+
+

Consider the following example:

+
+
+
+
Contract.make {
+    request {
+        method 'GET'
+        url("/foo")
+    }
+    response {
+        status OK()
+        body(events: [[
+                                 operation          : 'EXPORT',
+                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
+                                 status             : 'OK'
+                         ], [
+                                 operation          : 'INPUT_PROCESSING',
+                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
+                                 status             : 'OK'
+                         ]
+                ]
+        )
+        bodyMatchers {
+            jsonPath('$.events[0].operation', byRegex('.+'))
+            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
+            jsonPath('$.events[0].status', byRegex('.+'))
+        }
+    }
+}
+
+
+
+

The preceding code leads to creating the following test (the code block shows only the assertion section):

+
+
+
+
and:
+	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
+	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
+	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
+	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
+and:
+	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
+	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
+	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
+
+
+
+

As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole $.events +collection and assert it with the byCommand(…​) method.

+
+
+
+
+

JAX-RS Support

+
+

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define protected WebTarget webTarget and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of application/octet-stream gets used.

+
+
+

In order to use JAX-RS mode, use the following settings:

+
+
+
+
testMode == 'JAXRSCLIENT'
+
+
+
+

The following example shows a generated test API:

+
+
+
+
+
+
+
+
+

Async Support

+
+

If you’re using asynchronous communication on the server side (your controllers are +returning Callable, DeferredResult, and so on), then, inside your contract, you must +provide an async() method in the response section. The following code shows an example:

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status OK()
+        body 'Passed'
+        async()
+    }
+}
+
+
+
+
YAML
+
+
response:
+    async: true
+
+
+
+

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

+
+
+
Groovy DSL
+
+
org.springframework.cloud.contract.spec.Contract.make {
+    request {
+        method GET()
+        url '/get'
+    }
+    response {
+        status 200
+        body 'Passed'
+        fixedDelayMilliseconds 1000
+    }
+}
+
+
+
+
YAML
+
+
response:
+    fixedDelayMilliseconds: 1000
+
+
+
+
+

Working with Context Paths

+
+

Spring Cloud Contract supports context paths.

+
+
+ + + + + +
+ + +The only change needed to fully support context paths is the switch on the +PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer +side remains untouched. In order for the generated test to pass, you must use EXPLICIT +mode. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

That way, you generate a test that DOES NOT use MockMvc. It means that you generate +real requests and you need to setup your generated test’s base class to work on a real +socket.

+
+
+

Consider the following contract:

+
+
+
+
+
+
+
+

The following example shows how to set up a base class and Rest Assured:

+
+
+
+
+
+
+
+

If you do it this way:

+
+
+
    +
  • +

    All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, /my-context-path/url).

    +
  • +
  • +

    Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call /my-context-path/url).

    +
  • +
+
+
+
+

Working with WebFlux

+
+

Spring Cloud Contract offers two ways of working with WebFlux.

+
+
+

WebFlux with WebTestClient

+
+

One of them is via the WebTestClient mode.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>WEBTESTCLIENT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'WEBTESTCLIENT'
+}
+
+
+
+

The following example shows how to set up a WebTestClient base class and RestAssured +for WebFlux:

+
+
+
+
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
+import org.junit.Before;
+
+public abstract class BeerRestBase {
+
+	@Before
+	public void setup() {
+		RestAssuredWebTestClient.standaloneSetup(
+		new ProducerController(personToCheck -> personToCheck.age >= 20));
+	}
+}
+}
+
+
+
+
+

WebFlux with Explicit mode

+
+

Another way is with the EXPLICIT mode in your generated tests +to work with WebFlux.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <testMode>EXPLICIT</testMode>
+    </configuration>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+		testMode = 'EXPLICIT'
+}
+
+
+
+

The following example shows how to set up a base class and Rest Assured for Web Flux:

+
+
+
+
    // your tests go here
+
+    // in this config class you define all controllers and mocked services
+
+}
+
+
+
+
+
+

XML Support for REST

+
+

For REST contracts, we also support XML request and response body. +The XML body has to be passed within the body element +as a String or GString. Also body matchers can be provided for +both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath +method should be used, with the desired xPath provided as the first argument +and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

+
+
+

Here is an example of a Groovy DSL contract with XML response body:

+
+
+
+
+
+
+
+

And below is an example of a YAML contract with XML request and response bodies:

+
+
+
+
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
+
+
+
+

Here is an example of an automatically generated test for XML response body:

+
+
+
+
@Test
+public void validate_xmlMatches() throws Exception {
+	// given:
+	MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/xml");
+
+	// when:
+	ResponseOptions response = given().spec(request).get("/get");
+
+	// then:
+	assertThat(response.statusCode()).isEqualTo(200);
+	// and:
+	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
+					.newDocumentBuilder();
+	Document parsedXml = documentBuilder.parse(new InputSource(
+				new StringReader(response.getBody().asString())));
+	// and:
+	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
+	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
+	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
+	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
+	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
+	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
+	}
+
+
+
+
+

Messaging Top-Level Elements

+
+

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

+
+ +
+

Output Triggered by a Method

+
+

The output message can be triggered by calling a method (such as a Scheduler when a was +started and a message was sent), as shown in the following example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

In the previous example case, the output message is sent to output if a method called +bookReturnedTriggered is executed. On the message publisher’s side, we generate a +test that calls that method to trigger the message. On the consumer side, you can use +the some_label to trigger the message.

+
+
+
+

Output Triggered by a Message

+
+

The output message can be triggered by receiving a message, as shown in the following +example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

In the preceding example, the output message is sent to output if a proper message is +received on the input destination. On the message publisher’s side, the engine +generates a test that sends the input message to the defined destination. On the +consumer side, you can either send a message to the input destination or use a label +(some_label in the example) to trigger the message.

+
+
+
+

Consumer/Producer

+
+ + + + + +
+ + +This section is valid only for Groovy DSL. +
+
+
+

In HTTP, you have a notion of client/stub and `server/test notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the consumer and producer methods, as presented in the following example +(note that you can use either $ or value methods to provide consumer and producer +parts):

+
+
+
+
+
+
+
+
+

Common

+
+

In the input or outputMessage section you can call assertThat with the name +of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the +base class or in a static import. Spring Cloud Contract will execute that method +in the generated test.

+
+
+
+
+

Multiple Contracts in One File

+
+

You can define multiple contracts in one file. Such a contract might resemble the +following example:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

In the preceding example, one contract has the name field and the other does not. This +leads to generation of two tests that look more or less like this:

+
+
+
+
package org.springframework.cloud.contract.verifier.tests.com.hello;
+
+import com.example.TestBase;
+import com.jayway.jsonpath.DocumentContext;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
+import com.jayway.restassured.response.ResponseOptions;
+import org.junit.Test;
+
+import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
+import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class V1Test extends TestBase {
+
+	@Test
+	public void validate_should_post_a_user() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/1");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+	@Test
+	public void validate_withList_1() throws Exception {
+		// given:
+			MockMvcRequestSpecification request = given();
+
+		// when:
+			ResponseOptions response = given().spec(request)
+					.post("/users/2");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+	}
+
+}
+
+
+
+

Notice that, for the contract that has the name field, the generated test method is named +validate_should_post_a_user. For the one that does not have the name, it is called +validate_withList_1. It corresponds to the name of the file WithList.groovy and the +index of the contract in the list.

+
+
+

The generated stubs is shown in the following example:

+
+
+
+
should post a user.json
+1_WithList.json
+
+
+
+

As you can see, the first file got the name parameter from the contract. The second +got the name of the contract file (WithList.groovy) prefixed with the index (in this +case, the contract had an index of 1 in the list of contracts in the file).

+
+
+ + + + + +
+ + +As you can see, it is much better if you name your contracts because doing so makes +your tests far more meaningful. +
+
+
+
+

Generating Spring REST Docs snippets from the contracts

+
+

When you want to include the requests and responses of your API using Spring REST Docs, +you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. +Simply include the following dependencies if you haven’t already.

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+

Next you need to make some changes to your base class like the following example.

+
+
+
+
+
+
+
+

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

+
+
+
+
+
+
+
+ + + + + +
+ + +You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. +
+
+
+
+
+
+

Customization

+
+
+ + + + + +
+ + +This section is valid only for Groovy DSL +
+
+
+

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section.

+
+
+

Extending the DSL

+
+

You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of:

+
+
+
    +
  • +

    Creating a JAR with reusable classes.

    +
  • +
  • +

    Referencing of these classes in the DSLs.

    +
  • +
+
+
+

You can find the full example +here.

+
+
+

Common JAR

+
+

The following examples show three classes that can be reused in the DSLs.

+
+
+

PatternUtils contains functions used by both the consumer and the producer.

+
+
+
+
+
+
+
+

ConsumerUtils contains functions used by the consumer.

+
+
+
+
+
+
+
+

ProducerUtils contains functions used by the producer.

+
+
+
+
+
+
+
+
+

Adding the Dependency to the Project

+
+

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

+
+
+
+

Test the Dependency in the Project’s Dependencies

+
+

First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency:

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+

Test a Dependency in the Plugin’s Dependencies

+
+

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example:

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+

Referencing classes in DSLs

+
+

You can now reference your classes in your DSL, as shown in the following example:

+
+
+
+
+
+
+
+ + + + + +
+ + +You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. +
+
+
+
+
+
+
+

Using the Pluggable Architecture

+
+
+

You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations).

+
+
+

Custom Contract Converter

+
+

The ContractConverter interface lets you register your own implementation of a contract +structure converter. The following code listing shows the ContractConverter interface:

+
+
+
+
+
+
+
+

Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions.

+
+
+ + + + + +
+ + +Once you create your implementation, you must create a +/META-INF/spring.factories file in which you provide the fully qualified name of your +implementation. +
+
+
+

The following example shows a typical spring.factories file:

+
+
+
+
org.springframework.cloud.contract.spec.ContractConverter=\
+org.springframework.cloud.contract.verifier.converter.YamlContractConverter
+
+
+
+

Pact Converter

+
+

Spring Cloud Contract includes support for Pact representation of +contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. Note however that not all functionality is supported. +Starting with v3 you can combine multiple matcher for the same element; +you can use matchers for the body, headers, request and path; and you can use value generators. +Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. +Next to that the request and path matchers are skipped during the conversion. +When using a date, time or datetime value generator with a given format, +the given format will be skipped and the ISO format will be used.

+
+
+

In order to properly support the Spring Cloud Contract way of doing messaging +with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

+
+
+
    +
  • +

    to define the destination to which a message gets sent, you have to +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    +
  • +
+
+
+
+

Pact Contract

+
+

Consider following example of a Pact contract, which is a file under the +src/test/resources/contracts folder.

+
+
+
+
+
+
+
+

The remainder of this section about using Pact refers to the preceding file.

+
+
+
+

Pact for Producers

+
+

On the producer side, you must add two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use.

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+

When you execute the build of your application, a test will be generated. The generated +test might be as follows:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+	// given:
+		MockMvcRequestSpecification request = given()
+				.header("Content-Type", "application/vnd.fraud.v1+json")
+				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
+
+	// when:
+		ResponseOptions response = given().spec(request)
+				.put("/fraudcheck");
+
+	// then:
+		assertThat(response.statusCode()).isEqualTo(200);
+		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
+	// and:
+		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
+	// and:
+		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
+}
+
+
+
+

The corresponding generated stub might be as follows:

+
+
+
+
{
+  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
+  "request" : {
+    "url" : "/fraudcheck",
+    "method" : "PUT",
+    "headers" : {
+      "Content-Type" : {
+        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
+      }
+    },
+    "bodyPatterns" : [ {
+      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
+    }, {
+      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
+    } ]
+  },
+  "response" : {
+    "status" : 200,
+    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
+    "headers" : {
+      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
+    },
+    "transformers" : [ "response-template" ]
+  },
+}
+
+
+
+
+

Pact for Consumers

+
+

On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use.

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+
+

Using the Custom Test Generator

+
+

If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation.

+
+
+

The SingleTestGenerator interface lets you register your own implementation. The +following code listing shows the SingleTestGenerator interface:

+
+
+
+
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
+com.example.MyGenerator
+
+
+
+
+

Using the Custom Stub Generator

+
+

If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the StubGenerator interface. The following code listing shows the +StubGenerator interface:

+
+
+
+
+
+
+
+

Again, you must provide a spring.factories file, such as the one shown in the following +example:

+
+
+
+
+
+
+
+

The default implementation is the WireMock stub generation.

+
+
+ + + + + +
+ + +You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. +
+
+
+
+

Using the Custom Stub Runner

+
+

If you decide to use a custom stub generation, you also need a custom way of running +stubs with your different stub provider.

+
+
+

Assume that you use Moco to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file.

+
+
+

In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example:

+
+
+
+
+
+
+
+

Then, you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
+org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
+
+
+
+

Now you can run stubs with Moco.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. +
+
+
+
+

Using the Custom Stub Downloader

+
+

You can customize the way your stubs are downloaded by creating an implementation of the +StubDownloaderBuilder interface, as shown in the following example:

+
+
+
+
package com.example;
+
+class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
+
+	@Override
+	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
+		return new StubDownloader() {
+			@Override
+			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
+					StubConfiguration config) {
+				File unpackedStubs = retrieveStubs();
+				return new AbstractMap.SimpleEntry<>(
+						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
+								config.getClassifier()), unpackedStubs);
+			}
+
+			File retrieveStubs() {
+			    // here goes your custom logic to provide a folder where all the stubs reside
+			}
+}
+
+
+
+

Then you can register it in your spring.factories file, as shown in the following +example:

+
+
+
+
# Example of a custom Stub Downloader Provider
+org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
+com.example.CustomStubDownloaderBuilder
+
+
+
+

Now you can pick a folder with the source of your stubs.

+
+
+ + + + + +
+ + +If you do not provide any implementation, then the default is used (scan classpath). +If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or +, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used +If you provide more than one, then the first one on the list is used. +
+
+
+
+

Using the SCM Stub Downloader

+
+

Whenever the repositoryRoot starts with a SCM protocol +(currently we support only git://), the stub downloader will try +to clone the repository and use it as a source of contracts +to generate tests or stubs.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

+

* stubrunner.properties.git.branch (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

+

* stubrunner.properties.git.username (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

+

* stubrunner.properties.git.password (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

+

* stubrunner.properties.git.no-of-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

+

* stubrunner.properties.git.wait-between-attempts (system prop)

+

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

+
+
+

Using the Pact Stub Downloader

+
+

Whenever the repositoryRoot starts with a Pact protocol +(starts with pact://), the stub downloader will try +to fetch the Pact contract definitions from the Pact Broker. +Whatever is set after pact:// will be parsed as the Pact Broker URL.

+
+
+

Either via environment variables, system properties, properties set +inside the plugin or contracts repository configuration you can +tweak the downloader’s behaviour. Below you can find the list of +properties

+
+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

+

* stubrunner.properties.pactbroker.host (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

+

* stubrunner.properties.pactbroker.port (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

+

* stubrunner.properties.pactbroker.protocol (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

+

* stubrunner.properties.pactbroker.tags (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

+

* stubrunner.properties.pactbroker.auth.scheme (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

+

* stubrunner.properties.pactbroker.auth.username (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

+

* stubrunner.properties.pactbroker.auth.password (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

+

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

+

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_faq.html b/reference/html/verifier_faq.html new file mode 100644 index 0000000000..d03a388568 --- /dev/null +++ b/reference/html/verifier_faq.html @@ -0,0 +1,1540 @@ + + + + + + + +Spring Cloud Contract FAQ + + + + + + + + + + +
+
+

Spring Cloud Contract FAQ

+
+
+

Why use Spring Cloud Contract Verifier and not X ?

+
+

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating +software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make +Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

+
+
+
    +
  • +

    Possibility to do CDC with messaging

    +
  • +
  • +

    Clear and easy to use, statically typed DSL

    +
  • +
  • +

    Possibility to copy paste your current JSON file to the contract and only edit its elements

    +
  • +
  • +

    Automatic generation of tests from the defined Contract

    +
  • +
  • +

    Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory

    +
  • +
  • +

    Spring Cloud integration - no discovery service is needed for integration tests

    +
  • +
  • +

    Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality

    +
  • +
  • +

    Via Docker adds support for any language & framework used

    +
  • +
+
+
+
+

I don’t want to write a contract in Groovy!

+
+

No problem. You can write a contract in YAML!

+
+
+
+

What is this value(consumer(), producer()) ?

+
+

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. +What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. +Imagine the following JSON request

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

and JSON response

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the +database) by changing the clock in the system or providing stub implementations of data providers. The same is related +to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

+
+
+

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system +will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned +JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words +you would like the stub to work like this:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "foo"
+}
+
+
+
+

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

+
+
+
+
{
+    "time" : "2016-10-10 21:10:15",
+    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
+    "body" : "bar"
+}
+
+
+
+

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks +much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. +So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the +producer’s backend can work on. Such a JSON would be a valid one:

+
+
+
+
{
+    "time" : "2016-10-10 20:10:15",
+    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
+    "body" : "foo"
+}
+
+
+
+

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to +contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d +have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side +what you might want is the following response:

+
+
+
+
{
+    "time" : "SOMETHING THAT MATCHES TIME",
+    "id" : "SOMETHING THAT MATCHES UUID",
+    "body" : "bar"
+}
+
+
+
+

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? +In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both +sides of the communication. You can pass the values:

+
+
+

Either via the value method

+
+
+
+
value(consumer(...), producer(...))
+value(stub(...), test(...))
+value(client(...), server(...))
+
+
+
+

or using the $() method

+
+
+
+
$(consumer(...), producer(...))
+$(stub(...), test(...))
+$(client(...), server(...))
+
+
+
+

You can read more about this in the [contract-dsl] section.

+
+
+

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). +Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

+
+
+ + + + + +
+ + +If on one side you have passed the regular expression and you haven’t passed the other, then the +other side will get auto-generated. +
+
+
+

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

+
+
+

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression +for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

+
+
+
+
org.springframework.cloud.contract.spec.Contract.make {
+				request {
+					method 'GET'
+					url '/someUrl'
+					body([
+					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "foo"
+					])
+				}
+			response {
+				status OK()
+				body([
+					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
+					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
+					    body: "bar"
+					])
+			}
+}
+
+
+
+ + + + + +
+ + +Please read the Groovy docs related to JSON to understand how to +properly structure the request / response bodies. +
+
+
+
+

How to do Stubs versioning?

+
+

API Versioning

+
+

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are +different approaches.

+
+
+
    +
  • +

    use Hypermedia, links and do not version your API by any means

    +
  • +
  • +

    pass versions through headers / urls

    +
  • +
+
+
+

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate +business value should be picked.

+
+
+

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. +You can create a subfolder for every version or append it to the contract name - whatever suits you more.

+
+
+
+

JAR versioning

+
+

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

+
+
+

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of +the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version +looks like this (it got built on the 20.10.2016 at 20:15:21) :

+
+
+
+
1.0.0.20161020-201521-RELEASE
+
+
+
+

In that case your generated stub jar will look like this.

+
+
+
+
1.0.0.20161020-201521-RELEASE-stubs.jar
+
+
+
+

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the + latest version of the stubs. You can do that by passing the + sign. Example

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar +version. Example for 2.1.1.

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
+
+
+
+
+

Dev or prod stubs

+
+

You can manipulate the classifier to run the tests against current development version of the stubs of other services + or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier + once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

+
+
+

Example of tests using development version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
+
+
+
+

Example of tests using production version of stubs

+
+
+
+
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
+
+
+
+

You can pass those values also via properties from your deployment pipeline.

+
+
+
+
+

Common repo with contracts

+
+

Another way of storing contracts other than having them with the producer is keeping them in a common place. +It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep +contracts in a single place then you, as a producer, will know how many consumers you have and which +consumer you will break with your local changes.

+
+
+

Repo structure

+
+

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, +client2, client3. Then in the repository with common contracts you would have the following setup +(which you can checkout here):

+
+
+
+
├── com
+│   └── example
+│       └── server
+│           ├── client1
+│           │   └── expectation.groovy
+│           ├── client2
+│           │   └── expectation.groovy
+│           ├── client3
+│           │   └── expectation.groovy
+│           └── pom.xml
+├── mvnw
+├── mvnw.cmd
+├── pom.xml
+└── src
+    └── assembly
+        └── contracts.xml
+
+
+
+

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have +expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL +contract files as described throughout this documentation. This repository has to produce a JAR file that maps +one to one to the contents of the repo.

+
+
+

Example of a pom.xml inside the server folder.

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example</groupId>
+	<artifactId>server</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Server Stubs</name>
+	<description>POM used to install locally stubs for consumer side</description>
+
+	<parent>
+		<groupId>org.springframework.boot</groupId>
+		<artifactId>spring-boot-starter-parent</artifactId>
+		<version>2.2.0.M4</version>
+		<relativePath/>
+	</parent>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+		<java.version>1.8</java.version>
+		<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
+		<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
+		<excludeBuildFolders>true</excludeBuildFolders>
+	</properties>
+
+	<dependencyManagement>
+		<dependencies>
+			<dependency>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-dependencies</artifactId>
+				<version>${spring-cloud-release.version}</version>
+				<type>pom</type>
+				<scope>import</scope>
+			</dependency>
+		</dependencies>
+	</dependencyManagement>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.springframework.cloud</groupId>
+				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+				<version>${spring-cloud-contract.version}</version>
+				<extensions>true</extensions>
+				<configuration>
+					<!-- By default it would search under src/test/resources/ -->
+					<contractsDirectory>${project.basedir}</contractsDirectory>
+				</configuration>
+			</plugin>
+		</plugins>
+	</build>
+
+	<repositories>
+		<repository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+		<repository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</repository>
+	</repositories>
+	<pluginRepositories>
+		<pluginRepository>
+			<id>spring-snapshots</id>
+			<name>Spring Snapshots</name>
+			<url>https://repo.spring.io/snapshot</url>
+			<snapshots>
+				<enabled>true</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-milestones</id>
+			<name>Spring Milestones</name>
+			<url>https://repo.spring.io/milestone</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+		<pluginRepository>
+			<id>spring-releases</id>
+			<name>Spring Releases</name>
+			<url>https://repo.spring.io/release</url>
+			<snapshots>
+				<enabled>false</enabled>
+			</snapshots>
+		</pluginRepository>
+	</pluginRepositories>
+
+</project>
+
+
+
+

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. +Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install + stubs of the producer project.

+
+
+

The pom.xml in the root folder can look like this:

+
+
+
+
<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		 xmlns="http://maven.apache.org/POM/4.0.0"
+		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+
+	<groupId>com.example.standalone</groupId>
+	<artifactId>contracts</artifactId>
+	<version>0.0.1-SNAPSHOT</version>
+
+	<name>Contracts</name>
+	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
+		producers to generate tests and stubs
+	</description>
+
+	<properties>
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+	</properties>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.apache.maven.plugins</groupId>
+				<artifactId>maven-assembly-plugin</artifactId>
+				<executions>
+					<execution>
+						<id>contracts</id>
+						<phase>prepare-package</phase>
+						<goals>
+							<goal>single</goal>
+						</goals>
+						<configuration>
+							<attach>true</attach>
+							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
+							<!-- If you want an explicit classifier remove the following line -->
+							<appendAssemblyId>false</appendAssemblyId>
+						</configuration>
+					</execution>
+				</executions>
+			</plugin>
+		</plugins>
+	</build>
+
+</project>
+
+
+
+

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

+
+
+
+
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
+		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
+	<id>project</id>
+	<formats>
+		<format>jar</format>
+	</formats>
+	<includeBaseDirectory>false</includeBaseDirectory>
+	<fileSets>
+		<fileSet>
+			<directory>${project.basedir}</directory>
+			<outputDirectory>/</outputDirectory>
+			<useDefaultExcludes>true</useDefaultExcludes>
+			<excludes>
+				<exclude>**/${project.build.directory}/**</exclude>
+				<exclude>mvnw</exclude>
+				<exclude>mvnw.cmd</exclude>
+				<exclude>.mvn/**</exclude>
+				<exclude>src/**</exclude>
+			</excludes>
+		</fileSet>
+	</fileSets>
+</assembly>
+
+
+
+
+

Workflow

+
+

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference + is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on + common contracts in a common repository.

+
+
+
+

Consumer

+
+

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the +consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) +and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

+
+
+ + + + + +
+ + +You need to have Maven installed locally +
+
+
+
+

Producer

+
+

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency +of the JAR containing the contracts:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<configuration>
+		<contractsMode>REMOTE</contractsMode>
+		<contractsRepositoryUrl>
+			https://link/to/your/nexus/or/artifactory/or/sth
+		</contractsRepositoryUrl>
+		<contractDependency>
+			<groupId>com.example.standalone</groupId>
+			<artifactId>contracts</artifactId>
+		</contractDependency>
+	</configuration>
+</plugin>
+
+
+
+

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from https://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the +tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken +when some incompatible changes are done.

+
+
+

The rest of the flow looks the same.

+
+
+
+

How can I define messaging contracts per topic not per producer?

+
+

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, +we could create the structure when the rest contracts would be placed in a folder per producer and messaging +contracts in the folder per topic.

+
+
+
For Maven Project
+
+

To make it possible to work on the producer side we should specify an inclusion pattern for +filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin +allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

+
+
+
+
<plugin>
+   <groupId>org.springframework.cloud</groupId>
+   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+   <version>${spring-cloud-contract.version}</version>
+   <configuration>
+      <contractsMode>REMOTE</contractsMode>
+      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
+      <contractDependency>
+         <groupId>com.example</groupId>
+         <artifactId>common-repo-with-contracts</artifactId>
+         <version>+</version>
+      </contractDependency>
+      <contractsPath>/</contractsPath>
+      <baseClassMappings>
+         <baseClassMapping>
+            <contractPackageRegex>.*messaging.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
+         </baseClassMapping>
+         <baseClassMapping>
+            <contractPackageRegex>.*rest.*</contractPackageRegex>
+            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
+         </baseClassMapping>
+      </baseClassMappings>
+      <includedFiles>
+         <includedFile>**/${project.artifactId}/**</includedFile>
+         <includedFile>**/${first-topic}/**</includedFile>
+         <includedFile>**/${second-topic}/**</includedFile>
+      </includedFiles>
+   </configuration>
+</plugin>
+
+
+
+
+
For Gradle Project
+
+
    +
  • +

    Add a custom configuration for the common-repo dependency:

    +
  • +
+
+
+
+
ext {
+    conractsGroupId = "com.example"
+    contractsArtifactId = "common-repo"
+    contractsVersion = "1.2.3"
+}
+
+configurations {
+    contracts {
+        transitive = false
+    }
+}
+
+
+
+
    +
  • +

    Add the common-repo dependency to your classpath:

    +
  • +
+
+
+
+
dependencies {
+    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
+}
+
+
+
+
    +
  • +

    Download the dependency to an appropriate folder:

    +
  • +
+
+
+
+
task getContracts(type: Copy) {
+    from configurations.contracts
+    into new File(project.buildDir, "downloadedContracts")
+}
+
+
+
+
    +
  • +

    Unzip JAR:

    +
  • +
+
+
+
+
task unzipContracts(type: Copy) {
+    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
+    def outputDir = file("${buildDir}/unpackedContracts")
+
+    from zipTree(zipFile)
+    into outputDir
+}
+
+
+
+
    +
  • +

    Cleanup unused contracts:

    +
  • +
+
+
+
+
task deleteUnwantedContracts(type: Delete) {
+    delete fileTree(dir: "${buildDir}/unpackedContracts",
+        include: "**/*",
+        excludes: [
+            "**/${project.name}/**"",
+            "**/${first-topic}/**",
+            "**/${second-topic}/**"])
+}
+
+
+
+
    +
  • +

    Create task dependencies:

    +
  • +
+
+
+
+
unzipContracts.dependsOn("getContracts")
+deleteUnwantedContracts.dependsOn("unzipContracts")
+build.dependsOn("deleteUnwantedContracts")
+
+
+
+
    +
  • +

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

    +
  • +
+
+
+
+
contracts {
+    contractsDslDir = new File("${buildDir}/unpackedContracts")
+}
+
+
+
+
+
+
+

Do I need a Binary Storage? Can’t I use Git?

+
+

In the polyglot world, there are languages that don’t use binary storages like +Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide +mechanisms to store contracts and stubs in a SCM repository. Currently the +only supported SCM is Git.

+
+
+

The repository would have to the following setup +(which you can checkout here):

+
+
+
+
.
+└── META-INF
+    └── com.example
+        └── beer-api-producer-git
+            └── 0.0.1-SNAPSHOT
+                ├── contracts
+                │   └── beer-api-consumer
+                │       ├── messaging
+                │       │   ├── shouldSendAcceptedVerification.groovy
+                │       │   └── shouldSendRejectedVerification.groovy
+                │       └── rest
+                │           ├── shouldGrantABeerIfOldEnough.groovy
+                │           └── shouldRejectABeerIfTooYoung.groovy
+                └── mappings
+                    └── beer-api-consumer
+                        └── rest
+                            ├── shouldGrantABeerIfOldEnough.json
+                            └── shouldRejectABeerIfTooYoung.json
+
+
+
+

Under META-INF folder:

+
+
+
    +
  • +

    we group applications via groupId (e.g. com.example)

    +
  • +
  • +

    then each application is represented via the artifactId (e.g. beer-api-producer-git)

    +
  • +
  • +

    next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    +
    +
      +
    • +

      + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT

        +
      • +
      • +

        if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called latest or + we will pick that folder

        +
      • +
      +
      +
    • +
    • +

      release - to find the latest release version of your stubs. That means:

      +
      +
        +
      • +

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        +
      • +
      • +

        if you have a version called release we will pick that folder

        +
      • +
      +
      +
    • +
    +
    +
  • +
  • +

    finally, there are two folders:

    +
    +
      +
    • +

      contracts - the good practice is to store the contracts required by each +consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you +can use the stubs-per-consumer feature. Further directory structure is arbitrary.

      +
    • +
    • +

      mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push +the stub server mappings. On the consumer side, Stub Runner will scan this folder +to start stub servers with stub definitions. The folder structure will be a copy +of the one created in the contracts subfolder.

      +
    • +
    +
    +
  • +
+
+
+

Protocol convention

+
+

In order to control the type and location of the source of contracts (whether it’s +a binary storage or an SCM repository), you can use the protocol in the URL of +the repository. Spring Cloud Contract iterates over registered protocol resolvers +and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

+
+
+

For the SCM functionality, currently, we support the Git repository. To use it, +in the property, where the repository URL needs to be placed you just have to prefix +the connection URL with git://. Here you can find a couple of examples:

+
+
+
+
git://file:///foo/bar
+git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
+
+
+
+
+

Producer

+
+

For the producer, to use the SCM approach, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the SCM implementation via the URL that contains +the git:// protocol.

+
+
+ + + + + +
+ + +You have to manually add the pushStubsToScm +goal in Maven or execute (bind) the pushStubsToScm task in +Gradle. We don’t push stubs to origin of your git +repository out of the box. +
+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+
Gradle
+
+
contracts {
+	// We want to pick contracts from a Git repository
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:${project.version}"
+	}
+	/*
+	We reuse the contract dependency section to set up the path
+	to the folder that contains the contract definitions. In our case the
+	path will be /groupId/artifactId/version/contracts
+	 */
+	contractRepository {
+		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+/*
+In this scenario we want to publish stubs to SCM whenever
+the `publish` task is executed
+*/
+publish.dependsOn("publishStubsToScm")
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder +to find contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/contracts

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass, the stubs will be committed in the cloned repository

    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
+

Producer with contracts stored locally

+
+

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Contracts from the default src/test/resources/contracts directory will be picked

    +
  • +
  • +

    Tests will be generated from the contracts

    +
  • +
  • +

    Stubs will be created from the contracts

    +
  • +
  • +

    Once the tests pass

    +
    +
      +
    • +

      Git project will be cloned to a temporary directory

      +
    • +
    • +

      The stubs and contracts will be committed in the cloned repository

      +
    • +
    +
    +
  • +
  • +

    Finally, a push will be done to that repo’s origin

    +
  • +
+
+
+
Keeping contracts with the producer and stubs in an external repository
+
+

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. +This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to +use an artifact repository for storing the stubs.

+
+
+

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set +contractsRepositoryUrl to the repository where you want to keep the stubs.

+
+
+
+
+

Consumer

+
+

On the consumer side when passing the repositoryRoot parameter, +either from the @AutoConfigureStubRunner annotation, the +JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the +SCM repository, prefixed with the protocol. For example

+
+
+
+
@AutoConfigureStubRunner(
+    stubsMode="REMOTE",
+    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
+    ids="com.example:bookstore:0.0.1.RELEASE"
+)
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Git project will be cloned to a temporary directory

    +
  • +
  • +

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder +to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be +META-INF/com.example/foo/1.0.0/

    +
  • +
  • +

    Stub servers will be started and fed with mappings

    +
  • +
  • +

    Messaging definitions will be read and used in the messaging tests

    +
  • +
+
+
+
+
+

Can I use the Pact Broker?

+
+

When using Pact you can use the Pact Broker +to store and share Pact definitions. Starting from Spring Cloud Contract +2.0.0 one can fetch Pact files from the Pact Broker to generate +tests and stubs.

+
+
+

As a prerequisite the Pact Converter and Pact Stub Downloader +are required. You have to add them via the spring-cloud-contract-pact dependency. +You can read more about it in the [pact-converter] section.

+
+
+ + + + + +
+ + +Pact follows the Consumer Contract convention. That means +that the Consumer creates the Pact definitions first, then +shares the files with the Producer. Those expectations are generated +from the Consumer’s code and can break the Producer if the expectations +are not met. +
+
+
+

Pact Consumer

+
+

The consumer uses Pact framework to generate Pact files. The +Pact files are sent to the Pact Broker. An example of such +setup can be found here.

+
+
+
+

Producer

+
+

For the producer, to use the Pact files from the Pact Broker, we can reuse the +same mechanism we use for external contracts. We route Spring Cloud Contract +to use the Pact implementation via the URL that contains +the pact:// protocol. It’s enough to pass the URL to the +Pact Broker. An example of such setup can be found here.

+
+
+
Maven
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
+            <version>+</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-pact</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+    </dependencies>
+</plugin>
+
+
+
+
Gradle
+
+
buildscript {
+	repositories {
+		//...
+	}
+
+	dependencies {
+		// ...
+		// Don't forget to add spring-cloud-contract-pact to the classpath!
+		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
+	}
+}
+
+contracts {
+	// When + is passed, a latest tag will be applied when fetching pacts
+	contractDependency {
+		stringNotation = "${project.group}:${project.name}:+"
+	}
+	contractRepository {
+		repositoryUrl = "pact://http://localhost:8085"
+	}
+	// The mode can't be classpath
+	contractsMode = "REMOTE"
+	// Base class mappings etc.
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into tests and stubs

    +
  • +
  • +

    The JAR with the stubs gets automatically created as usual

    +
  • +
+
+
+
+

Pact Consumer (Producer Contract approach)

+
+

In the scenario where you don’t want to do Consumer Contract approach +(for every single consumer define the expectations) but you’d prefer +to do Producer Contracts (the producer provides the contracts and +publishes stubs), it’s enough to use Spring Cloud Contract with +Stub Runner option. An example of such setup can be found here.

+
+
+

First, remember to add Stub Runner and Spring Cloud Contract Pact module +as test dependencies.

+
+
+
Maven
+
+
<dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-dependencies</artifactId>
+            <version>${spring-cloud.version}</version>
+            <type>pom</type>
+            <scope>import</scope>
+        </dependency>
+    </dependencies>
+</dependencyManagement>
+
+<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
+<dependencies>
+    <!-- ... -->
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
+        <scope>test</scope>
+    </dependency>
+    <dependency>
+        <groupId>org.springframework.cloud</groupId>
+        <artifactId>spring-cloud-contract-pact</artifactId>
+        <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+
Gradle
+
+
dependencyManagement {
+    imports {
+        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
+    }
+}
+
+dependencies {
+    //...
+    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
+    // Don't forget to add spring-cloud-contract-pact to the classpath!
+    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
+}
+
+
+
+

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed +with pact:// protocol. E.g. pact://http://localhost:8085

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest
+@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
+		ids = "com.example:beer-api-producer-pact",
+		repositoryRoot = "pact://http://localhost:8085")
+public class BeerControllerTest {
+    //Inject the port of the running stub
+    @StubRunnerPort("beer-api-producer-pact") int producerPort;
+    //...
+}
+
+
+
+

With such a setup:

+
+
+
    +
  • +

    Pact files will be downloaded from the Pact Broker

    +
  • +
  • +

    Spring Cloud Contract will convert the Pact files into stub definitions

    +
  • +
  • +

    The stub servers will be started and fed with stubs

    +
  • +
+
+
+

For more information about Pact support you can go to +the [pact-stub-downloader] section.

+
+
+
+
+

How can I debug the request/response being sent by the generated tests client?

+
+

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

+
+
+
+
logging.level.org.apache.http.wire=DEBUG
+
+
+
+

How can I debug the mapping/request/response being sent by WireMock?

+
+

Starting from version 1.2.0 we turn on WireMock logging to +info and the WireMock notifier to being verbose. Now you will +exactly know what request was received by WireMock server and which +matching response definition was picked.

+
+
+

To turn off this feature just bump WireMock logging to ERROR

+
+
+
+
logging.level.com.github.tomakehurst.wiremock=ERROR
+
+
+
+
+

How can I see what got registered in the HTTP server stub?

+
+

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or +`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server +was started will be attached.

+
+
+
+

Can I reference text from file?

+
+

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays. +If you’re using YAML just use the bodyFromFile property.

+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_introduction.html b/reference/html/verifier_introduction.html new file mode 100644 index 0000000000..523f98c284 --- /dev/null +++ b/reference/html/verifier_introduction.html @@ -0,0 +1,1607 @@ + + + + + + + +Spring Cloud Contract Verifier Introduction + + + + + + + + + + +
+
+

Spring Cloud Contract Verifier Introduction

+
+
+

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture.

+
+
+

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract +definitions are used to produce the following resources:

+
+
+
    +
  • +

    JSON stub definitions to be used by WireMock when doing integration testing on the +client code (client tests). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier.

    +
  • +
  • +

    Messaging routes, if you’re using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations.

    +
  • +
  • +

    Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (server tests). A full test is generated by +Spring Cloud Contract Verifier.

    +
  • +
+
+
+

History

+
+

Before becoming Spring Cloud Contract, this project was called Accurest. +It was created by Marcin Grzejszczak and Jakub Kubrynski +from (Codearte.

+
+
+

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

+
+
+
+

Why a Contract Verifier?

+
+

Assume that we have a system consisting of multiple microservices:

+
+
+

Testing issues

+
+

If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things:

+
+
+
    +
  • +

    Deploy all microservices and perform end-to-end tests.

    +
  • +
  • +

    Mock other microservices in unit/integration tests.

    +
  • +
+
+
+

Both have their advantages but also a lot of disadvantages.

+
+
+

Deploy all microservices and perform end to end tests

+
+
+

Advantages:

+
+
+
    +
  • +

    Simulates production.

    +
  • +
  • +

    Tests real communication between services.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc.

    +
  • +
  • +

    The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime).

    +
  • +
  • +

    They take a long time to run.

    +
  • +
  • +

    The feedback comes very late in the process.

    +
  • +
  • +

    They are extremely hard to debug.

    +
  • +
+
+
+

Mock other microservices in unit/integration tests

+
+
+

Advantages:

+
+
+
    +
  • +

    They provide very fast feedback.

    +
  • +
  • +

    They have no infrastructure requirements.

    +
  • +
+
+
+

Disadvantages:

+
+
+
    +
  • +

    The implementor of the service creates stubs that might have nothing to do with +reality.

    +
  • +
  • +

    You can go to production with passing tests and failing production.

    +
  • +
+
+
+

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses.

+
+
+

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you’re calling. Also, if you can use them, it means that they +were tested against the producer’s side. In short, you can trust those stubs.

+
+
+
+
+

Purposes

+
+

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

+
+
+
    +
  • +

    To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does.

    +
  • +
  • +

    To promote ATDD method and Microservices architectural style.

    +
  • +
  • +

    To provide a way to publish changes in contracts that are immediately visible on both +sides.

    +
  • +
  • +

    To generate boilerplate test code to be used on the server side.

    +
  • +
+
+
+ + + + + +
+ + +Spring Cloud Contract Verifier’s purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. +
+
+
+
+

How It Works

+
+

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

+
+
+

A Three-second Tour

+
+

This very brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find a somewhat longer tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as +shown in the following example:

+
+
+
+
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the tests get generated under +org.springframework.cloud.contract.verifier.tests..

+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of either handling HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests, and it +should contain all the setup necessary to run them (for example RestAssuredMockMvc +controller setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +The changes can now be merged, and both the application and the stub artifacts may be +published in an online repository.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the +following example:

+
+
+
+
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the stubs +by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are being skipped because the Producer-side contract implementation is not +in place yet, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    By getting already-existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract +Stub Runner properties, as shown in the following example:

    +
    +
    +
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to +run the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

Now, in your integration test, you can receive stubbed versions of HTTP responses or +messages that are expected to be emitted by the collaborator service.

+
+
+
+
+

A Three-minute Tour

+
+

This brief tour walks through using Spring Cloud Contract:

+
+ +
+

You can find an even more brief tour +here.

+
+
+
On the Producer Side
+
+

To start working with Spring Cloud Contract, add files with REST/ messaging contracts +expressed in either Groovy DSL or YAML to the contracts directory, which is set by the +contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

+
+
+

For the HTTP stubs, a contract defines what kind of response should be returned for a +given request (taking into account the HTTP methods, URLs, headers, status codes, and so +on). The following example shows how an HTTP stub contract in Groovy DSL:

+
+
+
+
package contracts
+
+org.springframework.cloud.contract.spec.Contract.make {
+	request {
+		method 'PUT'
+		url '/fraudcheck'
+		body([
+			   "client.id": $(regex('[0-9]{10}')),
+			   loanAmount: 99999
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+	response {
+		status OK()
+		body([
+			   fraudCheckStatus: "FRAUD",
+			   "rejection.reason": "Amount too high"
+		])
+		headers {
+			contentType('application/json')
+		}
+	}
+}
+
+
+
+

The same contract expressed in YAML would look like the following example:

+
+
+
+
request:
+  method: PUT
+  url: /fraudcheck
+  body:
+    "client.id": 1234567890
+    loanAmount: 99999
+  headers:
+    Content-Type: application/json
+  matchers:
+    body:
+      - path: $.['client.id']
+        type: by_regex
+        value: "[0-9]{10}"
+response:
+  status: 200
+  body:
+    fraudCheckStatus: "FRAUD"
+    "rejection.reason": "Amount too high"
+  headers:
+    Content-Type: application/json;charset=UTF-8
+
+
+
+

In the case of messaging, you can define:

+
+
+
    +
  • +

    The input and the output messages can be defined (taking into account from and where it +was sent, the message body, and the header).

    +
  • +
  • +

    The methods that should be called after the message is received.

    +
  • +
  • +

    The methods that, when called, should trigger a message.

    +
  • +
+
+
+

The following example shows a Camel messaging contract expressed in Groovy DSL:

+
+
+
+
+
+
+
+

The following example shows the same contract expressed in YAML:

+
+
+
+
+
+
+
+

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, +as shown in the following example:

+
+
+
+
+
+
+
+

The following listing shows how to add the plugin, which should go in the build/plugins +portion of the file:

+
+
+
+
<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+</plugin>
+
+
+
+

Running ./mvnw clean install automatically generates tests that verify the application +compliance with the added contracts. By default, the generated tests are under +org.springframework.cloud.contract.verifier.tests..

+
+
+

The following example shows a sample auto-generated test for an HTTP contract:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

The preceding example uses Spring’s MockMvc to run the tests. This is the default test +mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be +used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, +respectively.)

+
+
+

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient +run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. +In order to use WebTestClient set testMode to WEBTESTCLIENT.

+
+
+

Here is an example of a test generated in WEBTESTCLIENT test mode:

+
+
+
+
[source,java,indent=0]
+
+
+
+
+
@Test
+	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
+		// given:
+			WebTestClientRequestSpecification request = given()
+					.header("Content-Type", "application/json")
+					.body("{\"age\":10}");
+
+		// when:
+			WebTestClientResponse response = given().spec(request)
+					.post("/check");
+
+		// then:
+			assertThat(response.statusCode()).isEqualTo(200);
+			assertThat(response.header("Content-Type")).matches("application/json.*");
+		// and:
+			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
+	}
+
+
+
+

Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin +testFramework property to either JUNIT5, TESTNG or Spock.

+
+
+ + + + + +
+ + +You can now also generate WireMock scenarios based on the contracts, by including an +order number followed by an underscore at the beginning of the contract file names. +
+
+
+

The following example shows an auto-generated test in Spock for a messaging stub contract:

+
+
+
+
[source,groovy,indent=0]
+
+
+
+
+
given:
+	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
+		\'\'\'{"bookName":"foo"}\'\'\',
+		['sample': 'header']
+	)
+
+when:
+	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
+
+then:
+	 noExceptionThrown()
+	 bookWasDeleted()
+
+
+
+

As the implementation of the functionalities described by the contracts is not yet +present, the tests fail.

+
+
+

To make them pass, you must add the correct implementation of handling either HTTP +requests or messages. Also, you must add a correct base test class for auto-generated +tests to the project. This class is extended by all the auto-generated tests and should +contain all the setup necessary to run them (for example, RestAssuredMockMvc controller +setup or messaging test setup).

+
+
+

Once the implementation and the test base class are in place, the tests pass, and both the +application and the stub artifacts are built and installed in the local Maven repository. +Information about installing the stubs jar to the local repository appears in the logs, as +shown in the following example:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

You can now merge the changes and publish both the application and the stub artifacts +in an online repository.

+
+
+

Docker Project

+
+
+

In order to enable working with contracts while creating applications in non-JVM +technologies, the springcloud/spring-cloud-contract Docker image has been created. It +contains a project that automatically generates tests for HTTP contracts and executes them +in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, +optionally, publishes them to an artifact manager. In order to use the image, you can +mount the contracts into the /contracts directory and set a few environment variables.

+
+
+
+
On the Consumer Side
+
+

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running +WireMock instance or messaging route that simulates the actual service.

+
+
+

To get started, add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
+
+
+
+

You can get the Producer-side stubs installed in your Maven repository in either of two +ways:

+
+
+
    +
  • +

    By checking out the Producer side repository and adding contracts and generating the +stubs by running the following commands:

    +
    +
    +
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    +
    +
    +
    + + + + + +
    + + +The tests are skipped because the Producer-side contract implementation is not yet +in place, so the automatically-generated contract tests fail. +
    +
    +
  • +
  • +

    Getting already existing producer service stubs from a remote repository. To do so, +pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub +Runner properties, as shown in the following example:

    +
    +
    +
    +
    +
    +
  • +
+
+
+

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, +provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run +the collaborators' stubs for you, as shown in the following example:

+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment=WebEnvironment.NONE)
+@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
+		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
+public class LoanApplicationServiceTests {
+
+
+
+ + + + + +
+ + +Use the REMOTE stubsMode when downloading stubs from an online repository and +LOCAL for offline work. +
+
+
+

In your integration test, you can receive stubbed versions of HTTP responses or messages +that are expected to be emitted by the collaborator service. You can see entries similar +to the following in the build logs:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+
+
+

Defining the Contract

+
+

As consumers of services, we need to define what exactly we want to achieve. We need to +formulate our expectations. That is why we write contracts.

+
+
+

Assume that you want to send a request containing the ID of a client company and the +amount it wants to borrow from us. You also want to send it to the /fraudcheck url via +the PUT method.

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+
+

Client Side

+
+

Spring Cloud Contract generates stubs, which you can use during client-side testing. +You get a running WireMock instance/Messaging route that simulates the service. +You would like to feed that instance with a proper stub definition.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service.

+
+
+
+
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

+
+
+
+
+
+
+
+

After that, during the tests, Spring Cloud Contract automatically finds the stubs +(simulating the real service) in the Maven repository and exposes them on a configured +(or random) port.

+
+
+
+

Server Side

+
+

Since you are developing your stub, you need to be sure that it actually resembles your +concrete implementation. You cannot have a situation where your stub acts in one way and +your application behaves in a different way, especially in production.

+
+
+

To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide.

+
+
+

The autogenerated test looks, more or less, like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+
+
+

Step-by-step Guide to Consumer Driven Contracts (CDC)

+
+

Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody.

+
+
+

Assume that Loan Issuance is a client to the Fraud Detection server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud.

+
+
+

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan +Issuance has an artifact-id of http-client, and both have a group-id of com.example.

+
+
+

Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication.

+
+ +
+ + + + + +
+ + +In this case, the producer owns the contracts. Physically, all the contract are +in the producer’s repository. +
+
+
+

Technical note

+
+

If using the SNAPSHOT / Milestone / Release Candidate versions please add the +following section to your build:

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+

Consumer side (Loan Issuance)

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

+
+
+
    +
  1. +

    Start doing TDD by writing a test for your feature.

    +
  2. +
  3. +

    Write the missing implementation.

    +
  4. +
  5. +

    Clone the Fraud Detection service repository locally.

    +
  6. +
  7. +

    Define the contract locally in the repo of Fraud Detection service.

    +
  8. +
  9. +

    Add the Spring Cloud Contract Verifier plugin.

    +
  10. +
  11. +

    Run the integration tests.

    +
  12. +
  13. +

    File a pull request.

    +
  14. +
  15. +

    Create an initial implementation.

    +
  16. +
  17. +

    Take over the pull request.

    +
  18. +
  19. +

    Write the missing implementation.

    +
  20. +
  21. +

    Deploy your app.

    +
  22. +
  23. +

    Work online.

    +
  24. +
+
+
+

Start doing TDD by writing a test for your feature.

+
+
+
+
+
+
+
+

Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description.

+
+
+

Write the missing implementation.

+
+
+

At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

+
+
+
+
+
+
+
+

For simplicity, the port of the Fraud Detection service is set to 8080, and the +application runs on 8090.

+
+
+

If you start the test at this point, it breaks, because no service currently runs on port +8080.

+
+
+

Clone the Fraud Detection service repository locally.

+
+
+

You can start by playing around with the server side contract. To do so, you must first +clone it.

+
+
+
+
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
+
+
+
+

Define the contract locally in the repo of Fraud Detection service.

+
+
+

As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract:

+
+
+ + + + + +
+ + +Place the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important because the producer’s test base class name references that folder. +
+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

The YML contract is quite straight-forward. However when you take a look at the Contract +written using a statically typed Groovy DSL - you might wonder what the +value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. +Consult the [contract-dsl] section for more information. We highly recommend using the map notation!

+
+
+ + + + + +
+ + +You must understand the map notation in order to set up contracts. Please read the +Groovy docs regarding JSON. +
+
+
+

The previously shown contract is an agreement between two sides that:

+
+
+
    +
  • +

    if an HTTP request is sent with all of

    +
    +
      +
    • +

      a PUT method on the /fraudcheck endpoint,

      +
    • +
    • +

      a JSON body with a client.id that matches the regular expression [0-9]{10} and +loanAmount equal to 99999,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json,

      +
    • +
    +
    +
  • +
  • +

    then an HTTP response is sent to the consumer that

    +
    +
      +
    • +

      has status 200,

      +
    • +
    • +

      contains a JSON body with the fraudCheckStatus field containing a value FRAUD and +the rejectionReason field having value Amount too high,

      +
    • +
    • +

      and a Content-Type header with a value of application/vnd.fraud.v1+json.

      +
    • +
    +
    +
  • +
+
+
+

Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally.

+
+
+

Add the Spring Cloud Contract Verifier plugin.

+
+
+

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the Spring Cloud Contract BOM.

+
+
+
+
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin

+
+
+
+
+
+
+
+

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, +from the provided contracts:

+
+
+
    +
  • +

    generate and run tests

    +
  • +
  • +

    produce and install stubs

    +
  • +
+
+
+

You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute:

+
+
+
+
$ cd local-http-server-repo
+$ ./mvnw clean install -DskipTests
+
+
+
+

In the logs, you see something like this:

+
+
+
+
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
+[INFO]
+[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
+[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
+[INFO]
+[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
+[INFO]
+[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
+[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
+[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

The following line is extremely important:

+
+
+
+
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+
+
+
+

It confirms that the stubs of the http-server have been installed in the local +repository.

+
+
+

Run the integration tests.

+
+
+

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (Loan +Application service):

+
+
+

Add the Spring Cloud Contract BOM:

+
+
+
+
+
+
+
+

Add the dependency to Spring Cloud Contract Stub Runner:

+
+
+
+
+
+
+
+

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the +group-id and artifact-id for the Stub Runner to download the stubs of your +collaborators. (Optional step) Because you’re playing with the collaborators offline, you +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

+
+
+
+
+
+
+
+

Now, when you run your tests, you see something like this:

+
+
+
+
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
+2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
+2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
+2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
+2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
+2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
+2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
+
+
+
+

This output means that Stub Runner has found your stubs and started a server for your app +with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of +the stubs and with stubs classifier on port 8080.

+
+
+

File a pull request.

+
+
+

What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish.

+
+
+

Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done.

+
+
+
+

Producer side (Fraud Detection server)

+
+

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

+
+
+

Create an initial implementation.

+
+
+

As a reminder, you can see the initial implementation here:

+
+
+
+
}
+
+
+
+

Take over the pull request.

+
+
+
+
$ git checkout -b contract-change-pr master
+$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
+
+
+
+

You must add the dependencies needed by the autogenerated tests:

+
+
+
+
+
+
+
+

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

+
+
+
+
+
+
+
+ + + + + +
+ + +This example uses "convention based" naming by setting the +packageWithBaseClasses property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +src/test/resources/contracts/fraud. Since you do not have two packages starting from +the contracts folder, pick only one, which should be fraud. Add the Base suffix and +capitalize fraud. That gives you the FraudBase test class name. +
+
+
+

All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use Rest Assured MVC to +start the server side FraudDetectionController.

+
+
+
+
+
+
+
+

Now, if you run the ./mvnw clean install, you get something like this:

+
+
+
+
Results :
+
+Tests in error:
+  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
+
+
+
+

This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this:

+
+
+
+
@Test
+public void validate_shouldMarkClientAsFraud() throws Exception {
+    // given:
+        MockMvcRequestSpecification request = given()
+                .header("Content-Type", "application/vnd.fraud.v1+json")
+                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
+
+    // when:
+        ResponseOptions response = given().spec(request)
+                .put("/fraudcheck");
+
+    // then:
+        assertThat(response.statusCode()).isEqualTo(200);
+        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
+    // and:
+        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
+        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
+        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
+}
+
+
+
+

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the +value(consumer(…​), producer(…​)) blocks got injected into the test. +In case of using YAML, the same applied for the matchers sections of the response.

+
+
+

Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the red part of red, green, and +refactor. It is time to convert the red into the green.

+
+
+

Write the missing implementation.

+
+
+

Because you know the expected input and expected output, you can write the missing +implementation:

+
+
+
+
}
+
+
+
+

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud +Contract Verifier plugin adds the tests to the generated-test-sources, you can +actually run those tests from your IDE.

+
+
+

Deploy your app.

+
+
+

Once you finish your work, you can deploy your change. First, merge the branch:

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+$ git push origin master
+
+
+
+

Your CI might run something like ./mvnw clean deploy, which would publish both the +application and the stub artifacts.

+
+
+
+

Consumer Side (Loan Issuance) Final Step

+
+

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

+
+
+

Merge branch to master.

+
+
+
+
$ git checkout master
+$ git merge --no-ff contract-change-pr
+
+
+
+

Work online.

+
+
+

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can set the value of +stubsMode to REMOTE. The following code shows an example of +achieving the same thing by changing the properties.

+
+
+
+
+
+
+
+

That’s it!

+
+
+
+
+

Dependencies

+
+

The best way to add dependencies is to use the proper starter dependency.

+
+
+

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add +spring-cloud-starter-contract-verifier.

+
+
+
+ +
+

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development.

+
+
+

Spring Cloud Contract video

+
+

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

+
+
+
+ +
+
+
+ +
+
+

Samples

+
+

You can find some samples at +samples.

+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_messaging.html b/reference/html/verifier_messaging.html new file mode 100644 index 0000000000..d022acd558 --- /dev/null +++ b/reference/html/verifier_messaging.html @@ -0,0 +1,401 @@ + + + + + + + +Spring Cloud Contract Verifier Messaging + + + + + + + + + + +
+
+

Spring Cloud Contract Verifier Messaging

+
+
+

Spring Cloud Contract Verifier lets you verify applications that use messaging as a +means of communication. All of the integrations shown in this document work with Spring, +but you can also create one of your own and use that.

+
+
+

Integrations

+
+

You can use one of the following four integration configurations:

+
+
+
    +
  • +

    Apache Camel

    +
  • +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

Since we use Spring Boot, if you have added one of these libraries to the classpath, all +the messaging configuration is automatically set up.

+
+
+ + + + + +
+ + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. +
+
+
+ + + + + +
+ + +If you want to use Spring Cloud Stream, remember to add a dependency on +org.springframework.cloud:spring-cloud-stream-test-support, as shown here: +
+
+
+
Maven
+
+
<dependency>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-stream-test-support</artifactId>
+    <scope>test</scope>
+</dependency>
+
+
+
+
Gradle
+
+
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
+
+
+
+
+

Manual Integration Testing

+
+

The main interface used by the tests is +org.springframework.cloud.contract.verifier.messaging.MessageVerifier. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal.

+
+
+

In a test, you can inject a ContractVerifierMessageExchange to send and receive +messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. +Here’s an example:

+
+
+
+
@RunWith(SpringTestRunner.class)
+@SpringBootTest
+@AutoConfigureMessageVerifier
+public static class MessagingContractTests {
+
+  @Autowired
+  private MessageVerifier verifier;
+  ...
+}
+
+
+
+ + + + + +
+ + +If your tests require stubs as well, then @AutoConfigureStubRunner includes the +messaging configuration, so you only need the one annotation. +
+
+
+
+

Publisher-Side Test Generation

+
+

Having the input or outputMessage sections in your DSL results in creation of tests +on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a +possibility to create JUnit 5, TestNG or Spock tests.

+
+
+

There are 3 main scenarios that we should take into consideration:

+
+
+
    +
  • +

    Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler).

    +
  • +
  • +

    Scenario 2: The input message triggers an output message.

    +
  • +
  • +

    Scenario 3: The input message is consumed and there is no output message.

    +
  • +
+
+
+ + + + + +
+ + +The destination passed to messageFrom or sentTo can have different +meanings for different messaging implementations. For Stream and Integration it is +first resolved as a destination of a channel. Then, if there is no such destination +it is resolved as a channel name. For Camel, that’s a certain component (for example, +jms). +
+
+
+

Scenario 1: No Input Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

The following JUnit test is created:

+
+
+
+
+
+
+
+

And the following Spock test would be created:

+
+
+
+
+
+
+
+
+

Scenario 2: Output Triggered by Input

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

The following JUnit test is created:

+
+
+
+
+
+
+
+

And the following Spock test would be created:

+
+
+
+
+
+
+
+
+

Scenario 3: No Output Message

+
+

For the given contract:

+
+
+
Groovy DSL
+
+
+
+
+
+
YAML
+
+
+
+
+
+

The following JUnit test is created:

+
+
+
+
+
+
+
+

And the following Spock test would be created:

+
+
+
+
+
+
+
+
+
+

Consumer Stub Generation

+
+

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

+
+
+

For more information, see [stub-runner-for-messaging] section.

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_setup.html b/reference/html/verifier_setup.html new file mode 100644 index 0000000000..fe087233ef --- /dev/null +++ b/reference/html/verifier_setup.html @@ -0,0 +1,1764 @@ + + + + + + + +Spring Cloud Contract Verifier Setup + + + + + + + + + + +
+
+

Spring Cloud Contract Verifier Setup

+
+
+

You can set up Spring Cloud Contract Verifier in the following ways:

+
+ +
+

Gradle Project

+
+

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

Prerequisites

+
+

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin.

+
+
+ + + + + +
+ + +If you want to use Spock in your projects, you must add separately the +spock-core and spock-spring modules. Check Spock +docs for more information +
+
+
+
+

Add Gradle Plugin with Dependencies

+
+

To add a Gradle plugin with dependencies, use code similar to this:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	// example with adding Spock core and Spock Spring
+	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
+	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}
+
+
+
+
+

Gradle and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

+
+
+
+
buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+		classpath "com.jayway.restassured:rest-assured:2.5.0"
+		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
+	}
+}
+
+depenendencies {
+    // all dependencies
+    // you can exclude rest-assured from spring-cloud-contract-verifier
+    testCompile "com.jayway.restassured:rest-assured:2.5.0"
+    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
+}
+
+
+
+

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

Snapshot Versions for Gradle

+
+

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

+
+
+
+
}
+
+
+
+
+

Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

+
+
+

The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

Run the Plugin

+
+

The plugin registers itself to be invoked before a check task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the generateContractTests task.

+
+
+
+

Default Setup

+
+

The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode):

+
+
+
+
contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
+    basePackageForTests = 'org.springframework.cloud.verifier.tests'
+    stubsOutputDir = project.file("${project.buildDir}/stubs")
+
+    // the following properties are used when you want to provide where the JAR with contract lays
+    contractDependency {
+        stringNotation = ''
+    }
+    contractsPath = ''
+    contractsWorkOffline = false
+    contractRepository {
+        cacheDownloadedContracts(true)
+    }
+}
+
+tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
+    baseName = project.name
+    classifier = contracts.stubsSuffix
+    from contractVerifier.stubsOutputDir
+}
+
+project.artifacts {
+    archives task
+}
+
+tasks.create(type: Copy, name: 'copyContracts') {
+    from contracts.contractsDslDir
+    into contracts.stubsOutputDir
+}
+
+verifierStubsJar.dependsOn 'copyContracts'
+
+publishing {
+    publications {
+        stubs(MavenPublication) {
+            artifactId project.name
+            artifact verifierStubsJar
+        }
+    }
+}
+
+
+
+
+

Configure Plugin

+
+

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

+
+
+
+
contracts {
+	testMode = 'MockMvc'
+	baseClassForTests = 'org.mycompany.tests'
+	generatedTestSourcesDir = project.file('src/generatedContract')
+}
+
+
+
+
+

Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    +
  • +
  • +

    staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.

    +
  • +
  • +

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.

    +
  • +
  • +

    contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.

    +
  • +
  • +

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

The following properties are used when you want to specify the location of the JAR +containing the contracts:

+
+
+
    +
  • +

    contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.

    +
  • +
  • +

    contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.

    +
  • +
  • +

    contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
+
+
+
+

If you use Explicit mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this +base class should also contain a protected WebTarget webTarget field. Right now, the +only option to test the JAX-RS API is to start a web server.

+
+
+
+

Different Base Classes for Contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    Provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
+
+
+
+

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

Invoking Generated Tests

+
+

To ensure that the provider side is compliant with defined contracts, you need to invoke:

+
+
+
+
./gradlew generateContractTests test
+
+
+
+
+

Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

+
+
+
+
$ ./gradlew pushStubsToScm
+
+
+
+

Under [scm-stub-downloader] you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

+
+
+
+

Spring Cloud Contract Verifier on the Consumer Side

+
+

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in src/test/resources/contracts and generate +WireMock JSON stubs using:

+
+
+
+
./gradlew generateClientStubs
+
+
+
+ + + + + +
+ + +The stubsOutputDir option has to be set for stub generation to work. +
+
+
+

When present, JSON stubs can be used in automated tests of consuming a service.

+
+
+
+
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
+class LoanApplicationServiceSpec extends Specification {
+
+ @ClassRule
+ @Shared
+ WireMockClassRule wireMockRule == new WireMockClassRule()
+
+ @Autowired
+ LoanApplicationService sut
+
+ def 'should successfully apply for loan'() {
+   given:
+ 	LoanApplication application =
+			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
+   when:
+	LoanApplicationResult loanApplication == sut.loanApplication(application)
+   then:
+	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
+	loanApplication.rejectionReason == null
+ }
+}
+
+
+
+

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

+
+
+
+
+

Maven Project

+
+

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections:

+
+ +
+

Add maven plugin

+
+

Add the Spring Cloud Contract BOM in a fashion similar to this:

+
+
+
+
+
+
+
+

Next, add the Spring Cloud Contract Verifier Maven plugin:

+
+
+
+
+
+
+ +
+
+

Maven and Rest Assured 2.0

+
+

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <packageWithBaseClasses>com.example</packageWithBaseClasses>
+    </configuration>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-contract-verifier</artifactId>
+            <version>${spring-cloud-contract.version}</version>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>rest-assured</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+        <dependency>
+           <groupId>com.jayway.restassured</groupId>
+           <artifactId>spring-mock-mvc</artifactId>
+           <version>2.5.0</version>
+           <scope>compile</scope>
+        </dependency>
+    </dependencies>
+</plugin>
+
+<dependencies>
+    <!-- all dependencies -->
+    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>rest-assured</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+    <dependency>
+       <groupId>com.jayway.restassured</groupId>
+       <artifactId>spring-mock-mvc</artifactId>
+       <version>2.5.0</version>
+       <scope>test</scope>
+    </dependency>
+</dependencies>
+
+
+
+

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly.

+
+
+
+

Snapshot versions for Maven

+
+

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

+
+
+
+
+
+
+
+
+

Add stubs

+
+

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure:

+
+
+
+
src/test/resources/contracts/myservice/shouldCreateUser.groovy
+src/test/resources/contracts/myservice/shouldReturnUser.groovy
+
+
+
+

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

+
+
+
    +
  • +

    shouldCreateUser()

    +
  • +
  • +

    shouldReturnUser()

    +
  • +
+
+
+
+

Run plugin

+
+

The plugin goal generateTests is assigned to be invoked in the phase called +generate-test-sources. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the generateTests goal.

+
+
+
+

Configure plugin

+
+

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <executions>
+        <execution>
+            <goals>
+                <goal>convert</goal>
+                <goal>generateStubs</goal>
+                <goal>generateTests</goal>
+            </goals>
+        </execution>
+    </executions>
+    <configuration>
+        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
+        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
+    </configuration>
+</plugin>
+
+
+
+
+

Configuration Options

+
+
    +
  • +

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.

    +
  • +
  • +

    basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.

    +
  • +
  • +

    ruleClassForTests: Specifies a rule that should be added to the generated test +classes.

    +
  • +
  • +

    baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.

    +
  • +
  • +

    contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.

    +
  • +
  • +

    generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.

    +
  • +
  • +

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    +
  • +
  • +

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.

    +
  • +
  • +

    packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.

    +
  • +
  • +

    baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.

    +
  • +
  • +

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    +
  • +
+
+
+

If you want to download your contract definitions from a Maven repository, you can use +the following options:

+
+
+
    +
  • +

    contractDependency: The contract dependency that contains all the packaged contracts.

    +
  • +
  • +

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.

    +
  • +
  • +

    contractsMode: Picks the mode in which stubs will be found and registered

    +
  • +
  • +

    deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

    +
  • +
  • +

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.

    +
  • +
  • +

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    +
  • +
  • +

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    +
  • +
+
+
+

We cache only non-snapshot, explicitly provided versions (for example ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

+
+
+

Below you can find a list of experimental features you can turn on via the plugin:

+
+
+
    +
  • +

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    +
  • +
  • +

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    +
  • +
+
+
+
+

Single Base Class for All Tests

+
+

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

+
+
+
+
package org.mycompany.tests
+
+import org.mycompany.ExampleSpringController
+import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
+import spock.lang.Specification
+
+class MvcSpec extends Specification {
+  def setup() {
+   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
+  }
+}
+
+
+
+

You can also setup the whole context if necessary.

+
+
+
+
import io.restassured.module.mockmvc.RestAssuredMockMvc;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@Autowired
+	WebApplicationContext context;
+
+	@Before
+	public void setup() {
+		RestAssuredMockMvc.webAppContextSetup(this.context);
+	}
+}
+
+
+
+

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

+
+
+
+
import io.restassured.RestAssured;
+import org.junit.Before;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.context.WebApplicationContext;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
+public abstract class BaseTestClass {
+
+	@LocalServerPort
+	int port;
+
+	@Before
+	public void setup() {
+		RestAssured.baseURI = "http://localhost:" + this.port;
+	}
+}
+
+
+
+

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right +now, the only option to test the JAX-RS API is to start a web server.

+
+
+
+

Different base classes for contracts

+
+

If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options:

+
+
+
    +
  • +

    Follow a convention by providing the packageWithBaseClasses

    +
  • +
  • +

    provide explicit mapping via baseClassMappings

    +
  • +
+
+
+

By Convention

+
+
+

The convention is such that if you have a contract under (for example) +src/test/resources/contract/foo/bar/baz/ and set the value of the +packageWithBaseClasses property to com.example.base, then Spring Cloud Contract +Verifier assumes that there is a BarBazBase class under the com.example.base package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a Base suffix. This rule takes precedence over baseClassForTests. +Here is an example of how it works in the contracts closure:

+
+
+
+
+
+
+
+

By Mapping

+
+
+

You can manually map a regular expression of the contract’s package to fully qualified +name of the base class for the matched contract. You have to provide a list called +baseClassMappings that consists baseClassMapping objects that takes a +contractPackageRegex to baseClassFQN mapping. Consider the following example:

+
+
+
+
+
+
+
+

Assume that you have contracts under these two locations: +* src/test/resources/contract/com/ +* src/test/resources/contract/foo/

+
+
+

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. +(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests +generated from src/test/resources/contract/com/ contracts extend the +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

+
+
+
+

Invoking generated tests

+
+

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +/generated-test-sources/contractVerifier and attaches this directory to testCompile +goal.

+
+
+

For Groovy Spock code, use the following:

+
+
+
+
<plugin>
+	<groupId>org.codehaus.gmavenplus</groupId>
+	<artifactId>gmavenplus-plugin</artifactId>
+	<version>1.5</version>
+	<executions>
+		<execution>
+			<goals>
+				<goal>testCompile</goal>
+			</goals>
+		</execution>
+	</executions>
+	<configuration>
+		<testSources>
+			<testSource>
+				<directory>${project.basedir}/src/test/groovy</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+			<testSource>
+				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
+				<includes>
+					<include>**/*.groovy</include>
+				</includes>
+			</testSource>
+		</testSources>
+	</configuration>
+</plugin>
+
+
+
+

To ensure that provider side is compliant with defined contracts, you need to invoke +mvn generateTest test.

+
+
+
+

Pushing stubs to SCM

+
+

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

+
+
+
+
<plugin>
+    <groupId>org.springframework.cloud</groupId>
+    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+    <version>${spring-cloud-contract.version}</version>
+    <extensions>true</extensions>
+    <configuration>
+        <!-- Base class mappings etc. -->
+
+        <!-- We want to pick contracts from a Git repository -->
+        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
+
+        <!-- We reuse the contract dependency section to set up the path
+        to the folder that contains the contract definitions. In our case the
+        path will be /groupId/artifactId/version/contracts -->
+        <contractDependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>${project.artifactId}</artifactId>
+            <version>${project.version}</version>
+        </contractDependency>
+
+        <!-- The contracts mode can't be classpath -->
+        <contractsMode>REMOTE</contractsMode>
+    </configuration>
+    <executions>
+        <execution>
+            <phase>package</phase>
+            <goals>
+                <!-- By default we will not push the stubs back to SCM,
+                you have to explicitly add it as a goal -->
+                <goal>pushStubsToScm</goal>
+            </goals>
+        </execution>
+    </executions>
+</plugin>
+
+
+
+

Under [scm-stub-downloader] you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

+
+
+
+

Maven Plugin and STS

+
+

If you see the following exception while using STS:

+
+
+

When you click on the error marker you should see something like this:

+
+
+
+
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+ cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
+ org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
+...
+ org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
+ org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
+ org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
+
+
+
+

In order to fix this issue, provide the following section in your pom.xml:

+
+
+
+
<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>
+
+
+
+
+

Maven Plugin with Spock Tests

+
+

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

+
+
+

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

+
+
+
+
+
+
+
+

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

+
+
+
+
+
+
+
+
+
+

Stubs and Transitive Dependencies

+
+

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

+
+
+
+
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
+├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
+├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
+├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
+├── ...
+└── ...
+
+
+
+

There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies:

+
+
+
    +
  • +

    Mark all application dependencies as optional

    +
  • +
  • +

    Create a separate artifactid for the stubs

    +
  • +
  • +

    Exclude dependencies on the consumer side

    +
  • +
+
+
+

Mark all application dependencies as optional

+
+
+

If, in the github-webhook application, you mark all of your dependencies as optional, +when you include the github-webhook stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded.

+
+
+

Create a separate artifactid for the stubs

+
+
+

If you create a separate artifactid, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all.

+
+
+

Exclude dependencies on the consumer side

+
+
+

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

+
+
+
+

Scenarios

+
+

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

+
+
+
+
my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy
+
+
+
+

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

+
+
+
    +
  1. +

    login marked as Started pointing to…​

    +
  2. +
  3. +

    showCart marked as Step1 pointing to…​

    +
  4. +
  5. +

    logout marked as Step2 which will close the scenario.

    +
  6. +
+
+
+

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

+
+
+

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

+
+
+
+

Docker Project

+
+

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

+
+
+ + + + + +
+ + +The EXPLICIT mode means that the tests generated from contracts will send +real requests and not the mocked ones. +
+
+
+

Short intro to Maven, JARs and Binary storage

+
+

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

+
+
+

Part of the following definitions were taken from the Maven Glossary

+
+
+
    +
  • +

    Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.

    +
  • +
  • +

    Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.

    +
  • +
  • +

    JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.

    +
  • +
  • +

    GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.

    +
  • +
  • +

    Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.

    +
  • +
  • +

    Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

    +
  • +
+
+
+
+

How it works

+
+

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

+
+
+

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

+
+
+
    +
  • +

    generate the contract tests

    +
  • +
  • +

    execute the tests against the provided URL

    +
  • +
  • +

    generate the WireMock stubs

    +
  • +
  • +

    (optional - turned on by default) publish the stubs to a Artifact Manager

    +
  • +
+
+
+
Environment Variables
+
+

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

+
+
+
    +
  • +

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    +
  • +
  • +

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    +
  • +
  • +

    PROJECT_NAME - artifact id. Defaults to example

    +
  • +
  • +

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    +
  • +
  • +

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    +
  • +
  • +

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    +
  • +
  • +

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    +
  • +
+
+
+

These environment variables are used when contracts lay in an external repository. To enable +this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

+
+
+
    +
  • +

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    +
  • +
  • +

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    +
  • +
  • +

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL +requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    +
  • +
  • +

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    +
  • +
+
+
+

These environment variables are used when tests are executed:

+
+
+
    +
  • +

    APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)

    +
  • +
  • +

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    +
  • +
  • +

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    +
  • +
+
+
+
+
+

Example of usage

+
+

Let’s take a look at a simple MVC application

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

The contracts are available under /contracts folder.

+
+
+
+

Server side (nodejs)

+
+

Since we want to run tests, we could just execute:

+
+
+
+
$ npm test
+
+
+
+

however, for learning purposes, let’s split it into pieces:

+
+
+
+
# Stop docker infra (nodejs, artifactory)
+$ ./stop_infra.sh
+# Start docker infra (nodejs, artifactory)
+$ ./setup_infra.sh
+
+# Kill & Run app
+$ pkill -f "node app"
+$ nohup node app &
+
+# Prepare environment variables
+$ SC_CONTRACT_DOCKER_VERSION="..."
+$ APP_IP="192.168.0.100"
+$ APP_PORT="3000"
+$ ARTIFACTORY_PORT="8081"
+$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
+$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
+$ CURRENT_DIR="$( pwd )"
+$ CURRENT_FOLDER_NAME=${PWD##*/}
+$ PROJECT_VERSION="0.0.1.RELEASE"
+
+# Execute contract tests
+$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
+
+# Kill app
+$ pkill -f "node app"
+
+
+
+

What will happen is that via bash scripts:

+
+
+
    +
  • +

    infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.

    +
  • +
  • +

    due to those constraints the contracts also represent the +stateful situation

    +
    +
      +
    • +

      first request is a POST that causes data to get inserted to the database

      +
    • +
    • +

      second request is a GET that returns a list of data with 1 previously inserted element

      +
    • +
    +
    +
  • +
  • +

    the NodeJS application will be started (on port 3000)

    +
  • +
  • +

    contract tests will be generated via Docker and tests +will be executed against the running application

    +
    +
      +
    • +

      the contracts will be taken from /contracts folder.

      +
    • +
    • +

      the output of the test execution is available under +node_modules/spring-cloud-contract/output.

      +
    • +
    +
    +
  • +
  • +

    the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    +
  • +
+
+
+

To see how the client side looks like check out the [stubrunner-docker] section.

+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_stubrunner.html b/reference/html/verifier_stubrunner.html new file mode 100644 index 0000000000..33efa3d1b1 --- /dev/null +++ b/reference/html/verifier_stubrunner.html @@ -0,0 +1,431 @@ + + + + + + + +Spring Cloud Contract Stub Runner + + + + + + + + + + +
+
+

Spring Cloud Contract Stub Runner

+
+
+

One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging.

+
+
+

Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you.

+
+
+

Snapshot versions

+
+

Add the additional snapshot repository to your build.gradle file to use snapshot +versions, which are automatically uploaded after every successful build:

+
+
+
Maven
+
+
+
+
+
+
Gradle
+
+
+
+
+
+
+

Publishing Stubs as JARs

+
+

The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository.

+
+
+ + + + + +
+ + +For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. +
+
+
+
Maven
+
+
<!-- First disable the default jar setup in the properties section -->
+
+<!-- Next add the assembly plugin to your build -->
+
+<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
+
+
+
+
Gradle
+
+
+
+
+
+
+

Common

+
+

This section briefly describes common properties, including:

+
+ +
+

Common Properties for JUnit and Spring

+
+

You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with +stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with +stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for +each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to +override the consumer name just change this value.

+
+
+

Stub Runner Stubs IDs

+
+

You can provide the stubs to download via the stubrunner.ids system property. They +follow this pattern:

+
+
+
+
groupId:artifactId:version:classifier:port
+
+
+
+

Note that version, classifier and port are optional.

+
+
+
    +
  • +

    If you do not provide the port, a random one will be picked.

    +
  • +
  • +

    If you do not provide the classifier, the default is used. (Note that you can +pass an empty classifier this way: groupId:artifactId:version:).

    +
  • +
  • +

    If you do not provide the version, then the + will be passed and the latest one is +downloaded.

    +
  • +
+
+
+

port means the port of the WireMock server.

+
+
+ + + + + +
+ + +Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +Aether versioning +ranges here. +
+
+
+
+
+

Stub Runner Docker

+
+

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +that will start the standalone version of Stub Runner.

+
+
+

If you want to learn more about the basics of Maven, artifact ids, +group ids, classifiers and Artifact Managers, just click here [docker-project].

+
+
+

How to use it

+
+

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring +as environment variables. The convention is that all the +letters should be upper case. The camel case notation should +and the dot (.) should be separated via underscore (_). E.g. + the stubrunner.repositoryRoot property should be represented + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

+
+
+
+

Example of client side usage in a non JVM project

+
+

We’d like to use the stubs created in this [docker-server-side] step. +Let’s assume that we want to run the stubs on port 9876. The NodeJS code +is available here:

+
+
+
+
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
+$ cd bookstore
+
+
+
+

Let’s run the Stub Runner Boot application with the stubs.

+
+
+
+
# Provide the Spring Cloud Contract Docker version
+$ SC_CONTRACT_DOCKER_VERSION="..."
+# The IP at which the app is running and Docker container can reach it
+$ APP_IP="192.168.0.100"
+# Spring Cloud Contract Stub Runner properties
+$ STUBRUNNER_PORT="8083"
+# Stub coordinates 'groupId:artifactId:version:classifier:port'
+$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
+$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
+# Run the docker with Stub Runner Boot
+$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
+
+
+
+

What’s happening is that

+
+
+
    +
  • +

    a standalone Stub Runner application got started

    +
  • +
  • +

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    +
  • +
  • +

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    +
  • +
  • +

    after a while Stub Runner will be running on port 8083

    +
  • +
  • +

    and the stubs will be running at port 9876

    +
  • +
+
+
+

On the server side we built a stateful stub. Let’s use curl to assert +that the stubs are setup properly.

+
+
+
+
# let's execute the first request (no response is returned)
+$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
+# Now time for the second request
+$ curl -X GET http://localhost:9876/api/books
+# You will receive contents of the JSON
+
+
+
+ + + + + +
+ + +If you want use the stubs that you have built locally, on your host, +then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" +
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/html/verifier_stubrunner_msg.html b/reference/html/verifier_stubrunner_msg.html new file mode 100644 index 0000000000..103d889f7d --- /dev/null +++ b/reference/html/verifier_stubrunner_msg.html @@ -0,0 +1,223 @@ + + + + + + + +Stub Runner for Messaging + + + + + + + + + + +
+
+

Stub Runner for Messaging

+
+
+

Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks:

+
+
+
    +
  • +

    Spring Integration

    +
  • +
  • +

    Spring Cloud Stream

    +
  • +
  • +

    Apache Camel

    +
  • +
  • +

    Spring AMQP

    +
  • +
+
+
+

It also provides entry points to integrate with any other solution on the market.

+
+
+ + + + + +
+ + +If you have multiple frameworks on the classpath Stub Runner will need to +define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration +on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. +That way the only remaining framework is Spring AMQP. +
+
+
+

Stub triggering

+
+

To trigger a message, use the StubTrigger interface:

+
+
+
+
+
+
+
+

For convenience, the StubFinder interface extends StubTrigger, so you only need one +or the other in your tests.

+
+
+

StubTrigger gives you the following options to trigger a message:

+
+ +
+

Trigger by Label

+
+
+
+
+
+
+ + +
+

Trigger All Messages

+
+
+
+
+
+
+
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/reference/htmlsingle/css/spring.css b/reference/htmlsingle/css/spring.css new file mode 100644 index 0000000000..40821db3cd --- /dev/null +++ b/reference/htmlsingle/css/spring.css @@ -0,0 +1 @@ +@import url("https://fonts.googleapis.com/css?family=Karla:400,700|Montserrat:400,700");/*! normalize.css v2.1.2 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden],template{display:none}script{display:none !important}html,body{font-size:100%}html{font-family:Karla, sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}body{background:white;color:#000;padding:0;margin:0;font-size:16px;font-family:Karla, sans-serif;font-weight:normal;font-style:normal;line-height:1.6em;position:relative;cursor:auto}a:hover{cursor:pointer}img,object,embed{max-width:100%;height:auto}object,embed{height:100%}img{-ms-interpolation-mode:bicubic}#map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none !important}.left{float:left !important}.right{float:right !important}.text-left{text-align:left !important}.text-right{text-align:right !important}.text-center{text-align:center !important}.text-justify{text-align:justify !important}.hide{display:none}.antialiased{-webkit-font-smoothing:antialiased}img{display:inline-block;vertical-align:middle}textarea{height:auto;min-height:50px}select{width:100%}object,svg{display:inline-block;vertical-align:middle}.center{margin-left:auto;margin-right:auto}.spread{width:100%}p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{line-height:1.6}.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#0b0a0a;font-weight:bold;margin-top:0;margin-bottom:0.8em}div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}a{color:#097dff;line-height:inherit;text-decoration:none}a:hover,a:focus{color:#016be2;text-decoration:underline}a img{border:none}p{font-family:inherit;font-weight:normal;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}p aside{font-size:0.875em;line-height:1.35;font-style:italic}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:Montserrat, sans-serif;font-weight:400;font-style:normal;color:#000;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:0.5em;line-height:1.0125em}h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#867c74;line-height:0}h1{font-size:2.125em}h2{font-size:1.6875em}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}h4{font-size:1.125em}h5{font-size:1.125em}h6{font-size:1em}hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}em,i{font-style:italic;line-height:inherit}strong,b{font-weight:bold;line-height:inherit}small{font-size:60%;line-height:inherit}code{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-weight:normal;color:#3d3d3c;word-break:break-word}ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}ul,ol{margin-left:1.5em}ul.no-bullet,ol.no-bullet{margin-left:1.5em}ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}ul.square{list-style-type:square}ul.circle{list-style-type:circle}ul.disc{list-style-type:disc}ul.no-bullet{list-style:none}ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}dl dt{margin-bottom:0.3125em;font-weight:bold}dl dd{margin-bottom:1.25em}abbr,acronym{text-transform:uppercase;font-size:90%;color:#000;border-bottom:1px dotted #dddddd;cursor:help}abbr{text-transform:none}blockquote{margin:0 0 1.25em;padding:0.5625em 1.25em 0 1.1875em;border-left:1px solid #dddddd}blockquote cite{display:block;font-size:0.9375em;color:rgba(0,0,0,0.6)}blockquote cite:before{content:"\2014 \0020"}blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,0.6)}blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,0.85)}.vcard{display:inline-block;margin:0 0 1.25em 0;border:1px solid #dddddd;padding:0.625em 0.75em}.vcard li{margin:0;display:block}.vcard .fn{font-weight:bold;font-size:0.9375em}.vevent .summary{font-weight:bold}.vevent abbr{cursor:auto;text-decoration:none;font-weight:bold;border:none;padding:0 0.0625em}#tocbot{padding:0 0 1rem 0;line-height:1.5rem;padding-left:25px}.mobile-toc{padding:0 0 1rem 0;line-height:1.5rem}.mobile-toc li a{display:block;padding:.3rem 0}#tocbot ol li{list-style:none;padding:0;margin:0}#tocbot ol{margin:0;padding:0;padding-left:0.6rem}#tocbot .toc-link{display:block;padding-top:4px;padding-bottom:4px;outline:none}table{background:white;margin-bottom:1.25em;border:solid 1px #cacaca;border-spacing:0}table thead,table tfoot{background:#f7f8f7;font-weight:bold}table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:0.5em 0.625em 0.625em;font-size:inherit;color:#000;text-align:left}table tr th,table tr td{padding:0.5625em 0.625em;font-size:inherit;color:#000}table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}body{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;tab-size:4}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-0.05em}.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}.clearfix:after,.float-group:after{clear:both}*:not(pre)>code{font-size:0.8525em;font-style:normal !important;letter-spacing:0;padding:0.1em 0.3em 0.2em;background-color:rgba(0,0,0,0.05);border-radius:4px;text-rendering:optimizeSpeed}pre,pre>code{line-height:1.85;color:rgba(0,0,0,0.9);font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-weight:normal;text-rendering:optimizeSpeed;word-break:normal}pre{overflow:auto}em em{font-style:normal}strong strong{font-weight:normal}.keyseq{color:#6b625c}kbd{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;display:inline-block;color:#000;font-size:0.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 0.1em white inset;box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 0.1em white inset;margin:0 0.15em;padding:0.2em 0.5em;vertical-align:middle;position:relative;top:-0.1em;white-space:nowrap}.keyseq kbd:first-child{margin-left:0}.keyseq kbd:last-child{margin-right:0}.menuseq,.menu{color:#191715}b.button:before,b.button:after{position:relative;top:-1px;font-weight:normal}b.button:before{content:"[";padding:0 3px 0 2px}b.button:after{content:"]";padding:0 2px 0 3px}p a>code:hover{color:rgba(0,0,0,0.9)}#toc{border-bottom:1px solid #ddddd8;padding-bottom:0.5em}#toc>ul{margin-left:0.125em}#toc ul.sectlevel0>li>a{font-style:italic}#toc ul.sectlevel0 ul.sectlevel1{margin:0.5em 0}#toc ul{list-style-type:none}#toc li{line-height:1.3334}#toc a{text-decoration:none}#toc a:active{text-decoration:underline}#toctitle{color:#0b0a0a;font-size:1.2em;display:none}body.toc2{padding-top:90px;text-rendering:optimizeLegibility}#content #toc{border-style:solid;border-width:1px;border-color:#d7d7d7;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;-webkit-border-radius:4px;border-radius:4px}#content #toc>:first-child{margin-top:0}#content #toc>:last-child{margin-bottom:0}#footer{padding-bottom:2rem}#footer #footer-text{padding:2rem 0;border-top:1px solid #efefed}#footer-text{color:rgba(0,0,0,0.6);line-height:1.44}.sect1{padding-bottom:0.625em}.sect1+.sect1{border-top:1px solid #efefed}#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;margin-top:0.1rem;display:block;visibility:hidden;text-align:center;font-weight:normal;color:rgba(0,0,0,0.2)}#content h1>a.anchor:hover,h2>a.anchor:hover,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4>a.anchor:hover,h5>a.anchor:hover,h6>a.anchor:hover{color:#097dff;text-decoration:none}#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\0023";font-size:0.85em;display:block;padding-top:0.1em}#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#000;text-decoration:none}#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#262321}.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:Karla, sans-serif;font-size:1rem}table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0;padding:0.6rem 0}table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}.admonitionblock>table td.icon{text-align:center;vertical-align:top;padding-top:0.8em;width:80px}.admonitionblock>table td.icon img{max-width:initial}.admonitionblock>table td.icon .title{font-weight:bold;font-family:Montserrat, sans-serif;text-transform:uppercase}.admonitionblock>table td.content{padding-left:0em;padding-right:1.25em;border-left:1px solid #ddddd8}.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}.exampleblock>.content{border-style:solid;border-width:0;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;border-radius:4px}.exampleblock>.content>:first-child{margin-top:0}.exampleblock>.content>:last-child{margin-bottom:0}.sidebarblock{border-style:solid;border-width:0;border-color:#d7d7d7;margin-bottom:1.25em;padding:1.25em;background:#f1f1f1;border-radius:4px;overflow:scroll}.sidebarblock>:first-child{margin-top:0}.sidebarblock>:last-child{margin-bottom:0}.sidebarblock>.content>.title{color:#0b0a0a;margin-top:0;text-align:center}.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#282c33;color:#e6e1dc;border-radius:4px}.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#282c33;color:#e6e1dc}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class],.listingblock pre:not(.highlight){padding:1em 1.5rem;font-size:0.8125em}.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto}.literalblock.output pre{color:whitesmoke;background-color:rgba(0,0,0,0.9)}.listingblock{white-space:nowrap}.listingblock pre.highlightjs{padding:0.2rem 0}.listingblock pre.highlightjs>code{padding:1em 1.5rem;border-radius:4px}.listingblock>.content{position:relative}.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:0.8em;font-weight:bold;top:0.425rem;right:0.5rem;line-height:1;text-transform:uppercase;color:#999}.listingblock code[data-lang]:before{display:block}.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:0.5em;color:#999}.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}table.pyhltable td.code{padding-left:.75em;padding-right:0}pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}pre.pygments .lineno{display:block;margin-right:.25em}table.pyhltable .linenodiv{background:none !important;padding-right:0 !important}.quoteblock{margin:0 1em 1.25em 1.5em;display:block;text-align:left;padding-left:20px}.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,0.85);line-height:1.75;letter-spacing:0}.quoteblock blockquote{margin:0;padding:0;border:0;position:relative}.quoteblock blockquote:before{content:"\201c";font-size:2.75em;font-weight:bold;line-height:0.6em;margin-left:0em;margin-right:1rem;margin-top:0.8rem;color:rgba(0,0,0,0.1);position:absolute;top:0;left:-30px}.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}.quoteblock .attribution{margin-right:0.5ex}.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:0.5em 0;border-left:3px solid rgba(0,0,0,0.6)}.quoteblock .quoteblock blockquote{padding:0 0 0 0.75em}.quoteblock .quoteblock blockquote:before{display:none}.verseblock{margin:0 1em 1.25em 0;background-color:#f1f1f1;padding:1rem 1.4rem;border-radius:4px}.verseblock pre{font-family:Monaco, Menlo, Consolas, "Courier New", monospace;font-size:0.9rem;color:rgba(0,0,0,0.85);font-weight:300;text-rendering:optimizeLegibility}.verseblock pre strong{font-weight:400}.verseblock .attribution{margin-top:1.25rem;margin-left:0.5ex}.quoteblock .attribution,.verseblock .attribution{font-size:0.9375em;line-height:1.45;font-style:italic}.quoteblock .attribution br,.verseblock .attribution br{display:none}.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-0.025em;color:rgba(0,0,0,0.6)}.quoteblock.abstract{margin:0 0 1.25em 0;display:block}.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}table.tableblock{max-width:100%;border-collapse:separate;overflow-x:scroll}table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}table.tableblock,th.tableblock,td.tableblock{border:0 solid #cacaca;background:white}table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}table.frame-all{border-width:1px}table.frame-sides{border-width:0 1px}table.frame-topbot{border-width:1px 0}th.halign-left,td.halign-left{text-align:left}th.halign-right,td.halign-right{text-align:right}th.halign-center,td.halign-center{text-align:center}th.valign-top,td.valign-top{vertical-align:top}th.valign-bottom,td.valign-bottom{vertical-align:bottom}th.valign-middle,td.valign-middle{vertical-align:middle}table thead th,table tfoot th{font-weight:bold}tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:#34302d;font-weight:bold}p.tableblock>code:only-child{background:none;padding:0}p.tableblock{font-size:1em}td>div.verse{white-space:pre}ol{margin-left:1.75em}ul li ol{margin-left:1.5em}dl dd{margin-left:1.125em}dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:0.625em}ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}ul.unstyled,ol.unnumbered,ul.checklist{margin-left:0.625em}ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:0.85em}ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}ul.inline{margin:0 auto 0.625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}ul.inline>li>*{display:block}.unstyled dl dt{font-weight:normal;font-style:normal}ol.arabic{list-style-type:decimal}ol.decimal{list-style-type:decimal-leading-zero}ol.loweralpha{list-style-type:lower-alpha}ol.upperalpha{list-style-type:upper-alpha}ol.lowerroman{list-style-type:lower-roman}ol.upperroman{list-style-type:upper-roman}ol.lowergreek{list-style-type:lower-greek}.hdlist>table,.colist>table{border:0;background:none}.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}td.hdlist1,td.hdlist2{vertical-align:top;padding:0 0.625em}td.hdlist1{font-weight:bold;padding-bottom:1.25em}.literalblock+.colist,.listingblock+.colist{margin-top:-0.5em}.colist>table tr>td:first-of-type{padding:0 0.75em;line-height:1}.colist>table tr>td:first-of-type img{max-width:initial}.colist>table tr>td:last-of-type{padding:0.25em 0}.thumb,.th{line-height:0;display:inline-block;border:solid 4px white;-webkit-box-shadow:0 0 0 1px #dddddd;box-shadow:0 0 0 1px #dddddd}.imageblock.left,.imageblock[style*="float: left"]{margin:0.25em 0.625em 1.25em 0}.imageblock.right,.imageblock[style*="float: right"]{margin:0.25em 0 1.25em 0.625em}.imageblock>.title{margin-bottom:0}.imageblock.thumb,.imageblock.th{border-width:6px}.imageblock.thumb>.title,.imageblock.th>.title{padding:0 0.125em}.image.left,.image.right{margin-top:0.25em;margin-bottom:0.25em;display:inline-block;line-height:0}.image.left{margin-right:0.625em}.image.right{margin-left:0.625em}a.image{text-decoration:none;display:inline-block}a.image object{pointer-events:none}sup.footnote,sup.footnoteref{font-size:0.875em;position:static;vertical-align:super}sup.footnote a,sup.footnoteref a{text-decoration:none}sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}#footnotes{padding-top:0.75em;padding-bottom:0.75em;margin-bottom:0.625em}#footnotes hr{width:20%;min-width:6.25em;margin:-0.25em 0 0.75em 0;border-width:1px 0 0 0}#footnotes .footnote{padding:0 0.375em 0 0.225em;line-height:1.3334;font-size:0.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:0.2em}#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}#footnotes .footnote:last-of-type{margin-bottom:0}#content #footnotes{margin-top:-0.625em;margin-bottom:0;padding:0.75em 0}.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}.gist .file-data>table td.line-data{width:99%}div.unbreakable{page-break-inside:avoid}.big{font-size:larger}.small{font-size:smaller}.underline{text-decoration:underline}.overline{text-decoration:overline}.line-through{text-decoration:line-through}.aqua{color:#00bfbf}.aqua-background{background-color:#00fafa}.black{color:black}.black-background{background-color:black}.blue{color:#0000bf}.blue-background{background-color:#0000fa}.fuchsia{color:#bf00bf}.fuchsia-background{background-color:#fa00fa}.gray{color:#606060}.gray-background{background-color:#7d7d7d}.green{color:#006000}.green-background{background-color:#007d00}.lime{color:#00bf00}.lime-background{background-color:#00fa00}.maroon{color:#600000}.maroon-background{background-color:#7d0000}.navy{color:#000060}.navy-background{background-color:#00007d}.olive{color:#606000}.olive-background{background-color:#7d7d00}.purple{color:#600060}.purple-background{background-color:#7d007d}.red{color:#bf0000}.red-background{background-color:#fa0000}.silver{color:#909090}.silver-background{background-color:#bcbcbc}.teal{color:#006060}.teal-background{background-color:#007d7d}.white{color:#bfbfbf}.white-background{background-color:#fafafa}.yellow{color:#bfbf00}.yellow-background{background-color:#fafa00}span.icon>.fa{cursor:default}.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;cursor:default}.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#3f6a22}.admonitionblock td.icon .icon-tip:before{content:"\f0eb";color:#0077b9}.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#d88400}.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}.conum[data-value]{display:inline-block;color:#000 !important;background-color:#ffe157;-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:0.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans", "DejaVu Sans", sans-serif;font-style:normal;font-weight:bold}.conum[data-value] *{color:#fff !important}.conum[data-value]+b{display:none}.conum[data-value]:after{content:attr(data-value)}pre .conum[data-value]{position:relative;top:0;color:#000 !important;background-color:#ffe157;font-size:12px}b.conum *{color:inherit !important}.conum:not([data-value]):empty{display:none}.admonitionblock{background-color:#ecf1e8;padding:0.8em 0;margin:30px 0;width:auto;border-radius:4px;overflow-x:scroll}.admonitionblock.important{border-left:0px solid #e20000;background-color:#f9ebeb}.admonitionblock.warning{border-left:0px solid #d88400;background-color:#fff9e4}.admonitionblock.tip{border-left:0px solid #0077b9;background-color:#e9f1f6}.admonitionblock.caution{border-left:0px solid #e20000;background-color:#f9ebeb}.admonitionblock .exampleblock>.content{border:0 none;background-color:#fff}#toc a:hover{text-decoration:underline}.admonitionblock>table{margin-bottom:0}.admonitionblock>table td.content{border-left:none}@media print{#tocbot a.toc-link.node-name--H4{display:none}}.is-collapsible{max-height:1000px;overflow:hidden;transition:all 200ms ease-in-out}.is-collapsed{max-height:0}div.back-action,#toc.toc2 div.back-action{padding:0.8rem 0 0 0}div.back-action a,#toc.toc2 div.back-action a{position:relative;display:inline-block;padding:0.6rem 1.2rem;padding-left:35px}div.back-action a span,#toc.toc2 div.back-action a span{position:absolute;left:5px;top:5px;display:block;color:#333;height:26px;width:26px;border-radius:13px}div.back-action a i,#toc.toc2 div.back-action a i{position:absolute;top:5px;left:5px}div.back-action a:hover span,#toc.toc2 div.back-action a:hover span{color:#000}#tocbot.desktop-toc{padding-top:0.8rem}#header-spring{position:absolute;text-rendering:optimizeLegibility;top:0;left:0;right:0;height:90px;margin:0 1rem;padding:0 1rem;border-bottom:1px solid #ddddd8;border-top:3px solid #6BB344}#header-spring h1{margin:0;padding:0;font-size:22px;text-align:left;line-height:86px;padding-left:0.6rem}#header-spring h1 svg{width:200px}#header-spring h1 svg .st0{fill:#6BB344}#header-spring h1 svg .st2{fill:#444}body.book #header-spring{position:relative;top:auto;left:auto;right:auto;margin:0}body.book #header>h1:only-child{border:0 none;padding-bottom:1.2rem;font-size:1.8rem}body.book #header,body.book #content,body.book #footnotes,body.book #footer{margin:0 auto}body.toc2 #header-spring{position:absolute;left:0;right:0;top:0}body.toc2 #header>h1:only-child{font-size:2.2rem}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{margin:0 auto}body.toc2 #content{padding-top:2rem}#header,#content,#footnotes,#footer{width:100%;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:0.9375em;padding-right:0.9375em}#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}#header:after,#content:after,#footnotes:after,#footer:after{clear:both}#content{margin-top:1.25em}#content:before{content:none}#header>h1:first-child{margin-top:2.55rem;margin-bottom:0.5em;margin-bottom:0.5em}#header>h1:first-child+#toc{margin-top:8px;border-top:0 none}#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:0;padding-bottom:2.25em;padding-left:0.25em;color:rgba(0,0,0,0.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}#header .details span:first-child{margin-left:-0.125em}#header .details span.email a{color:rgba(0,0,0,0.85)}#header .details br{display:none}#header .details br+span:before{content:"\00a0\2013\00a0"}#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,0.85)}#header .details br+span#revremark:before{content:"\00a0|\00a0"}#header #revnumber{text-transform:capitalize}#header #revnumber:after{content:"\00a0"}#content>h1:first-child:not([class]){color:rgba(0,0,0,0.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1.5rem;margin-bottom:1.25rem}h1{font-size:2.2rem;letter-spacing:-1px}h1,h2,h3,h4,h5,h6{font-weight:normal;font-family:Montserrat, Arial, Helvetica, sans-serif}h1:focus,h2:focus,h3:focus,h4:focus,h5:focus,h6:focus{box-shadow:none;outline:none}h2,h3,h4,h5,h6{padding:.8rem 0 .4rem}h1{font-size:1.75em}h2{font-size:1.6rem;letter-spacing:-1px}h3{font-size:1.5rem}h4{font-size:1.4rem}h5{font-size:1.3rem}h6{font-size:1.2rem}pre.highlight{background:#232323;color:#e6e1dc;border-radius:4px}pre.highlight code{color:#e6e1dc}pre.highlight a,#toc.toc2 a{color:#000;font-size:1rem}pre.highlight ul.sectlevel1,#toc.toc2 ul.sectlevel1{padding-left:0.2rem}pre.highlight ul.sectlevel1 li,#toc.toc2 ul.sectlevel1 li{line-height:1.4rem}::selection{background-color:#d1ff79}.literalblock pre::selection,.listingblock pre[class="highlight"]::selection,.highlight::selection,pre::selection,.highlight code::selection,.highlight code span::selection{background:rgba(255,255,255,0.2) !important}body.book #header{margin-bottom:2rem}body.toc2 #header{margin-bottom:0}.desktop-toc{display:none}.admonitionblock td.icon{display:none}.admonitionblock>table td.content{padding-left:1.25em}@media only screen and (min-width: 768px){#toctitle{font-size:1.375em}.sect1{padding-bottom:1.25em}.mobile-toc{display:none}.desktop-toc{display:block}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:0.90625em}.admonitionblock td.icon{display:table-cell}.admonitionblock>table td.content{padding-left:0}body.toc2{padding-right:0}body.toc2 #toc.toc2{position:absolute;margin-top:0 !important;width:15em;top:0;border-top-width:0 !important;border-bottom-width:0 !important;margin-left:-15.9375em;z-index:1000;padding:0 1em 1.25em 0em;overflow:auto}body.toc2 #toc.toc2 #toctitle{margin-top:0;margin-bottom:0.8rem;font-size:1.2em}body.toc2 #toc.toc2>ul{font-size:0.9em;margin-bottom:0}body.toc2 #toc.toc2 ul ul{margin-left:0;padding-left:1em}body.toc2 #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:0.5em;margin-bottom:0.5em}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{padding-left:15.9375em;max-width:none}body.book #header-spring h1{max-width:1400px;margin:0 auto}body.book #header,body.book #content,body.book #footnotes,body.book #footer{max-width:1400px}body.is-position-fixed #toc.toc2{position:fixed;height:100%}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}h1{font-size:1.75em}h2{font-size:1.6em}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.5em}h4{font-size:1.4em}h5{font-size:1.2em}h6{font-size:1.2em}#tocbot a.toc-link.node-name--H1{font-style:italic}#tocbot ol{margin:0;padding:0;padding-left:0.6rem}#tocbot ol li{list-style:none;padding:0 0;margin:0;display:block}#tocbot{z-index:999}#tocbot .toc-link{position:relative;display:block;z-index:999;padding-right:5px;padding-top:4px;padding-bottom:4px}#tocbot .is-active-link{padding-right:3px;border-right:3px solid #6BB344}}@media only screen and (min-width: 768px){#tocbot>ul.toc-list{margin-bottom:0.5em;margin-left:0.125em}#tocbot ul.sectlevel0,#tocbot a.toc-link.node-name--H1+ul{padding-left:0}#tocbot a.toc-link{height:100%}.is-collapsible{max-height:3000px;overflow:hidden}.is-collapsed{max-height:0}.is-active-link{font-weight:700}}@media only screen and (min-width: 768px){body.toc2 #header,body.toc2 #content,body.toc2 #footer{background-repeat:repeat-y;background-position:14em 0;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQwIDc5LjE2MDQ1MSwgMjAxNy8wNS8wNi0wMTowODoyMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTggKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDE0NUNENzNGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDE0NUNENzRGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpEMTQ1Q0Q3MUYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpEMTQ1Q0Q3MkYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjmGxxYAAAAGUExURd3d2AAAAJlCnKAAAAAMSURBVHjaYmAACDAAAAIAAU9tWeEAAAAASUVORK5CYII=)}}@media only screen and (min-width: 1280px){body.toc2{padding-right:0}body.toc2 #toc.toc2{width:25em;left:auto;margin-left:-26.9375em}body.toc2 #toc.toc2 #toctitle{font-size:1.375em}body.toc2 #toc.toc2>ul{font-size:0.95em}body.toc2 #toc.toc2 ul ul{padding-left:1.25em}body.toc2 body.toc2.toc-right{padding-left:0;padding-right:20em}body.toc2 #header,body.toc2 #content,body.toc2 #footnotes,body.toc2 #footer{padding-left:26.9375em;max-width:1400px}body.toc2 #header-spring h1{margin:0 auto;max-width:1400px}.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:0.8125em}body.toc2 #header,body.toc2 #content,body.toc2 #footer{background-repeat:repeat-y;background-position:24em 0;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAMAAAAoyzS7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQwIDc5LjE2MDQ1MSwgMjAxNy8wNS8wNi0wMTowODoyMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTggKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDE0NUNENzNGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDE0NUNENzRGMTVGMTFFODk5RjI5ODk3QURGRjcxMkEiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpEMTQ1Q0Q3MUYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpEMTQ1Q0Q3MkYxNUYxMUU4OTlGMjk4OTdBREZGNzEyQSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjmGxxYAAAAGUExURd3d2AAAAJlCnKAAAAAMSURBVHjaYmAACDAAAAIAAU9tWeEAAAAASUVORK5CYII=)}} diff --git a/reference/htmlsingle/favicon.ico b/reference/htmlsingle/favicon.ico new file mode 100644 index 0000000000..1a4956e647 Binary files /dev/null and b/reference/htmlsingle/favicon.ico differ diff --git a/reference/htmlsingle/images/Deps.png b/reference/htmlsingle/images/Deps.png new file mode 100644 index 0000000000..1426814308 Binary files /dev/null and b/reference/htmlsingle/images/Deps.png differ diff --git a/reference/htmlsingle/images/Stubs1.png b/reference/htmlsingle/images/Stubs1.png new file mode 100644 index 0000000000..ebadfdb910 Binary files /dev/null and b/reference/htmlsingle/images/Stubs1.png differ diff --git a/reference/htmlsingle/images/Stubs2.png b/reference/htmlsingle/images/Stubs2.png new file mode 100644 index 0000000000..e4bad24987 Binary files /dev/null and b/reference/htmlsingle/images/Stubs2.png differ diff --git a/reference/htmlsingle/js/highlight/highlight.min.js b/reference/htmlsingle/js/highlight/highlight.min.js new file mode 100644 index 0000000000..dcbbb4c7fc --- /dev/null +++ b/reference/htmlsingle/js/highlight/highlight.min.js @@ -0,0 +1,2 @@ +/*! highlight.js v9.13.1 | BSD3 License | git.io/hljslicense */ +!function(e){var n="object"==typeof window&&window||"object"==typeof self&&self;"undefined"!=typeof exports?e(exports):n&&(n.hljs=e({}),"function"==typeof define&&define.amd&&define([],function(){return n.hljs}))}(function(e){function n(e){return e.replace(/&/g,"&").replace(//g,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0===t.index}function a(e){return k.test(e)}function i(e){var n,t,r,i,o=e.className+" ";if(o+=e.parentNode?e.parentNode.className:"",t=M.exec(o))return w(t[1])?t[1]:"no-highlight";for(o=o.split(/\s+/),n=0,r=o.length;r>n;n++)if(i=o[n],a(i)||w(i))return i}function o(e){var n,t={},r=Array.prototype.slice.call(arguments,1);for(n in e)t[n]=e[n];return r.forEach(function(e){for(n in e)t[n]=e[n]}),t}function c(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3===i.nodeType?a+=i.nodeValue.length:1===i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function u(e,r,a){function i(){return e.length&&r.length?e[0].offset!==r[0].offset?e[0].offset"}function c(e){l+=""}function u(e){("start"===e.event?o:c)(e.node)}for(var s=0,l="",f=[];e.length||r.length;){var g=i();if(l+=n(a.substring(s,g[0].offset)),s=g[0].offset,g===e){f.reverse().forEach(c);do u(g.splice(0,1)[0]),g=i();while(g===e&&g.length&&g[0].offset===s);f.reverse().forEach(o)}else"start"===g[0].event?f.push(g[0].node):f.pop(),u(g.splice(0,1)[0])}return l+n(a.substr(s))}function s(e){return e.v&&!e.cached_variants&&(e.cached_variants=e.v.map(function(n){return o(e,{v:null},n)})),e.cached_variants||e.eW&&[o(e)]||[e]}function l(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var o={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");o[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):B(a.k).forEach(function(e){c(e,a.k[e])}),a.k=o}a.lR=t(a.l||/\w+/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.endSameAsBegin&&(a.e=a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),null==a.r&&(a.r=1),a.c||(a.c=[]),a.c=Array.prototype.concat.apply([],a.c.map(function(e){return s("self"===e?a:e)})),a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var u=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=u.length?t(u.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e){return new RegExp(e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}function c(e,n){var t,a;for(t=0,a=n.c.length;a>t;t++)if(r(n.c[t].bR,e))return n.c[t].endSameAsBegin&&(n.c[t].eR=o(n.c[t].bR.exec(e)[0])),n.c[t]}function u(e,n){if(r(e.eR,n)){for(;e.endsParent&&e.parent;)e=e.parent;return e}return e.eW?u(e.parent,n):void 0}function s(e,n){return!a&&r(n.iR,e)}function p(e,n){var t=R.cI?n[0].toLowerCase():n[0];return e.k.hasOwnProperty(t)&&e.k[t]}function d(e,n,t,r){var a=r?"":j.classPrefix,i='',i+n+o}function h(){var e,t,r,a;if(!E.k)return n(k);for(a="",t=0,E.lR.lastIndex=0,r=E.lR.exec(k);r;)a+=n(k.substring(t,r.index)),e=p(E,r),e?(M+=e[1],a+=d(e[0],n(r[0]))):a+=n(r[0]),t=E.lR.lastIndex,r=E.lR.exec(k);return a+n(k.substr(t))}function b(){var e="string"==typeof E.sL;if(e&&!L[E.sL])return n(k);var t=e?f(E.sL,k,!0,B[E.sL]):g(k,E.sL.length?E.sL:void 0);return E.r>0&&(M+=t.r),e&&(B[E.sL]=t.top),d(t.language,t.value,!1,!0)}function v(){y+=null!=E.sL?b():h(),k=""}function m(e){y+=e.cN?d(e.cN,"",!0):"",E=Object.create(e,{parent:{value:E}})}function N(e,n){if(k+=e,null==n)return v(),0;var t=c(n,E);if(t)return t.skip?k+=n:(t.eB&&(k+=n),v(),t.rB||t.eB||(k=n)),m(t,n),t.rB?0:n.length;var r=u(E,n);if(r){var a=E;a.skip?k+=n:(a.rE||a.eE||(k+=n),v(),a.eE&&(k=n));do E.cN&&(y+=I),E.skip||E.sL||(M+=E.r),E=E.parent;while(E!==r.parent);return r.starts&&(r.endSameAsBegin&&(r.starts.eR=r.eR),m(r.starts,"")),a.rE?0:n.length}if(s(n,E))throw new Error('Illegal lexeme "'+n+'" for mode "'+(E.cN||"")+'"');return k+=n,n.length||1}var R=w(e);if(!R)throw new Error('Unknown language: "'+e+'"');l(R);var x,E=i||R,B={},y="";for(x=E;x!==R;x=x.parent)x.cN&&(y=d(x.cN,"",!0)+y);var k="",M=0;try{for(var C,A,S=0;;){if(E.t.lastIndex=S,C=E.t.exec(t),!C)break;A=N(t.substring(S,C.index),C[0]),S=C.index+A}for(N(t.substr(S)),x=E;x.parent;x=x.parent)x.cN&&(y+=I);return{r:M,value:y,language:e,top:E}}catch(O){if(O.message&&-1!==O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function g(e,t){t=t||j.languages||B(L);var r={r:0,value:n(e)},a=r;return t.filter(w).filter(x).forEach(function(n){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}),a.language&&(r.second_best=a),r}function p(e){return j.tabReplace||j.useBR?e.replace(C,function(e,n){return j.useBR&&"\n"===e?"
":j.tabReplace?n.replace(/\t/g,j.tabReplace):""}):e}function d(e,n,t){var r=n?y[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function h(e){var n,t,r,o,s,l=i(e);a(l)||(j.useBR?(n=document.createElementNS("http://www.w3.org/1999/xhtml","div"),n.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):n=e,s=n.textContent,r=l?f(l,s,!0):g(s),t=c(n),t.length&&(o=document.createElementNS("http://www.w3.org/1999/xhtml","div"),o.innerHTML=r.value,r.value=u(t,c(o),s)),r.value=p(r.value),e.innerHTML=r.value,e.className=d(e.className,l,r.language),e.result={language:r.language,re:r.r},r.second_best&&(e.second_best={language:r.second_best.language,re:r.second_best.r}))}function b(e){j=o(j,e)}function v(){if(!v.called){v.called=!0;var e=document.querySelectorAll("pre code");E.forEach.call(e,h)}}function m(){addEventListener("DOMContentLoaded",v,!1),addEventListener("load",v,!1)}function N(n,t){var r=L[n]=t(e);r.aliases&&r.aliases.forEach(function(e){y[e]=n})}function R(){return B(L)}function w(e){return e=(e||"").toLowerCase(),L[e]||L[y[e]]}function x(e){var n=w(e);return n&&!n.disableAutodetect}var E=[],B=Object.keys,L={},y={},k=/^(no-?highlight|plain|text)$/i,M=/\blang(?:uage)?-([\w-]+)\b/i,C=/((^(<[^>]+>|\t|)+|(?:\n)))/gm,I="
",j={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0};return e.highlight=f,e.highlightAuto=g,e.fixMarkup=p,e.highlightBlock=h,e.configure=b,e.initHighlighting=v,e.initHighlightingOnLoad=m,e.registerLanguage=N,e.listLanguages=R,e.getLanguage=w,e.autoDetection=x,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e.METHOD_GUARD={b:"\\.\\s*"+e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/\b-?[a-z\._]+\b/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",_:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"meta",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,s,a,t]}});hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env arg user onbuild stopsignal",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{e:/[^\\]\n/,sL:"bash"}}],i:")?[^\s\(]+(\s+[^\s\(]+)\s*=/,r:5,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"type",b://,k:"reified",r:0},{cN:"params",b:/\(/,e:/\)/,endsParent:!0,k:t,r:0,c:[{b:/:/,e:/[=,\/]/,eW:!0,c:[{cN:"type",b:e.UIR},e.CLCM,e.CBCM],r:0},e.CLCM,e.CBCM,s,l,c,e.CNM]},e.CBCM]},{cN:"class",bK:"class interface trait",e:/[:\{(]|$/,eE:!0,i:"extends implements",c:[{bK:"public protected internal private constructor"},e.UTM,{cN:"type",b://,eB:!0,eE:!0,r:0},{cN:"type",b:/[,:]\s*/,e:/[<\(,]|$/,eB:!0,rE:!0},s,l]},c,{cN:"meta",b:"^#!/usr/bin/env",e:"$",i:"\n"},o]}});hljs.registerLanguage("java",function(e){var a="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",t=a+"(<"+a+"(\\s*,\\s*"+a+")*>)?",r="false synchronized int abstract float private char boolean var static null if const for true while long strictfp finally protected import native final void enum else break transient catch instanceof byte super volatile case assert short package default double public try this switch continue throws protected public private module requires exports do",s="\\b(0[bB]([01]+[01_]+[01]+|[01]+)|0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)|(([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?|\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))([eE][-+]?\\d+)?)[lLfF]?",c={cN:"number",b:s,r:0};return{aliases:["jsp"],k:r,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"new throw return else",r:0},{cN:"function",b:"("+t+"\\s+)+"+e.UIR+"\\s*\\(",rB:!0,e:/[{;=]/,eE:!0,k:r,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,k:r,r:0,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},c,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("xml",function(s){var e="[A-Za-z0-9\\._:-]+",t={eW:!0,i:/`]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist"],cI:!0,c:[{cN:"meta",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},s.C("",{r:10}),{b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"meta",b:/<\?xml/,e:/\?>/,r:10},{b:/<\?(php)?/,e:/\?>/,sL:"php",c:[{b:"/\\*",e:"\\*/",skip:!0},{b:'b"',e:'"',skip:!0},{b:"b'",e:"'",skip:!0},s.inherit(s.ASM,{i:null,cN:null,c:null,skip:!0}),s.inherit(s.QSM,{i:null,cN:null,c:null,skip:!0})]},{cN:"tag",b:"|$)",e:">",k:{name:"style"},c:[t],starts:{e:"",rE:!0,sL:["css","xml"]}},{cN:"tag",b:"|$)",e:">",k:{name:"script"},c:[t],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars","xml"]}},{cN:"tag",b:"",c:[{cN:"name",b:/[^\/><\s]+/,r:0},t]}]}});hljs.registerLanguage("properties",function(r){var t="[ \\t\\f]*",e="[ \\t\\f]+",s="("+t+"[:=]"+t+"|"+e+")",n="([^\\\\\\W:= \\t\\f\\n]|\\\\.)+",a="([^\\\\:= \\t\\f\\n]|\\\\.)+",c={e:s,r:0,starts:{cN:"string",e:/$/,r:0,c:[{b:"\\\\\\n"}]}};return{cI:!0,i:/\S/,c:[r.C("^\\s*[!#]","$"),{b:n+s,rB:!0,c:[{cN:"attr",b:n,endsParent:!0,r:0}],starts:c},{b:a+s,rB:!0,r:0,c:[{cN:"meta",b:a,endsParent:!0,r:0}],starts:c},{cN:"attr",r:0,b:a+t+"$"}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"meta",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"comment",v:[{b:/Index: /,e:/$/},{b:/={3,}/,e:/$/},{b:/^\-{3}/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+{3}/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"addition",b:"^\\!",e:"$"}]}});hljs.registerLanguage("shell",function(s){return{aliases:["console"],c:[{cN:"meta",b:"^\\s{0,3}[\\w\\d\\[\\]()@-]*[>%$#]",starts:{e:"$",sL:"bash"}}]}});hljs.registerLanguage("asciidoc",function(e){return{aliases:["adoc"],c:[e.C("^/{4,}\\n","\\n/{4,}$",{r:10}),e.C("^//","$",{r:0}),{cN:"title",b:"^\\.\\w.*$"},{b:"^[=\\*]{4,}\\n",e:"\\n^[=\\*]{4,}$",r:10},{cN:"section",r:10,v:[{b:"^(={1,5}) .+?( \\1)?$"},{b:"^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$"}]},{cN:"meta",b:"^:.+?:",e:"\\s",eE:!0,r:10},{cN:"meta",b:"^\\[.+?\\]$",r:0},{cN:"quote",b:"^_{4,}\\n",e:"\\n_{4,}$",r:10},{cN:"code",b:"^[\\-\\.]{4,}\\n",e:"\\n[\\-\\.]{4,}$",r:10},{b:"^\\+{4,}\\n",e:"\\n\\+{4,}$",c:[{b:"<",e:">",sL:"xml",r:0}],r:10},{cN:"bullet",b:"^(\\*+|\\-+|\\.+|[^\\n]+?::)\\s+"},{cN:"symbol",b:"^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+",r:10},{cN:"strong",b:"\\B\\*(?![\\*\\s])",e:"(\\n{2}|\\*)",c:[{b:"\\\\*\\w",r:0}]},{cN:"emphasis",b:"\\B'(?!['\\s])",e:"(\\n{2}|')",c:[{b:"\\\\'\\w",r:0}],r:0},{cN:"emphasis",b:"_(?![_\\s])",e:"(\\n{2}|_)",r:0},{cN:"string",v:[{b:"``.+?''"},{b:"`.+?'"}]},{cN:"code",b:"(`.+?`|\\+.+?\\+)",r:0},{cN:"code",b:"^[ \\t]",e:"$",r:0},{b:"^'{3,}[ \\t]*$",r:10},{b:"(link:)?(http|https|ftp|file|irc|image:?):\\S+\\[.*?\\]",rB:!0,c:[{b:"(link|image:?):",r:0},{cN:"link",b:"\\w",e:"[^\\[]+",r:0},{cN:"string",b:"\\[",e:"\\]",eB:!0,eE:!0,r:0}],r:10}]}});hljs.registerLanguage("aspectj",function(e){var t="false synchronized int abstract float private char boolean static null if const for true while long throw strictfp finally protected import native final return void enum else extends implements break transient new catch instanceof byte super volatile case assert short package default double public try this switch continue throws privileged aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization staticinitialization withincode target within execution getWithinTypeName handler thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents warning error soft precedence thisAspectInstance",i="get set args call";return{k:t,i:/<\/|#/,c:[e.C("/\\*\\*","\\*/",{r:0,c:[{b:/\w+@/,r:0},{cN:"doctag",b:"@[A-Za-z]+"}]}),e.CLCM,e.CBCM,e.ASM,e.QSM,{cN:"class",bK:"aspect",e:/[{;=]/,eE:!0,i:/[:;"\[\]]/,c:[{bK:"extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton"},e.UTM,{b:/\([^\)]*/,e:/[)]+/,k:t+" "+i,eE:!1}]},{cN:"class",bK:"class interface",e:/[{;=]/,eE:!0,r:0,k:"class interface",i:/[:"\[\]]/,c:[{bK:"extends implements"},e.UTM]},{bK:"pointcut after before around throwing returning",e:/[)]/,eE:!1,i:/["\[\]]/,c:[{b:e.UIR+"\\s*\\(",rB:!0,c:[e.UTM]}]},{b:/[:]/,rB:!0,e:/[{;]/,r:0,eE:!1,k:t,i:/["\[\]]/,c:[{b:e.UIR+"\\s*\\(",k:t+" "+i,r:0},e.QSM]},{bK:"new throw",r:0},{cN:"function",b:/\w+ +\w+(\.)?\w+\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,rB:!0,e:/[{;=]/,k:t,eE:!0,c:[{b:e.UIR+"\\s*\\(",rB:!0,r:0,c:[e.UTM]},{cN:"params",b:/\(/,e:/\)/,r:0,k:t,c:[e.ASM,e.QSM,e.CNM,e.CBCM]},e.CLCM,e.CBCM]},e.CNM,{cN:"meta",b:"@[A-Za-z]+"}]}});hljs.registerLanguage("gradle",function(e){return{cI:!0,k:{keyword:"task project allprojects subprojects artifacts buildscript configurations dependencies repositories sourceSets description delete from into include exclude source classpath destinationDir includes options sourceCompatibility targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant def abstract break case catch continue default do else extends final finally for if implements instanceof native new private protected public return static switch synchronized throw throws transient try volatile while strictfp package import false null super this true antlrtask checkstyle codenarc copy boolean byte char class double float int interface long short void compile runTime file fileTree abs any append asList asWritable call collect compareTo count div dump each eachByte eachFile eachLine every find findAll flatten getAt getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter newReader newWriter next plus pop power previous print println push putAt read readBytes readLines reverse reverseEach round size sort splitEachLine step subMap times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader withStream withWriter withWriterAppend write writeLine"},c:[e.CLCM,e.CBCM,e.ASM,e.QSM,e.NM,e.RM]}});hljs.registerLanguage("json",function(e){var i={literal:"true false null"},n=[e.QSM,e.CNM],r={e:",",eW:!0,eE:!0,c:n,k:i},t={b:"{",e:"}",c:[{cN:"attr",b:/"/,e:/"/,c:[e.BE],i:"\\n"},e.inherit(r,{b:/:/})],i:"\\S"},c={b:"\\[",e:"\\]",c:[e.inherit(r)],i:"\\S"};return n.splice(n.length,0,t,c),{c:n,k:i,i:"\\S"}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*]/,c:[{bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke comment with",e:/;/,eW:!0,l:/[\w\.]+/,k:{keyword:"as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null unknown",built_in:"array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text time timestamp varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t,e.HCM]},e.CBCM,t,e.HCM]}});hljs.registerLanguage("go",function(e){var t={keyword:"break default func interface select case map struct chan else goto package switch const fallthrough if range type continue for import return var go defer bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 uint16 uint32 uint64 int uint uintptr rune",literal:"true false iota nil",built_in:"append cap close complex copy imag len make new panic print println real recover delete"};return{aliases:["golang"],k:t,i:"",rB:!0,e:"\\s*=>",c:[{cN:"params",v:[{b:r},{b:/\(\s*\)/},{b:/\(/,e:/\)/,eB:!0,eE:!0,k:t,c:s}]}]},{b://,sL:"xml",c:[{b:/<\w+\s*\/>/,skip:!0},{b:/<\w+/,e:/(\/\w+|\w+\/)>/,skip:!0,c:[{b:/<\w+\s*\/>/,skip:!0},"self"]}]}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:r}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:s}],i:/\[|%/},{b:/\$[(.]/},e.METHOD_GUARD,{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]},{bK:"constructor",e:/\{/,eE:!0}],i:/#(?!!)/}}); \ No newline at end of file diff --git a/reference/htmlsingle/js/highlight/styles/a11y-dark.min.css b/reference/htmlsingle/js/highlight/styles/a11y-dark.min.css new file mode 100644 index 0000000000..b93b742a45 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/a11y-dark.min.css @@ -0,0 +1,99 @@ +/* a11y-dark theme */ +/* Based on the Tomorrow Night Eighties theme: https://github.com/isagalaev/highlight.js/blob/master/src/styles/tomorrow-night-eighties.css */ +/* @author: ericwbailey */ + +/* Comment */ +.hljs-comment, +.hljs-quote { + color: #d4d0ab; +} + +/* Red */ +.hljs-variable, +.hljs-template-variable, +.hljs-tag, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-regexp, +.hljs-deletion { + color: #ffa07a; +} + +/* Orange */ +.hljs-number, +.hljs-built_in, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params, +.hljs-meta, +.hljs-link { + color: #f5ab35; +} + +/* Yellow */ +.hljs-attribute { + color: #ffd700; +} + +/* Green */ +.hljs-string, +.hljs-symbol, +.hljs-bullet, +.hljs-addition { + color: #abe338; +} + +/* Blue */ +.hljs-title, +.hljs-section { + color: #00e0e0; +} + +/* Purple */ +.hljs-keyword, +.hljs-selector-tag { + color: #dcc6e0; +} + +.hljs { + display: block; + overflow-x: auto; + background: #2b2b2b; + color: #f8f8f2; + padding: 0.5em; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +@media screen and (-ms-high-contrast: active) { + .hljs-addition, + .hljs-attribute, + .hljs-built_in, + .hljs-builtin-name, + .hljs-bullet, + .hljs-comment, + .hljs-link, + .hljs-literal, + .hljs-meta, + .hljs-number, + .hljs-params, + .hljs-string, + .hljs-symbol, + .hljs-type, + .hljs-quote { + color: highlight; + } + + .hljs-keyword, + .hljs-selector-tag { + font-weight: bold; + } +} diff --git a/reference/htmlsingle/js/highlight/styles/an-old-hope.min.css b/reference/htmlsingle/js/highlight/styles/an-old-hope.min.css new file mode 100644 index 0000000000..a6d56f4b40 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/an-old-hope.min.css @@ -0,0 +1,89 @@ +/* + +An Old Hope – Star Wars Syntax (c) Gustavo Costa +Original theme - Ocean Dark Theme – by https://github.com/gavsiu +Based on Jesse Leite's Atom syntax theme 'An Old Hope' – https://github.com/JesseLeite/an-old-hope-syntax-atom + +*/ + +/* Death Star Comment */ +.hljs-comment, +.hljs-quote +{ + color: #B6B18B; +} + +/* Darth Vader */ +.hljs-variable, +.hljs-template-variable, +.hljs-tag, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-regexp, +.hljs-deletion +{ + color: #EB3C54; +} + +/* Threepio */ +.hljs-number, +.hljs-built_in, +.hljs-builtin-name, +.hljs-literal, +.hljs-type, +.hljs-params, +.hljs-meta, +.hljs-link +{ + color: #E7CE56; +} + +/* Luke Skywalker */ +.hljs-attribute +{ + color: #EE7C2B; +} + +/* Obi Wan Kenobi */ +.hljs-string, +.hljs-symbol, +.hljs-bullet, +.hljs-addition +{ + color: #4FB4D7; +} + +/* Yoda */ +.hljs-title, +.hljs-section +{ + color: #78BB65; +} + +/* Mace Windu */ +.hljs-keyword, +.hljs-selector-tag +{ + color: #B45EA4; +} + +/* Millenium Falcon */ +.hljs +{ + display: block; + overflow-x: auto; + background: #1C1D21; + color: #c0c5ce; + padding: 0.5em; +} + +.hljs-emphasis +{ + font-style: italic; +} + +.hljs-strong +{ + font-weight: bold; +} diff --git a/reference/htmlsingle/js/highlight/styles/atom-one-dark-reasonable.min.css b/reference/htmlsingle/js/highlight/styles/atom-one-dark-reasonable.min.css new file mode 100644 index 0000000000..fd41c996a3 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/atom-one-dark-reasonable.min.css @@ -0,0 +1,77 @@ +/* + +Atom One Dark With support for ReasonML by Gidi Morris, based off work by Daniel Gamage + +Original One Dark Syntax theme from https://github.com/atom/one-dark-syntax + +*/ +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + line-height: 1.3em; + color: #abb2bf; + background: #282c34; + border-radius: 5px; +} +.hljs-keyword, .hljs-operator { + color: #F92672; +} +.hljs-pattern-match { + color: #F92672; +} +.hljs-pattern-match .hljs-constructor { + color: #61aeee; +} +.hljs-function { + color: #61aeee; +} +.hljs-function .hljs-params { + color: #A6E22E; +} +.hljs-function .hljs-params .hljs-typing { + color: #FD971F; +} +.hljs-module-access .hljs-module { + color: #7e57c2; +} +.hljs-constructor { + color: #e2b93d; +} +.hljs-constructor .hljs-string { + color: #9CCC65; +} +.hljs-comment, .hljs-quote { + color: #b18eb1; + font-style: italic; +} +.hljs-doctag, .hljs-formula { + color: #c678dd; +} +.hljs-section, .hljs-name, .hljs-selector-tag, .hljs-deletion, .hljs-subst { + color: #e06c75; +} +.hljs-literal { + color: #56b6c2; +} +.hljs-string, .hljs-regexp, .hljs-addition, .hljs-attribute, .hljs-meta-string { + color: #98c379; +} +.hljs-built_in, .hljs-class .hljs-title { + color: #e6c07b; +} +.hljs-attr, .hljs-variable, .hljs-template-variable, .hljs-type, .hljs-selector-class, .hljs-selector-attr, .hljs-selector-pseudo, .hljs-number { + color: #d19a66; +} +.hljs-symbol, .hljs-bullet, .hljs-link, .hljs-meta, .hljs-selector-id, .hljs-title { + color: #61aeee; +} +.hljs-emphasis { + font-style: italic; +} +.hljs-strong { + font-weight: bold; +} +.hljs-link { + text-decoration: underline; +} diff --git a/reference/htmlsingle/js/highlight/styles/atom-one-dark.min.css b/reference/htmlsingle/js/highlight/styles/atom-one-dark.min.css new file mode 100644 index 0000000000..1616aafe31 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/atom-one-dark.min.css @@ -0,0 +1,96 @@ +/* + +Atom One Dark by Daniel Gamage +Original One Dark Syntax theme from https://github.com/atom/one-dark-syntax + +base: #282c34 +mono-1: #abb2bf +mono-2: #818896 +mono-3: #5c6370 +hue-1: #56b6c2 +hue-2: #61aeee +hue-3: #c678dd +hue-4: #98c379 +hue-5: #e06c75 +hue-5-2: #be5046 +hue-6: #d19a66 +hue-6-2: #e6c07b + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #abb2bf; + background: #282c34; +} + +.hljs-comment, +.hljs-quote { + color: #5c6370; + font-style: italic; +} + +.hljs-doctag, +.hljs-keyword, +.hljs-formula { + color: #c678dd; +} + +.hljs-section, +.hljs-name, +.hljs-selector-tag, +.hljs-deletion, +.hljs-subst { + color: #e06c75; +} + +.hljs-literal { + color: #56b6c2; +} + +.hljs-string, +.hljs-regexp, +.hljs-addition, +.hljs-attribute, +.hljs-meta-string { + color: #98c379; +} + +.hljs-built_in, +.hljs-class .hljs-title { + color: #e6c07b; +} + +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-type, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-number { + color: #d19a66; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link, +.hljs-meta, +.hljs-selector-id, +.hljs-title { + color: #61aeee; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-link { + text-decoration: underline; +} diff --git a/reference/htmlsingle/js/highlight/styles/atom-one-light.min.css b/reference/htmlsingle/js/highlight/styles/atom-one-light.min.css new file mode 100644 index 0000000000..d5bd1d2a9a --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/atom-one-light.min.css @@ -0,0 +1,96 @@ +/* + +Atom One Light by Daniel Gamage +Original One Light Syntax theme from https://github.com/atom/one-light-syntax + +base: #fafafa +mono-1: #383a42 +mono-2: #686b77 +mono-3: #a0a1a7 +hue-1: #0184bb +hue-2: #4078f2 +hue-3: #a626a4 +hue-4: #50a14f +hue-5: #e45649 +hue-5-2: #c91243 +hue-6: #986801 +hue-6-2: #c18401 + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #383a42; + background: #fafafa; +} + +.hljs-comment, +.hljs-quote { + color: #a0a1a7; + font-style: italic; +} + +.hljs-doctag, +.hljs-keyword, +.hljs-formula { + color: #a626a4; +} + +.hljs-section, +.hljs-name, +.hljs-selector-tag, +.hljs-deletion, +.hljs-subst { + color: #e45649; +} + +.hljs-literal { + color: #0184bb; +} + +.hljs-string, +.hljs-regexp, +.hljs-addition, +.hljs-attribute, +.hljs-meta-string { + color: #50a14f; +} + +.hljs-built_in, +.hljs-class .hljs-title { + color: #c18401; +} + +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-type, +.hljs-selector-class, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-number { + color: #986801; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link, +.hljs-meta, +.hljs-selector-id, +.hljs-title { + color: #4078f2; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-link { + text-decoration: underline; +} diff --git a/reference/htmlsingle/js/highlight/styles/dracula.min.css b/reference/htmlsingle/js/highlight/styles/dracula.min.css new file mode 100644 index 0000000000..d591db6801 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/dracula.min.css @@ -0,0 +1,76 @@ +/* + +Dracula Theme v1.2.0 + +https://github.com/zenorocha/dracula-theme + +Copyright 2015, All rights reserved + +Code licensed under the MIT license +http://zenorocha.mit-license.org + +@author Éverton Ribeiro +@author Zeno Rocha + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #282a36; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-section, +.hljs-link { + color: #8be9fd; +} + +.hljs-function .hljs-keyword { + color: #ff79c6; +} + +.hljs, +.hljs-subst { + color: #f8f8f2; +} + +.hljs-string, +.hljs-title, +.hljs-name, +.hljs-type, +.hljs-attribute, +.hljs-symbol, +.hljs-bullet, +.hljs-addition, +.hljs-variable, +.hljs-template-tag, +.hljs-template-variable { + color: #f1fa8c; +} + +.hljs-comment, +.hljs-quote, +.hljs-deletion, +.hljs-meta { + color: #6272a4; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-title, +.hljs-section, +.hljs-doctag, +.hljs-type, +.hljs-name, +.hljs-strong { + font-weight: bold; +} + +.hljs-emphasis { + font-style: italic; +} diff --git a/reference/htmlsingle/js/highlight/styles/github.min.css b/reference/htmlsingle/js/highlight/styles/github.min.css new file mode 100644 index 0000000000..791932b87e --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/github.min.css @@ -0,0 +1,99 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; +} + +.hljs-comment, +.hljs-quote { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-subst { + color: #333; + font-weight: bold; +} + +.hljs-number, +.hljs-literal, +.hljs-variable, +.hljs-template-variable, +.hljs-tag .hljs-attr { + color: #008080; +} + +.hljs-string, +.hljs-doctag { + color: #d14; +} + +.hljs-title, +.hljs-section, +.hljs-selector-id { + color: #900; + font-weight: bold; +} + +.hljs-subst { + font-weight: normal; +} + +.hljs-type, +.hljs-class .hljs-title { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-name, +.hljs-attribute { + color: #000080; + font-weight: normal; +} + +.hljs-regexp, +.hljs-link { + color: #009926; +} + +.hljs-symbol, +.hljs-bullet { + color: #990073; +} + +.hljs-built_in, +.hljs-builtin-name { + color: #0086b3; +} + +.hljs-meta { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/htmlsingle/js/highlight/styles/monokai-sublime.min.css b/reference/htmlsingle/js/highlight/styles/monokai-sublime.min.css new file mode 100644 index 0000000000..2864170daf --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/monokai-sublime.min.css @@ -0,0 +1,83 @@ +/* + +Monokai Sublime style. Derived from Monokai by noformnocontent http://nn.mit-license.org/ + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #23241f; +} + +.hljs, +.hljs-tag, +.hljs-subst { + color: #f8f8f2; +} + +.hljs-strong, +.hljs-emphasis { + color: #a8a8a2; +} + +.hljs-bullet, +.hljs-quote, +.hljs-number, +.hljs-regexp, +.hljs-literal, +.hljs-link { + color: #ae81ff; +} + +.hljs-code, +.hljs-title, +.hljs-section, +.hljs-selector-class { + color: #a6e22e; +} + +.hljs-strong { + font-weight: bold; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-name, +.hljs-attr { + color: #f92672; +} + +.hljs-symbol, +.hljs-attribute { + color: #66d9ef; +} + +.hljs-params, +.hljs-class .hljs-title { + color: #f8f8f2; +} + +.hljs-string, +.hljs-type, +.hljs-built_in, +.hljs-builtin-name, +.hljs-selector-id, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-addition, +.hljs-variable, +.hljs-template-variable { + color: #e6db74; +} + +.hljs-comment, +.hljs-deletion, +.hljs-meta { + color: #75715e; +} diff --git a/reference/htmlsingle/js/highlight/styles/monokai.min.css b/reference/htmlsingle/js/highlight/styles/monokai.min.css new file mode 100644 index 0000000000..775d53f91a --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/monokai.min.css @@ -0,0 +1,70 @@ +/* +Monokai style - ported by Luigi Maselli - http://grigio.org +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #272822; color: #ddd; +} + +.hljs-tag, +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-strong, +.hljs-name { + color: #f92672; +} + +.hljs-code { + color: #66d9ef; +} + +.hljs-class .hljs-title { + color: white; +} + +.hljs-attribute, +.hljs-symbol, +.hljs-regexp, +.hljs-link { + color: #bf79db; +} + +.hljs-string, +.hljs-bullet, +.hljs-subst, +.hljs-title, +.hljs-section, +.hljs-emphasis, +.hljs-type, +.hljs-built_in, +.hljs-builtin-name, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-addition, +.hljs-variable, +.hljs-template-tag, +.hljs-template-variable { + color: #a6e22e; +} + +.hljs-comment, +.hljs-quote, +.hljs-deletion, +.hljs-meta { + color: #75715e; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-literal, +.hljs-doctag, +.hljs-title, +.hljs-section, +.hljs-type, +.hljs-selector-id { + font-weight: bold; +} diff --git a/reference/htmlsingle/js/highlight/styles/solarized-light.min.css b/reference/htmlsingle/js/highlight/styles/solarized-light.min.css new file mode 100644 index 0000000000..fdcfcc72c4 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/solarized-light.min.css @@ -0,0 +1,84 @@ +/* + +Orginal Style from ethanschoonover.com/solarized (c) Jeremy Hull + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #fdf6e3; + color: #657b83; +} + +.hljs-comment, +.hljs-quote { + color: #93a1a1; +} + +/* Solarized Green */ +.hljs-keyword, +.hljs-selector-tag, +.hljs-addition { + color: #859900; +} + +/* Solarized Cyan */ +.hljs-number, +.hljs-string, +.hljs-meta .hljs-meta-string, +.hljs-literal, +.hljs-doctag, +.hljs-regexp { + color: #2aa198; +} + +/* Solarized Blue */ +.hljs-title, +.hljs-section, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class { + color: #268bd2; +} + +/* Solarized Yellow */ +.hljs-attribute, +.hljs-attr, +.hljs-variable, +.hljs-template-variable, +.hljs-class .hljs-title, +.hljs-type { + color: #b58900; +} + +/* Solarized Orange */ +.hljs-symbol, +.hljs-bullet, +.hljs-subst, +.hljs-meta, +.hljs-meta .hljs-keyword, +.hljs-selector-attr, +.hljs-selector-pseudo, +.hljs-link { + color: #cb4b16; +} + +/* Solarized Red */ +.hljs-built_in, +.hljs-deletion { + color: #dc322f; +} + +.hljs-formula { + background: #eee8d5; +} + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/htmlsingle/js/highlight/styles/zenburn.min.css b/reference/htmlsingle/js/highlight/styles/zenburn.min.css new file mode 100644 index 0000000000..07be502016 --- /dev/null +++ b/reference/htmlsingle/js/highlight/styles/zenburn.min.css @@ -0,0 +1,80 @@ +/* + +Zenburn style from voldmar.ru (c) Vladimir Epifanov +based on dark.css by Ivan Sagalaev + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + background: #3f3f3f; + color: #dcdcdc; +} + +.hljs-keyword, +.hljs-selector-tag, +.hljs-tag { + color: #e3ceab; +} + +.hljs-template-tag { + color: #dcdcdc; +} + +.hljs-number { + color: #8cd0d3; +} + +.hljs-variable, +.hljs-template-variable, +.hljs-attribute { + color: #efdcbc; +} + +.hljs-literal { + color: #efefaf; +} + +.hljs-subst { + color: #8f8f8f; +} + +.hljs-title, +.hljs-name, +.hljs-selector-id, +.hljs-selector-class, +.hljs-section, +.hljs-type { + color: #efef8f; +} + +.hljs-symbol, +.hljs-bullet, +.hljs-link { + color: #dca3a3; +} + +.hljs-deletion, +.hljs-string, +.hljs-built_in, +.hljs-builtin-name { + color: #cc9393; +} + +.hljs-addition, +.hljs-comment, +.hljs-quote, +.hljs-meta { + color: #7f9f7f; +} + + +.hljs-emphasis { + font-style: italic; +} + +.hljs-strong { + font-weight: bold; +} diff --git a/reference/htmlsingle/js/toc.js b/reference/htmlsingle/js/toc.js new file mode 100644 index 0000000000..a6e933bf96 --- /dev/null +++ b/reference/htmlsingle/js/toc.js @@ -0,0 +1,107 @@ +var toctitle = document.getElementById('toctitle'); +var path = window.location.pathname; +if (toctitle != null) { + var oldtoc = toctitle.nextElementSibling; + var newtoc = document.createElement('div'); + newtoc.setAttribute('id', 'tocbot'); + newtoc.setAttribute('class', 'js-toc desktop-toc'); + oldtoc.setAttribute('class', 'mobile-toc'); + oldtoc.parentNode.appendChild(newtoc); + tocbot.init({ + contentSelector: '#content', + headingSelector: 'h1, h2, h3, h4, h5', + positionFixedSelector: 'body', + fixedSidebarOffset: 90, + smoothScroll: false + }); + if (!path.endsWith("index.html") && !path.endsWith("/")) { + var link = document.createElement("a"); + link.setAttribute("href", "index.html"); + link.innerHTML = " Back to index"; + var block = document.createElement("div"); + block.setAttribute('class', 'back-action'); + block.appendChild(link); + var toc = document.getElementById('toc'); + var next = document.getElementById('toctitle').nextElementSibling; + toc.insertBefore(block, next); + } +} + +var headerHtml = '
\n' + + '

\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '\n' + + '

\n' + + '
'; + +var header = document.createElement("div"); +header.innerHTML = headerHtml; +document.body.insertBefore(header, document.body.firstChild); \ No newline at end of file diff --git a/reference/htmlsingle/js/tocbot/tocbot.css b/reference/htmlsingle/js/tocbot/tocbot.css new file mode 100644 index 0000000000..0632de2328 --- /dev/null +++ b/reference/htmlsingle/js/tocbot/tocbot.css @@ -0,0 +1 @@ +.toc{overflow-y:auto}.toc>.toc-list{overflow:hidden;position:relative}.toc>.toc-list li{list-style:none}.toc-list{margin:0;padding-left:10px}a.toc-link{color:currentColor;height:100%}.is-collapsible{max-height:1000px;overflow:hidden;transition:all 300ms ease-in-out}.is-collapsed{max-height:0}.is-position-fixed{position:fixed !important;top:0}.is-active-link{font-weight:700}.toc-link::before{background-color:#EEE;content:' ';display:inline-block;height:inherit;left:0;margin-top:-1px;position:absolute;width:2px}.is-active-link::before{background-color:#54BC4B} diff --git a/reference/htmlsingle/js/tocbot/tocbot.min.js b/reference/htmlsingle/js/tocbot/tocbot.min.js new file mode 100644 index 0000000000..943d8fdb77 --- /dev/null +++ b/reference/htmlsingle/js/tocbot/tocbot.min.js @@ -0,0 +1 @@ +!function(e){function t(o){if(n[o])return n[o].exports;var l=n[o]={i:o,l:!1,exports:{}};return e[o].call(l.exports,l,l.exports,t),l.l=!0,l.exports}var n={};t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=0)}([function(e,t,n){(function(o){var l,i,s;!function(n,o){i=[],l=o(n),void 0!==(s="function"==typeof l?l.apply(t,i):l)&&(e.exports=s)}(void 0!==o?o:this.window||this.global,function(e){"use strict";function t(){for(var e={},t=0;te.fixedSidebarOffset?-1===n.className.indexOf(e.positionFixedClass)&&(n.className+=h+e.positionFixedClass):n.className=n.className.split(h+e.positionFixedClass).join("")}function s(t){var n=document.documentElement.scrollTop||f.scrollTop;e.positionFixedSelector&&i();var o,l=t;if(m&&null!==document.querySelector(e.tocSelector)&&l.length>0){d.call(l,function(t,i){if(t.offsetTop>n+e.headingsOffset+10){return o=l[0===i?i:i-1],!0}if(i===l.length-1)return o=l[l.length-1],!0});var s=document.querySelector(e.tocSelector).querySelectorAll("."+e.linkClass);u.call(s,function(t){t.className=t.className.split(h+e.activeLinkClass).join("")});var c=document.querySelector(e.tocSelector).querySelectorAll("."+e.listItemClass);u.call(c,function(t){t.className=t.className.split(h+e.activeListItemClass).join("")});var a=document.querySelector(e.tocSelector).querySelector("."+e.linkClass+".node-name--"+o.nodeName+'[href="#'+o.id+'"]');-1===a.className.indexOf(e.activeLinkClass)&&(a.className+=h+e.activeLinkClass);var p=a.parentNode;p&&-1===p.className.indexOf(e.activeListItemClass)&&(p.className+=h+e.activeListItemClass);var C=document.querySelector(e.tocSelector).querySelectorAll("."+e.listClass+"."+e.collapsibleClass);u.call(C,function(t){-1===t.className.indexOf(e.isCollapsedClass)&&(t.className+=h+e.isCollapsedClass)}),a.nextSibling&&-1!==a.nextSibling.className.indexOf(e.isCollapsedClass)&&(a.nextSibling.className=a.nextSibling.className.split(h+e.isCollapsedClass).join("")),r(a.parentNode.parentNode)}}function r(t){return-1!==t.className.indexOf(e.collapsibleClass)&&-1!==t.className.indexOf(e.isCollapsedClass)?(t.className=t.className.split(h+e.isCollapsedClass).join(""),r(t.parentNode.parentNode)):t}function c(t){var n=t.target||t.srcElement;"string"==typeof n.className&&-1!==n.className.indexOf(e.linkClass)&&(m=!1)}function a(){m=!0}var u=[].forEach,d=[].some,f=document.body,m=!0,h=" ";return{enableTocAnimation:a,disableTocAnimation:c,render:n,updateToc:s}}},function(e,t){e.exports=function(e){function t(e){return e[e.length-1]}function n(e){return+e.nodeName.split("H").join("")}function o(t){var o={id:t.id,children:[],nodeName:t.nodeName,headingLevel:n(t),textContent:t.textContent.trim()};return e.includeHtml&&(o.childNodes=t.childNodes),o}function l(l,i){for(var s=o(l),r=n(l),c=i,a=t(c),u=a?a.headingLevel:0,d=r-u;d>0;)a=t(c),a&&void 0!==a.children&&(c=a.children),d--;return r>=e.collapseDepth&&(s.isCollapsed=!0),c.push(s),c}function i(t,n){var o=n;e.ignoreSelector&&(o=n.split(",").map(function(t){return t.trim()+":not("+e.ignoreSelector+")"}));try{return document.querySelector(t).querySelectorAll(o)}catch(e){return console.warn("Element not found: "+t),null}}function s(e){return r.call(e,function(e,t){return l(o(t),e.nest),e},{nest:[]})}var r=[].reduce;return{nestHeadingsArray:s,selectHeadings:i}}},function(e,t){function n(e){function t(e){return"a"===e.tagName.toLowerCase()&&(e.hash.length>0||"#"===e.href.charAt(e.href.length-1))&&(n(e.href)===s||n(e.href)+"#"===s)}function n(e){return e.slice(0,e.lastIndexOf("#"))}function l(e){var t=document.getElementById(e.substring(1));t&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())}!function(){document.documentElement.style}();var i=e.duration,s=location.hash?n(location.href):location.href;!function(){function n(n){!t(n.target)||n.target.className.indexOf("no-smooth-scroll")>-1||"#"===n.target.href.charAt(n.target.href.length-2)&&"!"===n.target.href.charAt(n.target.href.length-1)||-1===n.target.className.indexOf(e.linkClass)||o(n.target.hash,{duration:i,callback:function(){l(n.target.hash)}})}document.body.addEventListener("click",n,!1)}()}function o(e,t){function n(e){s=e-i,window.scrollTo(0,c.easing(s,r,u,d)),s - + All Classes (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/allclasses-noframe.html b/spring-cloud-contract-maven-plugin/apidocs/allclasses-noframe.html index 4098674de3..8350f388a3 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/allclasses-noframe.html +++ b/spring-cloud-contract-maven-plugin/apidocs/allclasses-noframe.html @@ -2,10 +2,10 @@ - + All Classes (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/constant-values.html b/spring-cloud-contract-maven-plugin/apidocs/constant-values.html index 9d522e0f66..138427ba68 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/constant-values.html +++ b/spring-cloud-contract-maven-plugin/apidocs/constant-values.html @@ -2,10 +2,10 @@ - + Constant Field Values (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/deprecated-list.html b/spring-cloud-contract-maven-plugin/apidocs/deprecated-list.html index 274de0e3d3..31d4a816cf 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/deprecated-list.html +++ b/spring-cloud-contract-maven-plugin/apidocs/deprecated-list.html @@ -2,10 +2,10 @@ - + Deprecated List (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/help-doc.html b/spring-cloud-contract-maven-plugin/apidocs/help-doc.html index 9b53da686d..15c9665f66 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/help-doc.html +++ b/spring-cloud-contract-maven-plugin/apidocs/help-doc.html @@ -2,10 +2,10 @@ - + API Help (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/index-all.html b/spring-cloud-contract-maven-plugin/apidocs/index-all.html index d78001c7cf..5e657cef33 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/index-all.html +++ b/spring-cloud-contract-maven-plugin/apidocs/index-all.html @@ -2,10 +2,10 @@ - + Index (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/index.html b/spring-cloud-contract-maven-plugin/apidocs/index.html index 3f6091b6a6..9b1538b425 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/index.html +++ b/spring-cloud-contract-maven-plugin/apidocs/index.html @@ -2,7 +2,7 @@ - + Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/ConvertMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/ConvertMojo.html index f0f54ceb71..29b0439a84 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/ConvertMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/ConvertMojo.html @@ -2,10 +2,10 @@ - + ConvertMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.html index eee41e0f67..40dfaeb697 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.html @@ -2,10 +2,10 @@ - + GenerateStubsMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.html index f97b88efb7..07b3f1900f 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.html @@ -2,10 +2,10 @@ - + GenerateTestsMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/HelpMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/HelpMojo.html index e4129c9e6b..548f7bc91c 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/HelpMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/HelpMojo.html @@ -2,10 +2,10 @@ - + HelpMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.html index b3cd72e327..773a7c3aef 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.html @@ -2,10 +2,10 @@ - + PushStubsToScmMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/RunMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/RunMojo.html index a3554f7113..aff6cf47b2 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/RunMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/RunMojo.html @@ -2,10 +2,10 @@ - + RunMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/BaseClassMapping.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/BaseClassMapping.html index 078b918cf1..f552218fd8 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/BaseClassMapping.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/BaseClassMapping.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.BaseClassMapping (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/ConvertMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/ConvertMojo.html index 3f7b937563..5039e524e6 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/ConvertMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/ConvertMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.ConvertMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateStubsMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateStubsMojo.html index 6d836c7ffa..12e58bb6fa 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateStubsMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateStubsMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.GenerateStubsMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateTestsMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateTestsMojo.html index c7df3c7ba6..0d92439687 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateTestsMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/GenerateTestsMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.GenerateTestsMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/HelpMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/HelpMojo.html index 54f14f4ae3..ab6a5719ef 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/HelpMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/HelpMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.HelpMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/PushStubsToScmMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/PushStubsToScmMojo.html index 60088b791d..f1a88fd917 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/PushStubsToScmMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/PushStubsToScmMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.PushStubsToScmMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/RunMojo.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/RunMojo.html index 617e1d63fe..c9db8f9a04 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/RunMojo.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/class-use/RunMojo.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.RunMojo (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-frame.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-frame.html index 4195161f2c..8154decdae 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-frame.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-frame.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-summary.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-summary.html index 5bc517b3b9..2539b586ff 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-summary.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-summary.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-tree.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-tree.html index b316bedc78..9e65154ca7 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-tree.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-tree.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier Class Hierarchy (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-use.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-use.html index 5ab9dcaa51..6d3a1004bc 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-use.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/package-use.html @@ -2,10 +2,10 @@ - + Uses of Package org.springframework.cloud.contract.maven.verifier (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.html index 055b04bb9f..6ab1340886 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.html @@ -2,10 +2,10 @@ - + AetherStubDownloaderFactory (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.html index 7ab2e182be..96e3e3f5ad 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.html @@ -2,10 +2,10 @@ - + LocalStubRunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.html index 5b1b8b6d32..26808c9a95 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.html @@ -2,10 +2,10 @@ - + RemoteStubRunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/AetherStubDownloaderFactory.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/AetherStubDownloaderFactory.html index 6c6fc57813..ee3c77ebd0 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/AetherStubDownloaderFactory.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/AetherStubDownloaderFactory.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.stubrunner.AetherStubDownloaderFactory (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/LocalStubRunner.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/LocalStubRunner.html index e69e2d9542..8d106efe77 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/LocalStubRunner.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/LocalStubRunner.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.stubrunner.LocalStubRunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/RemoteStubRunner.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/RemoteStubRunner.html index f86a39e467..6990f6bf7b 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/RemoteStubRunner.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/class-use/RemoteStubRunner.html @@ -2,10 +2,10 @@ - + Uses of Class org.springframework.cloud.contract.maven.verifier.stubrunner.RemoteStubRunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-frame.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-frame.html index a174369835..5de12006b6 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-frame.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-frame.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier.stubrunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-summary.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-summary.html index 16da52e2df..7faf11dc92 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-summary.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-summary.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier.stubrunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-tree.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-tree.html index f01eee2842..ecf3b6cc91 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-tree.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-tree.html @@ -2,10 +2,10 @@ - + org.springframework.cloud.contract.maven.verifier.stubrunner Class Hierarchy (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-use.html b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-use.html index e1b0440ad3..9a36b6865a 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-use.html +++ b/spring-cloud-contract-maven-plugin/apidocs/org/springframework/cloud/contract/maven/verifier/stubrunner/package-use.html @@ -2,10 +2,10 @@ - + Uses of Package org.springframework.cloud.contract.maven.verifier.stubrunner (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/overview-frame.html b/spring-cloud-contract-maven-plugin/apidocs/overview-frame.html index 41d463bd8c..810a0422b3 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/overview-frame.html +++ b/spring-cloud-contract-maven-plugin/apidocs/overview-frame.html @@ -2,10 +2,10 @@ - + Overview List (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/overview-summary.html b/spring-cloud-contract-maven-plugin/apidocs/overview-summary.html index 75d613244c..6f229483dc 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/overview-summary.html +++ b/spring-cloud-contract-maven-plugin/apidocs/overview-summary.html @@ -2,10 +2,10 @@ - + Overview (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/apidocs/overview-tree.html b/spring-cloud-contract-maven-plugin/apidocs/overview-tree.html index 0de8ed5734..9531392688 100644 --- a/spring-cloud-contract-maven-plugin/apidocs/overview-tree.html +++ b/spring-cloud-contract-maven-plugin/apidocs/overview-tree.html @@ -2,10 +2,10 @@ - + Class Hierarchy (Spring Cloud Contract Maven Plugin 2.2.0.BUILD-SNAPSHOT API) - + diff --git a/spring-cloud-contract-maven-plugin/checkstyle.html b/spring-cloud-contract-maven-plugin/checkstyle.html index 81bfdf1a68..374b06c460 100644 --- a/spring-cloud-contract-maven-plugin/checkstyle.html +++ b/spring-cloud-contract-maven-plugin/checkstyle.html @@ -1,13 +1,13 @@ - + Spring Cloud Contract Maven Plugin – Checkstyle Results @@ -148,7 +148,7 @@