From e990dab424af2bc0cdf037c7a43a7d2497fb78c4 Mon Sep 17 00:00:00 2001 From: buildmaster Date: Tue, 7 Feb 2017 18:43:14 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- spring-cloud-contract.html | 7536 +++++++++++++++++------------------- 1 file changed, 3590 insertions(+), 3946 deletions(-) diff --git a/spring-cloud-contract.html b/spring-cloud-contract.html index fce73fc846..9245f949fd 100644 --- a/spring-cloud-contract.html +++ b/spring-cloud-contract.html @@ -551,273 +551,16 @@ $(addBlockSwitches);
  • Common repo with contracts -
  • -
  • Can I have multiple base classes for tests?
  • - - -
  • Spring Cloud Contract Verifier HTTP - -
  • -
  • Spring Cloud Contract Verifier Messaging - -
  • -
  • Spring Cloud Contract Stub Runner - -
  • -
  • Stub Runner Core - -
  • -
  • Stub Runner JUnit Rule - -
  • -
  • Stub Runner Spring Cloud - -
  • -
  • Stub Runner Boot Application - -
  • -
  • Stub Runner for Messaging - -
  • -
  • Stub Runner Camel - -
  • -
  • Stub Runner Integration - -
  • -
  • Stub Runner Stream - -
  • -
  • Stub Runner Spring AMQP - -
  • -
  • Contract DSL - -
  • -
  • Customization -
  • -
  • Pluggable architecture - -
  • -
  • Links
  • - - +
  • Converters
  • +
  • Stub converters
  • +
  • Example of a custom HTTP Server Stub
  • +
  • Example of a custom Stub Downloader Provider
  • @@ -1887,7 +1630,11 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/1.0.x/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
    +
    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>
    @@ -1942,12 +1689,7 @@ public class LoanApplicationServiceTests {
    -
    @RequestMapping(
    -		value = "/fraudcheck",
    -		method = PUT,
    -		consumes = FRAUD_SERVICE_JSON_VERSION_1,
    -		produces = FRAUD_SERVICE_JSON_VERSION_1)
    -public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
    +
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/1.0.x/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
     return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
     }
    @@ -2539,177 +2281,84 @@ one to one to the contents of the repo.

    -
    <?xml version="1.0" encoding="UTF-8"?>
    +
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/1.0.x/samples/standalone/contracts/com/example/server/pom.xml[indent=0]
    +
    +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:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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>1.4.2.BUILD-SNAPSHOT</version> - <relativePath /> - </parent> - - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <java.version>1.8</java.version> - <spring-cloud-contract.version>1.0.4.BUILD-SNAPSHOT</spring-cloud-contract.version> - <spring-cloud-dependencies.version>Camden.BUILD-SNAPSHOT</spring-cloud-dependencies.version> - <excludeBuildFolders>true</excludeBuildFolders> - </properties> - - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.springframework.cloud</groupId> - <artifactId>spring-cloud-dependencies</artifactId> - <version>${spring-cloud-dependencies.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> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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>
    -

    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:

    +

    </project>

    -
    <?xml version="1.0" encoding="UTF-8"?>
    -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    -		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    -	<modelVersion>4.0.0</modelVersion>
    +
    It's using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:
     
    -	<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>
    +[source,xml,indent=0]
    -

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

    -
    -
    -
    -
    <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
    +

    <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 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">; <id>project</id> <formats> <format>jar</format> @@ -2721,114 +2370,86 @@ Those poms are necessary for the consumer side to run mvn clean install -D <outputDirectory>/</outputDirectory> <useDefaultExcludes>true</useDefaultExcludes> <excludes> - <exclude>**/${project.build.directory}/**</exclude> + <exclude>/${project.build.directory}/</exclude> <exclude>mvnw</exclude> <exclude>mvnw.cmd</exclude> - <exclude>.mvn/**</exclude> - <exclude>src/**</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.

    -
    -
    - - - - - -
    -
    Tip
    -
    -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:

    +</assembly>

    -
    <plugin>
    +
    ===== 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.
    +
    +TIP: You need to have http://maven.apache.org/download.cgi[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:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

    With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded -from http://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.

    -
    -
    - - -
    -

    Can I have multiple base classes for tests?

    -
    -

    Yes! Check out the Different base classes for contracts sections -of either Gradle or Maven plugins.

    -
    -
    - -
    -

    Spring Cloud Contract Verifier HTTP

    -
    -

    Gradle Project

    -
    -
    Prerequisites
    -
    -

    In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin.

    -
    -
    - - - - - -
    -
    Warning
    -
    -If you want to use Spock in your projects you have to add separately -the spock-core and spock-spring modules. Check Spock docs for more information -
    -
    -
    -
    Add gradle plugin with dependencies
    -
    buildscript {
    +
    With this setup the JAR with groupid `com.example.standalone` and artifactid `contracts` will be downloaded
    +from `http://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.
    +
    +==== Can I have multiple base classes for tests?
    +
    +Yes! Check out the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_different_base_classes_for_contracts[Different base classes for contracts] sections
    +of either Gradle or Maven plugins.
    +
    +=== Spring Cloud Contract Verifier HTTP
    +
    +==== Gradle Project
    +
    +===== Prerequisites
    +
    +In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin.
    +
    +WARNING: If you want to use Spock in your projects you have to add separately
    +the `spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock docs for more information]
    +
    +====== Add gradle plugin with dependencies
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    buildscript { repositories { mavenCentral() } @@ -2836,35 +2457,39 @@ the spock-core and spock-spring modules. Check +

    +
    +

    apply plugin: 'groovy' +apply plugin: 'spring-cloud-contract'

    +
    +
    +

    dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}" } -} - -dependencies { +}

    +
    +
    +

    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' -} -

    -
    -
    -
    -
    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:

    +}

    -
    buildscript {
    +
    ====== 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:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    buildscript { repositories { mavenCentral() mavenLocal() @@ -2872,15 +2497,17 @@ dependencies { maven { url "http://repo.spring.io/milestone" } maven { url "http://repo.spring.io/release" } } -} +}

    -
    -
    -
    -
    Add maven plugin with dependencies
    -
    <dependencyManagement>
    +
    ====== Add maven plugin with dependencies
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> @@ -2890,17 +2517,19 @@ dependencies { <scope>import</scope> </dependency> </dependencies> -</dependencyManagement> - -<dependencies> +</dependencyManagement>

    +
    +
    +

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

    +
    +
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <executions> @@ -2912,304 +2541,270 @@ dependencies { </goals> </execution> </executions> -</plugin> +</plugin>

    -
    -
    -
    -
    -
    Add stubs
    -
    -

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

    -
    -
    -

    Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test. +

    +
    +
    Read more: https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[spring-cloud-contract-maven-plugin]
    +
    +====== Add stubs
    +
    +By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory.
    +
    +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 which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
    -So with following structure

    +So with following structure + +[source,groovy,indent=0]
    +
    +
    +
    +

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

    -
    src/test/resources/contracts/myservice/shouldCreateUser.groovy
    -src/test/resources/contracts/myservice/shouldReturnUser.groovy
    +
    Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
    +
    + - `shouldCreateUser()`
    + - `shouldReturnUser()`
    +
    +===== Run plugin
    +
    +Plugin registers itself to be invoked before `check` task. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateContractTests` task.
    +
    +===== Default setup
    +
    +Default Gradle Plugin setup creates the following Gradle part of the build (it's a pseudocode)
    +
    +[source,groovy,indent=0]
    -

    Spring Cloud Contract Verifier will create test class defaultBasePackage.MyService with two methods

    -
    -
    -
      -
    • -

      shouldCreateUser()

      -
    • -
    • -

      shouldReturnUser()

      -
    • -
    -
    -
    -
    -
    -
    Run plugin
    -
    -

    Plugin registers itself to be invoked before check task. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke generateContractTests task.

    -
    -
    -
    -
    Default setup
    -
    -

    Default Gradle Plugin setup creates the following Gradle part of the build (it’s a pseudocode)

    -
    -
    -
    -
    contracts {
    +

    contracts { targetFramework = 'JUNIT' testMode = 'MockMvc' generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/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 + 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
    -}
    -
    -tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
    +}
    +
    +
    +
    +

    tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { baseName = project.name classifier = contracts.stubsSuffix from contractVerifier.stubsOutputDir -} - -project.artifacts { +}

    +
    +
    +

    project.artifacts { archives task -} - -tasks.create(type: Copy, name: 'copyContracts') { +}

    +
    +
    +

    tasks.create(type: Copy, name: 'copyContracts') { from contracts.contractsDslDir into contracts.stubsOutputDir -} - -verifierStubsJar.dependsOn 'copyContracts' - -publishing { +}

    +
    +
    +

    verifierStubsJar.dependsOn 'copyContracts'

    +
    +
    +

    publishing { publications { stubs(MavenPublication) { artifactId project.name artifact verifierStubsJar } } -} -

    -
    -
    -
    -
    Configure plugin
    -
    -

    To change default configuration just add contracts snippet to your Gradle config

    +}

    -
    contracts {
    +
    ===== Configure plugin
    +
    +To change default configuration just add `contracts` snippet to your Gradle config
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

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

    -
    -
    -
    Configuration options
    -
    -
      -
    • -

      testMode - defines mode for acceptance tests. By default MockMvc which is based on Spring’s MockMvc. It can also be changed to JaxRsClient or to Explicit for real HTTP calls.

      -
    • -
    • -

      imports - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []

      -
    • -
    • -

      staticImports - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []

      -
    • -
    • -

      basePackageForTests - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests

      -
    • -
    • -

      baseClassForTests - base class for all generated tests. By default spock.lang.Specification if using Spock tests.

      -
    • -
    • -

      packageWithBaseClasses - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over baseClassForTests.

      -
    • -
    • -

      baseClassMappings - explicitly map contract package to a FQN of a base class. Takes precedence over packageWithBaseClasses and baseClassForTests.

      -
    • -
    • -

      ruleClassForTests - specifies Rule which should be added to generated test classes.

      -
    • -
    • -

      ignoredFiles - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []

      -
    • -
    • -

      contractsDslDir - directory containing contracts written using the GroovyDSL. By default $rootDir/src/test/resources/contracts

      -
    • -
    • -

      generatedTestSourcesDir - test source directory where tests generated from Groovy DSL should be placed. By default $buildDir/generated-test-sources/contractVerifier

      -
    • -
    • -

      stubsOutputDir - dir where the generated WireMock stubs from Groovy DSL should be placed

      -
    • -
    • -

      targetFramework - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework

      -
    • -
    -
    -
    -

    The following properties are used when you want to provide where the JAR with contract lays

    -
    -
    -
      -
    • -

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

      -
    • -
    • -

      contractsPath - if contract deps are downloaded will default to groupid/artifactid where groupid will be slash separated. Otherwise will scan contracts under provided directory

      -
    • -
    • -

      contractsWorkOffline - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo)

      -
    • -
    -
    -
    -
    -
    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 endpoint which should be verified.

    +}

    -
    abstract class BaseMockMvcSpec extends Specification {
    +
    ====== Configuration options
     
    -	def setup() {
    -		RestAssuredMockMvc.standaloneSetup(new PairIdController())
    -	}
    + - **testMode** - defines mode for acceptance tests. By default MockMvc which is based on Spring's MockMvc. It can also be changed to **JaxRsClient** or to **Explicit** for real HTTP calls.
    + - **imports** - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []
    + - **staticImports** - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []
    + - **basePackageForTests** - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests
    + - **baseClassForTests** - base class for all generated tests. By default `spock.lang.Specification` if using Spock tests.
    + - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over **baseClassForTests**.
    + - **baseClassMappings** - explicitly map contract package to a FQN of a base class. Takes precedence over **packageWithBaseClasses** and **baseClassForTests**.
    + - **ruleClassForTests** - specifies Rule which should be added to generated test classes.
    + - **ignoredFiles** - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []
    + - **contractsDslDir** - directory containing contracts written using the GroovyDSL. By default `$rootDir/src/test/resources/contracts`
    + - **generatedTestSourcesDir** - test source directory where tests generated from Groovy DSL should be placed. By default `$buildDir/generated-test-sources/contractVerifier`
    + - **stubsOutputDir** - dir where the generated WireMock stubs from Groovy DSL should be placed
    + - **targetFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
     
    -	void isProperCorrelationId(Integer correlationId) {
    -		assert correlationId == 123456
    -	}
    +The following properties are used when you want to provide where the JAR with contract lays
     
    -	void isEmpty(String value) {
    -		assert value == null
    -	}
    + - **contractDependency** - the Dependency that provides `groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` closure to set it up
    + - **contractsPath** - if contract deps are downloaded will default to `groupid/artifactid` where `groupid` will be slash separated. Otherwise will scan contracts under provided directory
    + - **contractsWorkOffline** - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo)
     
    -}
    +====== 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 endpoint which should be verified. + +[source,groovy,indent=0]
    -

    In case of using Explicit mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of JAXRSCLIENT mode this base class -should also contain protected WebTarget webTarget field, right now the only option to test JAX-RS API is to start a web server.

    +

    abstract class BaseMockMvcSpec extends Specification {

    +
    +
    +
    +
    def setup() {
    +	RestAssuredMockMvc.standaloneSetup(new PairIdController())
    +}
    -
    -
    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:

    +
    +
    +
    void isProperCorrelationId(Integer correlationId) {
    +	assert correlationId == 123456
    +}
    +
    +
    +
    +
    +
    void isEmpty(String value) {
    +	assert value == null
    +}
    -
    -
      -
    • -

      follow a convention by providing the packageWithBaseClasses

      -
    • -
    • -

      provide explicit mapping via baseClassMappings

      -
    • -
    -

    Convention

    -
    -
    -

    The convention is such that if you have a contract under e.g. src/test/resources/contract/foo/bar/baz/ and provide the value of the packageWithBaseClasses property -to com.example.base then we will assume that there is a BarBazBase class under com.example.base package. In other words we take last two parts of package -if they exist and form a class with a Base suffix. Takes precedence over baseClassForTests. Example of usage in the contracts closure:

    +

    }

    -
    packageWithBaseClasses = 'com.example.base'
    +
    In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class
    +should also contain `protected WebTarget webTarget` field, right now the only option to test 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`
    +
    +*Convention*
    +
    +The convention is such that if you have a contract under e.g. `src/test/resources/contract/foo/bar/baz/` and provide the value of the `packageWithBaseClasses` property
    +to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. In other words we take last two parts of package
    +if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage in the `contracts` closure:
    +
    +[source,groovy,indent=0]
    -

    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. -Let’s take a look at the following example:

    +

    packageWithBaseClasses = 'com.example.base'

    -
    baseClassForTests = "com.example.FooBase"
    +
    *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.
    +Let's take a look at the following example:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    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 didn’t succeed (you could also provide -the packageWithBaseClasses as fallback). That way the tests generated from src/test/resources/contract/com/ contracts -will be extending the com.example.ComBase whereas the rest of tests will extend com.example.FooBase.

    -
    -
    -
    -
    -
    Invoking generated tests
    -
    -

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

    + baseClassMapping('./com/.', 'com.example.ComBase') + baseClassMapping('./bar/.':'com.example.BarBase') +}

    -
    ./gradlew generateContractTests test
    +
    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 didn't succeed (you could also provide
    +the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
    +will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
    +
    +===== Invoking generated tests
    +
    +To ensure that provider side is complaint with defined contracts, you need to invoke:
    +
    +[source,bash,indent=0]
    -
    -
    -
    Spring Cloud Contract Verifier on consumer side
    -
    -

    In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. If you don’t want to use Stub Runner then you need to copy contracts stored in -src/test/resources/contracts and generate WireMock json stubs using:

    -
    +
    /gradlew generateContractTests test
    -
    ./gradlew generateClientStubs
    +
    ===== Spring Cloud Contract Verifier on consumer side
    +
    +In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. If you don't want to use Stub Runner then you need to copy contracts stored in
    +`src/test/resources/contracts` and generate WireMock json stubs using:
    +
    +[source,bash,indent=0]
    -
    -

    Note that stubsOutputDir option has to be set for stub generation to work.

    -
    -
    -

    When present, json stubs can be used in consumer automated tests.

    -
    +
    /gradlew generateClientStubs
    -
    @ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
    -class LoanApplicationServiceSpec extends Specification {
    +
    Note that `stubsOutputDir` option has to be set for stub generation to work.
     
    - @ClassRule
    - @Shared
    - WireMockClassRule wireMockRule == new WireMockClassRule()
    +When present, json stubs can be used in consumer automated tests.
     
    - @Autowired
    - LoanApplicationService sut
    -
    - def 'should successfully apply for loan'() {
    +[source,groovy,indent=0]
    +
    +
    +
    +

    @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)
    @@ -3219,24 +2814,24 @@ class LoanApplicationServiceSpec extends Specification {
     	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
     	loanApplication.rejectionReason == null
      }
    -}
    +}
    -
    -

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

    -
    -
    -
    -
    -

    Using in your Maven project

    -
    -
    Add maven plugin
    -
    -

    Add the Spring Cloud Contract BOM

    -
    -
    <dependencyManagement>
    +
    Underneath LoanApplication makes a call to FraudDetection service. This request is handled by WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
    +
    +==== Using in your Maven project
    +
    +===== Add maven plugin
    +
    +Add the Spring Cloud Contract BOM
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> @@ -3246,15 +2841,17 @@ class LoanApplicationServiceSpec extends Specification { <scope>import</scope> </dependency> </dependencies> -</dependencyManagement> -

    -
    -
    -

    Next, the Spring Cloud Contract Verifier Maven plugin

    +</dependencyManagement>

    -
    <plugin>
    +
    Next, the `Spring Cloud Contract Verifier` Maven plugin
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <version>${spring-cloud-contract.version}</version> @@ -3262,24 +2859,25 @@ class LoanApplicationServiceSpec extends Specification { <configuration> <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses> </configuration> -</plugin> -

    -
    -
    -

    You can read more in the Spring Cloud Contract Maven Plugin Docs

    -
    -
    -
    Snapshot versions for Maven
    -
    -

    For Snapshot / Milestone versions you have to add the following section to your pom.xml

    +</plugin>

    -
    <repositories>
    +
    You can read more in the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin Docs]
    +
    +====== Snapshot versions for Maven
    +
    +For Snapshot / Milestone versions you have to add the following section to your `pom.xml`
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url> + <url>https://repo.spring.io/snapshot</url>; <snapshots> <enabled>true</enabled> </snapshots> @@ -3287,7 +2885,7 @@ class LoanApplicationServiceSpec extends Specification { <repository> <id>spring-milestones</id> <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url> + <url>https://repo.spring.io/milestone</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -3295,7 +2893,7 @@ class LoanApplicationServiceSpec extends Specification { <repository> <id>spring-releases</id> <name>Spring Releases</name> - <url>https://repo.spring.io/release</url> + <url>https://repo.spring.io/release</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -3305,7 +2903,7 @@ class LoanApplicationServiceSpec extends Specification { <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url> + <url>https://repo.spring.io/snapshot</url>; <snapshots> <enabled>true</enabled> </snapshots> @@ -3313,7 +2911,7 @@ class LoanApplicationServiceSpec extends Specification { <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url> + <url>https://repo.spring.io/milestone</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -3321,50 +2919,48 @@ class LoanApplicationServiceSpec extends Specification { <pluginRepository> <id>spring-releases</id> <name>Spring Releases</name> - <url>https://repo.spring.io/release</url> + <url>https://repo.spring.io/release</url>; <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> -</pluginRepositories> +</pluginRepositories>

    -
    - - -
    -
    Add stubs
    -
    -

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

    +
    +
    ===== Add stubs
    +
    +By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory.
     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 which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
    -So with following structure

    +So with following structure + +[source,groovy,indent=0]
    +
    +
    +
    +

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

    -
    src/test/resources/contracts/myservice/shouldCreateUser.groovy
    -src/test/resources/contracts/myservice/shouldReturnUser.groovy
    +
    Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
    + - `shouldCreateUser()`
    + - `shouldReturnUser()`
    +
    +===== Run plugin
    +
    +Plugin goal `generateTests` is assigned to be invoked in phase `generate-test-sources`. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateTests` goal.
    +
    +===== Configure plugin
    +
    +To change default configuration just add `configuration` section to plugin definition or `execution` definition.
    +
    +[source,xml,indent=0]
    -

    Spring Cloud Contract Verifier will create test class defaultBasePackage.MyService with two methods - - shouldCreateUser() - - shouldReturnUser()

    -
    -
    -
    -
    Run plugin
    -
    -

    Plugin goal generateTests is assigned to be invoked in phase generate-test-sources. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke generateTests goal.

    -
    -
    -
    -
    Configure plugin
    -
    -

    To change default configuration just add configuration section to plugin definition or execution definition.

    -
    -
    -
    -
    <plugin>
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <executions> @@ -3380,177 +2976,137 @@ src/test/resources/contracts/myservice/shouldReturnUser.groovy

    <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests> <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests> </configuration> -</plugin>
    -
    -
    -
    -
    Important configuration options
    -
    -
      -
    • -

      testMode - defines mode for acceptance tests. By default MockMvc which is based on Spring’s MockMvc. It can also be changed to JaxRsClient or to Explicit for real HTTP calls.

      -
    • -
    • -

      basePackageForTests - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests.

      -
    • -
    • -

      ruleClassForTests - specifies Rule which should be added to generated test classes.

      -
    • -
    • -

      baseClassForTests - base class for generated tests. By default spock.lang.Specification if using Spock tests.

      -
    • -
    • -

      contractsDir - directory containing contracts written using the GroovyDSL. By default /src/test/resources/contracts.

      -
    • -
    • -

      testFramework - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework

      -
    • -
    • -

      packageWithBaseClasses - instead of providing a fixed value for base class you can provide a package where all the base classes lay. -The convention is such that if you have a contract under src/test/resources/contract/foo/bar/baz/ and provide the value of this property -to com.example.base then we will assume that there is a BarBazBase class under com.example.base package. Takes precedence -over baseClassForTests

      -
    • -
    • -

      baseClassMappings - list of base class mappings that where you have to provide contractPackageRegex which is checked -against the package in which the contract lays and baseClassFQN that maps to fully qualified name of the base class for the matched -contract. 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 will extend com.example.base.BaseClass. Takes precedence over packageWithBaseClasses - and baseClassForTests.

      -
    • -
    -
    -
    -

    If you want to download your contract definitions from a Maven repository you can use

    -
    -
    -
      -
    • -

      contractsRepositoryUrl - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones

      -
    • -
    • -

      contractDependency - the contract dependency that contains all the packaged contracts

      -
    • -
    • -

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

      -
    • -
    • -

      contractsWorkOffline - if the dependencies should be downloaded or local Maven only should be reused

      -
    • -
    -
    -
    -

    For complete information take a look at Plugin Documentation

    -
    -
    -
    -
    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 endpoint which should be verified.

    +</plugin>

    -
    package org.mycompany.tests
    +
    ====== Important configuration options
     
    -import org.mycompany.ExampleSpringController
    + - **testMode** - defines mode for acceptance tests. By default `MockMvc` which is based on Spring's MockMvc. It can also be changed to `JaxRsClient` or to `Explicit` for real HTTP calls.
    + - **basePackageForTests** - specifies base package for all generated tests. By default set to `org.springframework.cloud.verifier.tests`.
    + - **ruleClassForTests** - specifies Rule which should be added to generated test classes.
    + - **baseClassForTests** - base class for generated tests. By default `spock.lang.Specification` if using Spock tests.
    + - **contractsDir** - directory containing contracts written using the GroovyDSL. By default `/src/test/resources/contracts`.
    + - **testFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
    + - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay.
    +  The convention is such that if you have a contract under `src/test/resources/contract/foo/bar/baz/` and provide the value of this property
    +  to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. Takes precedence
    +  over **baseClassForTests**
    + - **baseClassMappings** - list of base class mappings that where you have to provide `contractPackageRegex` which is checked
    + against the package in which the contract lays and `baseClassFQN` that maps to fully qualified name of the base class for the matched
    + contract. 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 will extend `com.example.base.BaseClass`. Takes precedence over **packageWithBaseClasses**
    +  and **baseClassForTests**.
    +
    +If you want to download your contract definitions from a Maven repository you can use
    +
    + - **contractsRepositoryUrl** - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones
    + - **contractDependency** - the contract dependency that contains all the packaged contracts
    + - **contractsPath** - path to concrete contracts in the JAR with packaged contracts. Defaults to `groupid/artifactid` where `gropuid` is slash separated.
    + - **contractsWorkOffline** - if the dependencies should be downloaded or local Maven only should be reused
    +
    +For complete information take a look at https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/plugin-info.html[Plugin Documentation]
    +
    +====== 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 endpoint which should be verified.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    package org.mycompany.tests

    +
    +
    +

    import org.mycompany.ExampleSpringController import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc -import spock.lang.Specification - -class MvcSpec extends Specification { +import spock.lang.Specification

    +
    +
    +

    class MvcSpec extends Specification { def setup() { RestAssuredMockMvc.standaloneSetup(new ExampleSpringController()) } -} -

    -
    -
    -

    In case of using Explicit mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of JAXRSCLIENT mode this base class should also contain protected WebTarget webTarget field, right now the only option to test 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

      -
    • -
    -
    -
    -

    Convention

    -
    -
    -

    The convention is such that if you have a contract under e.g. src/test/resources/contract/hello/v1/ and provide the value of the packageWithBaseClasses property -to hello then we will assume that there is a HelloV1Base class under hello package. In other words we take last two parts of package -if they exist and form a class with a Base suffix. Takes precedence over baseClassForTests. Example of usage:

    +}

    -
    <plugin>
    +
    In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class should also contain `protected WebTarget webTarget` field, right now the only option to test 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`
    +
    +*Convention*
    +
    +The convention is such that if you have a contract under e.g. `src/test/resources/contract/hello/v1/` and provide the value of the `packageWithBaseClasses` property
    +to `hello` then we will assume that there is a `HelloV1Base` class under `hello` package. In other words we take last two parts of package
    +if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

    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 baseClassMappings of baseClassMapping that takes a contractPackageRegex to baseClassFQN mapping. -Let’s take a look at the following example:

    +</plugin>

    -
    <plugin>
    +
    *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 `baseClassMappings` of `baseClassMapping` that takes a `contractPackageRegex` to `baseClassFQN` mapping.
    +Let's take a look at the following example:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

    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 didn’t succeed (you could also provide -the packageWithBaseClasses as fallback). That way the tests generated from src/test/resources/contract/com/ contracts -will be extending the com.example.ComBase whereas the rest of tests will extend com.example.FooBase.

    -
    - - -
    -
    Invoking generated tests
    -
    -

    Spring Cloud Contract Maven Plugin generates verification code into directory /generated-test-sources/contractVerifier and attach this directory to testCompile goal.

    -
    -
    -

    For Groovy Spock code use:

    +</plugin>

    -
    <plugin>
    +
    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 didn't succeed (you could also provide
    +the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
    +will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
    +
    +===== Invoking generated tests
    +
    +Spring Cloud Contract Maven Plugin generates verification code into directory `/generated-test-sources/contractVerifier` and attach this directory to `testCompile` goal.
    +
    +For Groovy Spock code use:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.5</version> @@ -3566,43 +3122,42 @@ will be extending the com.example.ComBase whereas the rest of tests <testSource> <directory>${project.basedir}/src/test/groovy</directory> <includes> - <include>**/*.groovy</include> + <include>/.groovy</include> </includes> </testSource> <testSource> <directory>${project.build.directory}/generated-test-sources/contractVerifier</directory> <includes> - <include>**/*.groovy</include> + <include>/.groovy</include> </includes> </testSource> </testSources> </configuration> -</plugin> -

    -
    -
    -

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

    -
    - -
    -
    Spring Cloud Contract Verifier on consumer side
    -
    -

    You can actually use the Spring Cloud Contract Verifier also for the consumer side! -You can use the plugin so that it only converts the contracts and generates the stubs. -To achieve that you need to configure Spring Cloud Contract Verifier plugin in exactly -the same way as in case of provider. You need to copy contracts stored in -src/test/resources/contracts and generate WireMock json stubs using: -mvn generateStubs command. By default generated WireMock mapping is -stored in directory target/mappings. Your project should create from -this generated mappings additional artifact with classifier stubs for -easy deploy to maven repository.

    -
    -
    -

    Sample configuration:

    +</plugin>

    -
    <plugin>
    +
    To ensure that provider side is complaint with defined contracts, you need to invoke `mvn generateTest test`
    +
    +===== Spring Cloud Contract Verifier on consumer side
    +
    +You can actually use the Spring Cloud Contract Verifier also for the consumer side!
    +You can use the plugin so that it only converts the contracts and generates the stubs.
    +To achieve that you need to configure Spring Cloud Contract Verifier plugin in exactly
    +the same way as in case of provider. You need to copy contracts stored in
    +`src/test/resources/contracts` and generate WireMock json stubs using:
    +`mvn generateStubs` command. By default generated WireMock mapping is
    +stored in directory `target/mappings`. Your project should create from
    +this generated mappings additional artifact with classifier `stubs` for
    +easy deploy to maven repository.
    +
    +Sample configuration:
    +
    +[source,xml,indent=0]
    +
    +
    +
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <version>${verifier-plugin.version}</version> @@ -3614,23 +3169,30 @@ easy deploy to maven repository.

    </goals> </execution> </executions> -</plugin>
    -
    -
    -
    -

    When present, json stubs can be used in consumer automated tests.

    +</plugin>

    -
    @RunWith(SpringTestRunner.class)
    +
    When present, json stubs can be used in consumer automated tests.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    @RunWith(SpringTestRunner.class) @SpringBootTest @AutoConfigureStubRunner -public class LoanApplicationServiceTests { - - @Autowired - LoanApplicationService service; - - @Test +public class LoanApplicationServiceTests {

    +
    +
    +
    +
    @Autowired
    +LoanApplicationService service;
    +
    +
    +
    +
    +
      @Test
       public void shouldSuccessfullyApplyForLoan() {
         //given:
      	LoanApplication application =
    @@ -3641,212 +3203,151 @@ public class LoanApplicationServiceTests {
     	assertThat(loanApplication.loanApplicationStatus).isEqualTo(LoanApplicationStatus.LOAN_APPLIED);
     	assertThat(loanApplication.rejectionReason).isNull();
       }
    -}
    +}
    -
    -

    Underneath LoanApplication makes a call to the FraudDetection service. This request is handled by -a WireMock server configured using stubs generated by Spring Cloud Contract Verifier.

    -
    - - -
    -

    Scenarios

    -
    -

    It’s possible to handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to proper naming convention while creating your contracts. The convention requires to include order number followed by the underscore.

    -
    -
    my_contracts_dir\
    +
    Underneath `LoanApplication` makes a call to the `FraudDetection` service. This request is handled by
    +a WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
    +
    +==== Scenarios
    +
    +It's possible to handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to proper naming convention while creating your contracts. The convention requires to include order number followed by the underscore.
    +
    +[source,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

    Such tree will cause Spring Cloud Contract Verifier generating WireMock’s scenario with name scenario1 and three steps:

    -
    -
    -
      -
    • -

      login marked as Started pointing to:

      -
    • -
    • -

      showCart marked as Step1 pointing to:

      -
    • -
    • -

      logout marked as Step2 which will close the scenario.

      -
    • -
    -
    -
    -

    More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html

    -
    -
    -

    Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.

    -
    - -
    -

    Stubs and transitive dependencies

    -
    -

    The Maven and Gradle plugin that we’re created are adding the tasks that create the stubs jar for you. What can be problematic -is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact -even though you have a couple of different jars, all of them share one pom:

    + 3_logout.groovy

    -
    ├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
    +
    Such tree will cause Spring Cloud Contract Verifier generating WireMock's scenario with name `scenario1` and three steps:
    +
    + - login marked as `Started` pointing to:
    + - showCart marked as `Step1` pointing to:
    + - logout marked as `Step2` which will close the scenario.
    +
    +More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html]
    +
    +Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.
    +
    +==== Stubs and transitive dependencies
    +
    +The Maven and Gradle plugin that we're created are adding the tasks that create the stubs jar for you. What can be problematic
    +is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact
    +even though you have a couple of different jars, all of them share one pom:
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

    ├── 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

    -
    -
    -

    If in the github-webhook application we would mark all of our 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 depenencies are optional, they will not get downloaded.

    -
    -
    -

    Create a separate artifactid for stubs

    -
    -
    -

    If you create a separate artifactid then you can set it up in whatever way you wish. For example by having 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.

    -
    - - -
    -

    Spring Cloud Contract Verifier Messaging

    -
    -

    Spring Cloud Contract Verifier allows you to verify your application that uses messaging as means of communication. -All of our integrations are working with Spring but you can also create one yourself and use it.

    -
    -
    -

    Integrations

    -
    -

    You can use one of the four integration configurations:

    -
    -
    -
      -
    • -

      Apache Camel

      -
    • -
    • -

      Spring Integration

      -
    • -
    • -

      Spring Cloud Stream

      -
    • -
    • -

      Spring AMQP

      -
    • -
    -
    -
    -

    Since we’re using Spring Boot then if you have added one of the aforementioned libraries -to the classpath then automatically all the messaging configuration will be set up.

    -
    -
    - - - - - -
    -
    Important
    -
    -Remember to put @AutoConfigureMessageVerifier on the base class of your -generated tests. Otherwise messaging part of Spring Cloud Contract Verifier will not work. -
    -
    -
    -
    -

    Manual Integration Testing

    -
    -

    The main interface used by the tests is the 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 the a test you can inject a ContractVerifierMessageExchange to send and receive messages that follow the contract. -Then add @AutoConfigureMessageVerifier to your test, e.g.

    +├── …​ +└── …​

    -
    @RunWith(SpringTestRunner.class)
    +
    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*
    +
    +If in the `github-webhook` application we would mark all of our 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 depenencies are optional, they will not get downloaded.
    +
    +*Create a separate artifactid for stubs*
    +
    +If you create a separate artifactid then you can set it up in whatever way you wish. For example by having 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.
    +
    +=== Spring Cloud Contract Verifier Messaging
    +
    +Spring Cloud Contract Verifier allows you to verify your application that uses messaging as means of communication.
    +All of our integrations are working with Spring but you can also create one yourself and use it.
    +
    +==== Integrations
    +
    +You can use one of the four integration configurations:
    +
    +- Apache Camel
    +- Spring Integration
    +- Spring Cloud Stream
    +- Spring AMQP
    +
    +Since we're using Spring Boot then if you have added one of the aforementioned libraries
    +to the classpath then automatically all the messaging configuration will be set up.
    +
    +IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your
    +generated tests. Otherwise messaging part of Spring Cloud Contract Verifier will not work.
    +
    +==== Manual Integration Testing
    +
    +The main interface used by the tests is the `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 the a test you can inject a `ContractVerifierMessageExchange` to send and receive messages that follow the contract.
    +Then add `@AutoConfigureMessageVerifier` to your test, e.g.
    +
    +[source,java,indent=0]
    +
    +
    +
    +

    @RunWith(SpringTestRunner.class) @SpringBootTest @AutoConfigureMessageVerifier -public static class MessagingContractTests { - - @Autowired +public static class MessagingContractTests {

    +
    +
    +
    +
      @Autowired
       private MessageVerifier verifier;
       ...
    -}
    +}
    -
    - - - - - -
    -
    Note
    -
    -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 will result in creation of tests on the publisher’s side. By default -JUnit tests will be created, however there is also a possibility to create Spock tests.

    -
    -
    -

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

    -
    -
    -
      -
    • -

      Scenario 1: there is no input message that produces an output one. The output message is triggered by a component -inside the application (e.g. scheduler)

      -
    • -
    • -

      Scenario 2: the input message triggers an output message

      -
    • -
    • -

      Scenario 3: the input message is consumed and there is no output message

      -
    • -
    -
    -
    -
    Scenario 1 (no input message)
    -
    -

    For the given contract:

    -
    -
    def contractDsl = Contract.make {
    +
    NOTE: 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 will result in creation of tests on the publisher's side. By default
    +JUnit tests will be created, however there is also a possibility to create Spock tests.
    +
    +There are 3 main scenarios that we should take into consideration:
    +
    +- Scenario 1: there is no input message that produces an output one. The output message is triggered by a component
    +inside the application (e.g. scheduler)
    +- Scenario 2: the input message triggers an output message
    +- Scenario 3: the input message is consumed and there is no output message
    +
    +===== Scenario 1 (no input message)
    +
    +For the given contract:
    +
    +[source,groovy]
    +
    +
    +
    +

    def contractDsl = Contract.make { label 'some_label' input { triggeredBy('bookReturnedTriggered()') @@ -3858,57 +3359,71 @@ inside the application (e.g. scheduler)

    header('BOOK-NAME', 'foo') } } -}
    -
    -
    -
    -

    The following JUnit test will be created:

    +}

    -
    '''
    - // when:
    -  bookReturnedTriggered();
    +
    The following JUnit test will be created:
     
    - // then:
    +[source,groovy]
    +
    +
    +
    +
    +
    +
    // when:
    + bookReturnedTriggered();
    +
    +
    +
    +
    +
     // then:
       ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
       assertThat(response).isNotNull();
       assertThat(response.getHeader("BOOK-NAME")).isEqualTo("foo");
      // and:
       DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
       assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
    -'''
    +'''
    -
    -

    And the following Spock test would be created:

    -
    -
    '''
    - when:
    -  bookReturnedTriggered()
    +
    And the following Spock test would be created:
     
    - then:
    -  ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
    -  assert response != null
    -  response.getHeader('BOOK-NAME')  == 'foo'
    - and:
    -  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
    -  assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
    -
    -'''
    +[source,groovy]
    +
    +
    +
    +
    when:
    + bookReturnedTriggered()
    -
    -
    Scenario 2 (output triggered by input)
    -
    -

    For the given contract:

    +
    +
    +
    then:
    + ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
    + assert response != null
    + response.getHeader('BOOK-NAME')  == 'foo'
    +and:
    + DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
    + assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
    +
    +
    +
    -
    def contractDsl = Contract.make {
    +
    ===== Scenario 2 (output triggered by input)
    +
    +For the given contract:
    +
    +[source,groovy]
    +
    +
    +
    +

    def contractDsl = Contract.make { label 'some_label' input { messageFrom('jms:input') @@ -3928,68 +3443,80 @@ inside the application (e.g. scheduler)

    header('BOOK-NAME', 'foo') } } -}
    -
    -
    -
    -

    The following JUnit test will be created:

    +}

    -
    '''
    -// given:
    - ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +
    The following JUnit test will be created:
    +
    +[source,groovy]
    +
    +
    +
    +
    +
    +
     ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
       "{\\"bookName\\":\\"foo\\"}"
     , headers()
    -  .header("sample", "header"));
    -
    -// when:
    - contractVerifierMessaging.send(inputMessage, "jms:input");
    -
    -// then:
    - ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
    +  .header("sample", "header"));
    +
    +
    +
    +
    +
    contractVerifierMessaging.send(inputMessage, "jms:input");
    +
    +
    +
    +
    +
     ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
      assertThat(response).isNotNull();
      assertThat(response.getHeader("BOOK-NAME")).isEqualTo("foo");
     // and:
      DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
      assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
    -'''
    +'''
    -
    -

    And the following Spock test would be created:

    -
    -
    """\
    +
    And the following Spock test would be created:
    +
    +[source,groovy]
    +
    +
    +
    +

    """\ given: ContractVerifierMessage inputMessage = contractVerifierMessaging.create( '''{"bookName":"foo"}''', ['sample': 'header'] - ) - -when: - contractVerifierMessaging.send(inputMessage, 'jms:input') - -then: + )

    +
    +
    +

    when: + contractVerifierMessaging.send(inputMessage, 'jms:input')

    +
    +
    +

    then: ContractVerifierMessage response = contractVerifierMessaging.receive('jms:output') assert response !- null response.getHeader('BOOK-NAME') == 'foo' and: DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload)) assertThatJson(parsedJson).field("bookName").isEqualTo("foo") -""" -

    -
    -
    -
    -
    Scenario 3 (no output message)
    -
    -

    For the given contract:

    +"""

    -
    def contractDsl = Contract.make {
    +
    ===== Scenario 3 (no output message)
    +
    +For the given contract:
    +
    +[source,groovy]
    +
    +
    +
    +

    def contractDsl = Contract.make { label 'some_label' input { messageFrom('jms:delete') @@ -4001,71 +3528,83 @@ and: } assertThat('bookWasDeleted()') } -} -

    -
    -
    -

    The following JUnit test will be created:

    +}

    -
    '''
    -// given:
    - ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +
    The following JUnit test will be created:
    +
    +[source,groovy]
    +
    +
    +
    +
    +
    +
     ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
     	"{\\"bookName\\":\\"foo\\"}"
     , headers()
    -	.header("sample", "header"));
    -
    -// when:
    - contractVerifierMessaging.send(inputMessage, "jms:delete");
    -
    -// then:
    - bookWasDeleted();
    -'''
    + .header("sample", "header"));
    -
    -

    And the following Spock test would be created:

    +
    +
    +
    contractVerifierMessaging.send(inputMessage, "jms:delete");
    +
    +
    +
    +
    +
     bookWasDeleted();
    +'''
    +
    -
    '''
    -given:
    +
    And the following Spock test would be created:
    +
    +[source,groovy]
    +
    +
    +
    +
    +

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

    +
    +
    +

    when: + contractVerifierMessaging.send(inputMessage, 'jms:delete')

    +
    +
    +

    then: noExceptionThrown() bookWasDeleted() -''' +'''

    -
    -
    - -
    -

    Consumer Stub Side generation

    -
    -

    Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it’s parsed on the consumer side -and proper stubbed routes are created.

    -
    -
    -

    For more information please consult the Stub Runner Messaging sections.

    -
    -
    -
    Maven
    +
    -
    <dependencies>
    +
    ==== Consumer Stub Side generation
    +
    +Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it's parsed on the consumer side
    +and proper stubbed routes are created.
    +
    +For more information please consult the Stub Runner Messaging sections.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.Maven
    +
    +
    +
    +

    <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-rabbit</artifactId> - </dependency> - - <dependency> + </dependency>

    +
    +
    +
    +
    	<dependency>
     		<groupId>org.springframework.cloud</groupId>
     		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
     		<scope>test</scope>
    @@ -4075,9 +3614,11 @@ and proper stubbed routes are created.

    <artifactId>spring-cloud-stream-test-support</artifactId> <scope>test</scope> </dependency> -</dependencies> - -<dependencyManagement> +</dependencies>
    +
    +
    +
    +

    <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> @@ -4087,60 +3628,56 @@ and proper stubbed routes are created.

    <scope>import</scope> </dependency> </dependencies> -</dependencyManagement>
    +</dependencyManagement>

    -
    -
    -
    Gradle
    +
    -
    ext {
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.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 { +}

    +
    +
    +

    publishing { publications { stubs(MavenPublication) { artifactId "${project.name}-stubs" artifact verifierStubsJar } } -} +}

    -
    -
    - -
    -

    Spring Cloud Contract Stub Runner

    -
    -

    One of the issues that you could have encountered while using Spring Cloud Contract Verifier was to pass the generated WireMock JSON stubs from the server side to the client side (or various clients). - The same takes place in terms of client side generation for messaging.

    -
    -
    -

    Copying the JSON files / setting the client side for messaging manually is out of the question.

    -
    -
    -

    That’s why we’ll introduce Spring Cloud Contract Stub Runner that can download and run the stubs -automatically for you.

    -
    -
    -

    Snapshot versions

    -
    -

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

    -
    -
    -
    Maven
    +
    -
    <repositories>
    +
    === Spring Cloud Contract Stub Runner
    +
    +One of the issues that you could have encountered while using Spring Cloud Contract Verifier was to pass the generated WireMock JSON stubs from the server side to the client side (or various clients).
    + The same takes place in terms of client side generation for messaging.
    +
    +Copying the JSON files / setting the client side for messaging manually is out of the question.
    +
    +That's why we'll introduce Spring Cloud Contract Stub Runner that can download and run the stubs
    +automatically for you.
    +
    +==== Snapshot versions
    +
    +Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.Maven
    +
    +
    +
    +

    <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url> + <url>https://repo.spring.io/snapshot</url>; <snapshots> <enabled>true</enabled> </snapshots> @@ -4148,7 +3685,7 @@ automatically for you.

    <repository> <id>spring-milestones</id> <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url> + <url>https://repo.spring.io/milestone</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -4156,7 +3693,7 @@ automatically for you.

    <repository> <id>spring-releases</id> <name>Spring Releases</name> - <url>https://repo.spring.io/release</url> + <url>https://repo.spring.io/release</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -4166,7 +3703,7 @@ automatically for you.

    <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url> + <url>https://repo.spring.io/snapshot</url>; <snapshots> <enabled>true</enabled> </snapshots> @@ -4174,7 +3711,7 @@ automatically for you.

    <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url> + <url>https://repo.spring.io/milestone</url>; <snapshots> <enabled>false</enabled> </snapshots> @@ -4182,52 +3719,48 @@ automatically for you.

    <pluginRepository> <id>spring-releases</id> <name>Spring Releases</name> - <url>https://repo.spring.io/release</url> + <url>https://repo.spring.io/release</url>; <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> -</pluginRepositories>
    +</pluginRepositories>

    -
    -
    -
    Gradle
    +
    -
    buildscript {
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    buildscript { repositories { mavenCentral() mavenLocal() maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } maven { url "http://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.

    -
    -
    - - - - - -
    -
    Tip
    -
    -For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to. -
    -
    -
    -
    Maven
    +
    -
    <!-- First disable the default jar setup in the properties section-->
    -Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0]
    +
    ==== Publishing stubs as JARs
     
    -<!-- Next add the assembly plugin to your build -->
    +The easiest approach would be to centralize the way stubs are kept. For example you can keep them as JARs in a Maven repository.
    +
    +TIP: For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.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 -→ <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> @@ -4245,13 +3778,14 @@ Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubus </configuration> </execution> </executions> -</plugin> - -<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml --> +</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 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">; <id>stubs</id> <formats> <format>jar</format> @@ -4262,102 +3796,86 @@ Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubus <directory>src/main/java</directory> <outputDirectory>/</outputDirectory> <includes> - <include>**com/example/model/*.*</include> + <include>com/example/model/.</include> </includes> </fileSet> <fileSet> <directory>${project.build.directory}/classes</directory> <outputDirectory>/</outputDirectory> <includes> - <include>**com/example/model/*.*</include> + <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> + <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> + <include>/.groovy</include> </includes> </fileSet> </fileSets> -</assembly> +</assembly>

    -
    -
    -
    Gradle
    +
    -
    ext {
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.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 { +}

    +
    +
    +

    publishing { publications { stubs(MavenPublication) { artifactId "${project.name}-stubs" artifact verifierStubsJar } } -} -

    -
    -
    -
    -

    Modules

    - -
    -
    -
    -

    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, start WireMock servers for them and feed them with proper stub definitions. -For messaging, special stub routes are defined.

    -
    -
    -

    Running stubs

    -
    -
    Limitations
    -
    - - - - - -
    -
    Important
    -
    -There might be a problem with StubRunner shutting down ports between tests. You might - have a situation in which you get port conflicts. As long as you use the same context across tests - everything works fine. But when the context are different (e.g. different stubs or different profiles) - then you have to either use @DirtiesContext to shut down the stub servers, or else run them on - different ports per test. -
    -
    -
    -
    -
    Running using main app
    -
    -

    You can set the following options to the main class:

    +}

    -
    -c, --classifier                Suffix for the jar containing stubs (e.
    +
    ==== Modules
    +
    +=== Stub Runner Core
    +
    +Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of
    +http://martinfowler.com/articles/consumerDrivenContracts.html[Consumer Driven Contracts].
    +
    +Stub Runner allows you to automatically download the stubs of the provided dependencies, start WireMock servers for them and feed them with proper stub definitions.
    +For messaging, special stub routes are defined.
    +
    +==== Running stubs
    +
    +===== Limitations
    +
    +IMPORTANT: There might be a problem with StubRunner shutting down ports between tests. You might
    + have a situation in which you get port conflicts. As long as you use the same context across tests
    + everything works fine. But when the context are different (e.g. different stubs or different profiles)
    + then you have to either use `@DirtiesContext` to shut down the stub servers, or else run them on
    + different ports per test.
    +
    +===== Running using main app
    +
    +You can set the following options to the main class:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    -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' @@ -4385,21 +3903,21 @@ There might be a problem with StubRunner shutting down ports between tests. You -u, --username Username to user when connecting to repository --wo, --workOffline Switch to work offline. Defaults to - 'false' -

    -
    -
    -
    -
    HTTP Stubs
    -
    -

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

    -
    -
    -

    Example:

    + 'false'

    -
    {
    +
    ===== HTTP Stubs
    +
    +Stubs are defined in JSON documents, whose syntax is defined in http://wiremock.org/stubbing.html[WireMock documentation]
    +
    +Example:
    +
    +[source,javascript,indent=0]
    +
    +
    +
    +

    { "request": { "method": "GET", "url": "/ping" @@ -4411,77 +3929,64 @@ There might be a problem with StubRunner shutting down ports between tests. You "Content-Type": "text/plain" } } -} -

    -
    -
    -
    -
    Viewing registered mappings
    -
    -

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

    -
    -
    -
    -
    Messaging Stubs
    -
    -

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

    -
    -
    - - -
    -

    Stub Runner JUnit Rule

    -
    -

    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()
    +
    ===== Viewing registered mappings
    +
    +Every stubbed collaborator exposes list of defined mappings under `__/admin/` endpoint.
    +
    +===== Messaging Stubs
    +
    +Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.
    +
    +=== Stub Runner JUnit Rule
    +
    +Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:
    +
    +[source,java,indent=0]
    +
    +
    +
    +
    +
    @ClassRule public static StubRunnerRule rule = new StubRunnerRule()
     		.repoRoot(repoRoot())
     		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
    -		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
    + .downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
    -
    -

    After that rule gets 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

      -
    • -
    -
    -
    -

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

    -
    -
    -

    Since the StubRunnerRule implements the StubFinder it allows you to find the started stubs:

    -
    -
    package org.springframework.cloud.contract.stubrunner;
    +
    After that rule gets executed Stub Runner connects to your Maven repository and for the given list of dependencies tries to:
     
    -import java.net.URL;
    +- 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
    +
    +Stub Runner uses https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies.
    +Check their https://wiki.eclipse.org/Aether[docs] for more information.
    +
    +Since the `StubRunnerRule` implements the `StubFinder` it allows you to find the started stubs:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    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; - -public interface StubFinder extends StubTrigger { +import java.util.Map;

    +
    +
    +

    import org.springframework.cloud.contract.spec.Contract;

    +
    +
    +

    public interface StubFinder extends StubTrigger { /** * For the given groupId and artifactId tries to find the matching * URL of the running stub. @@ -4489,40 +3994,55 @@ public interface StubFinder extends StubTrigger { * @param groupId - might be null. In that case a search only via artifactId takes place * @return URL of a running stub or throws exception if not found */ - 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 - */ - URL findStubUrl(String ivyNotation) throws StubNotFoundException; - - /** - * Returns all running stubs - */ - RunningStubs findAllRunningStubs(); - - /** + 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
    + */
    +URL findStubUrl(String ivyNotation) throws StubNotFoundException;
    +
    +
    +
    +
    +
    /**
    + * Returns all running stubs
    + */
    +RunningStubs findAllRunningStubs();
    +
    +
    +
    +
    +
    	/**
     	 * Returns the list of Contracts
     	 */
     	Map<StubConfiguration, Collection<Contract>> getContracts();
    -}
    +}
    -
    -

    Example of usage in Spock tests:

    -
    -
    @ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
    +
    Example of usage in Spock tests:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +
    +
    @ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
     		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
     		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
    -		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
    -
    -def 'should start WireMock servers'() {
    +		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
    +
    +
    +
    +
    +
    def 'should start WireMock servers'() {
     	expect: 'WireMocks are running'
     		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
     		rule.findStubUrl('loanIssuance') != null
    @@ -4535,15 +4055,19 @@ def 'should start WireMock servers'() {
     	and: 'Stubs were registered'
     		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
     		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
    -}
    +}
    -
    -

    Example of usage in JUnit tests:

    -
    -
    @Test
    +
    Example of usage in JUnit tests:
    +
    +[source,java,indent=0]
    +
    +
    +
    +
    +
    @Test
     public void should_start_wiremock_servers() throws Exception {
     	// expect: 'WireMocks are running'
     		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")).isNotNull();
    @@ -4557,124 +4081,149 @@ public void should_start_wiremock_servers() throws Exception {
     	// and: 'Stubs were registered'
     		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name")).isEqualTo("loanIssuance");
     		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer");
    -}
    +}
    -
    -

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

    -
    -
    -

    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 you can add a stub to download and then pass the port for the last downloaded stub.

    -
    -
    @ClassRule public static StubRunnerRule rule = new StubRunnerRule()
    +
    Check the *Common properties for JUnit and Spring* for more information on how to apply global configuration of Stub Runner.
    +
    +==== 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` you can add a stub to download and then pass the port for the last downloaded stub.
    +
    +[source,java,indent=0]
    +
    +
    +
    +
    +
    @ClassRule public static StubRunnerRule rule = new StubRunnerRule()
     		.repoRoot(repoRoot())
     		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
     		.withPort(12345)
    -		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
    + .downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
    -
    -

    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());
    +
    You can see that for this example the following test is valid:
    +
    +[source,java,indent=0]
    +
    +
    +
    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)
    +
    ==== 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:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    @ContextConfiguration(classes = Config, loader = SpringBootContextLoader) @SpringBootTest(properties = [" stubrunner.cloud.enabled=false", "stubrunner.camel.enabled=false"]) @AutoConfigureStubRunner @DirtiesContext @ActiveProfiles("test") -class StubRunnerConfigurationSpec extends Specification { - - @Autowired StubFinder stubFinder - @Autowired Environment environment - - @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' - } - - 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) - } - - @Configuration +class StubRunnerConfigurationSpec extends Specification {

    +
    +
    +
    +
    @Autowired StubFinder stubFinder
    +@Autowired Environment environment
    +
    +
    +
    +
    +
    @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'
    +}
    +
    +
    +
    +
    +
    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)
    +}
    +
    +
    +
    +
    +
    	@Configuration
     	@EnableAutoConfiguration
     	static class Config {}
    -}
    +}
    -
    -

    for the following configuration file:

    -
    -
    stubrunner:
    +
    for the following configuration file:
    +
    +[source,yml,indent=0]
    +
    +
    +
    +

    stubrunner: repositoryRoot: classpath:m2repo/repository/ ids: - org.springframework.cloud.contract.verifier.stubs:loanIssuance @@ -4683,92 +4232,81 @@ class StubRunnerConfigurationSpec extends Specification { cloud: enabled: false camel: - enabled: false - -spring.cloud: - consul.enabled: false - service-registry.enabled: false -

    + enabled: false

    -

    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.

    +

    spring.cloud: + consul.enabled: false + service-registry.enabled: false

    -
    @AutoConfigureStubRunner(
    +
    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.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    @AutoConfigureStubRunner( ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance", "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer", "org.springframework.cloud.contract.verifier.stubs:bootService"], - 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.bar.port

      -
    • -
    -
    -
    -

    Which you can reference in your code.

    -
    -
    -
    -
    -

    Stub Runner Spring Cloud

    -
    -

    Stub Runner can integrate with Spring Cloud.

    -
    -
    -

    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

    + repositoryRoot = "classpath:m2repo/repository/")

    -
    def 'should make service discovery work'() {
    +
    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.bar.port`
    +
    +Which you can reference in your code.
    +
    +
    +=== Stub Runner Spring Cloud
    +
    +Stub Runner can integrate with Spring Cloud.
    +
    +==== 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
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +
    +
    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

    -
    -
    spring.cloud:
    +
    for the following configuration file
    +
    +[source,yml,indent=0]
    +
    +
    +
    +

    spring.cloud: zookeeper.enabled: false consul.enabled: false eureka.client.enabled: false @@ -4776,520 +4314,452 @@ stubrunner: camel.enabled: false idsToServiceIds: ivyNotation: someValueInsideYourCode - fraudDetectionServer: someNameThatShouldMapFraudDetectionServer + fraudDetectionServer: someNameThatShouldMapFraudDetectionServer

    -
    -
    -
    -

    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

    -
    -
    - - - - - -
    -
    Tip
    -
    -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 +
    +
    +
    ==== 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`
    +
    +TIP: 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.
    -
    + +=== Stub Runner Boot Application + +Spring Cloud Contract Verifier 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 read + more about this in the http://toomuchcoding.com/blog/2015/09/27/microservice-deployment/["Microservice Deployment" article at Too Much Coding blog.] + +==== How to use it? + +Just add the + +[source,groovy,indent=0]
    - -
    -

    Stub Runner Boot Application

    -
    -

    Spring Cloud Contract Verifier 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 read - more about this in the "Microservice Deployment" article at Too Much Coding blog.

    -
    -
    -

    How to use it?

    -
    -

    Just add the

    +

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

    -
    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.
    +
    +==== 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
    +
    +[source,groovy,indent=0]
    -

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

    -
    -
    -

    For the properties check the Stub Runner Spring section.

    -
    -
    -
    -

    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)
    +

    @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 - response.body.as(Integer) > 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=") - } - -}

    +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
    +		response.body.as(Integer) > 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
    +
    ==== 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.
    +
    +[source,java,indent=0]
    +
    +
    +
    +

    @SpringBootApplication @EnableStubRunnerServer @EnableEurekaClient @AutoConfigureStubRunner -public class StubRunnerBootEurekaExample { - - public static void main(String[] args) { - SpringApplication.run(StubRunnerBootEurekaExample.class, args); - } - -} +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=http://repo.spring.io/snapshots (1)
    +
    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
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

    -Dstubrunner.repositoryRoot=http://repo.spring.io/snapshots (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 +-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 artifactId to serviceId mapping +(4) - we provide a list of artifactId to serviceId mapping

    -
    -
    -

    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 +

    +
    +
    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.

    +the Stub Runner Boot. + +==== Common properties for JUnit and Spring + +Some of the properties that are repetitive can be set using system properties or configuration properties (for Spring). Here are their names with their default values: + +[frame="topbot",options="header"] +|====================== +| Property name | Default value | Description +|stubrunner.minPort|10000| Minimal value of a port for a started WireMock with stubs +|stubrunner.maxPort|15000| Minimal value of a port for a started WireMock with stubs +|stubrunner.repositoryRoot|| Maven repo url. If blank then will call the local maven repo +|stubrunner.classifier|stubs| Default classifier for the stub artifacts +|stubrunner.workOffline|false| If true then will not contact any remote repositories to download 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 +|====================== + +===== Stub runner stubs ids + +You can provide the stubs to download via the `stubrunner.ids` system property. They follow the following pattern: + +[source,java,indent=0]
    -
    -

    Common properties for JUnit and Spring

    -

    Some of the properties that are repetitive can be set using system properties or configuration properties (for Spring). Here are their names with their default values:

    -
    - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Property nameDefault valueDescription

    stubrunner.minPort

    10000

    Minimal value of a port for a started WireMock with stubs

    stubrunner.maxPort

    15000

    Minimal value of a port for a started WireMock with stubs

    stubrunner.repositoryRoot

    Maven repo url. If blank then will call the local maven repo

    stubrunner.classifier

    stubs

    Default classifier for the stub artifacts

    stubrunner.workOffline

    false

    If true then will not contact any remote repositories to download 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

    -
    -
    Stub runner stubs ids
    -
    -

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

    +

    groupId:artifactId:version:classifier:port

    -
    groupId:artifactId:version:classifier:port
    +
    `version`, `classifier` and `port` are optional.
    +
    +* If you don't provide the `port` then a random one will be picked
    +* If you don't provide the `classifier` then the default one will be taken. (NOTE that you can pass an empty classifier like this `groupId:artifactId:version:`)
    +* If you don't provide the `version` then the `+` will be passed and the latest one will be downloaded
    +
    +Where `port` means the port of the WireMock server.
    +
    +IMPORTANT: Starting from version 1.0.4 as a version you can provide a range of versions that you would like
    +the Stub Runner to take into consideration. You can read more about the https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning ranges here].
    +
    +Taken from http://download.eclipse.org/aether/aether-core/0.9.0/apidocs/org/eclipse/aether/util/version/GenericVersionScheme.html[Aether Docs]:
    +
    +> This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments. The characters '-', '_', and '.' as well as the mere
    +> transitions from digit to letter and vice versa delimit the version segments. Delimiters are treated as equivalent.
    +>
    +> Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and case-insensitively. However, the following qualifier strings are
    +> recognized and treated specially: "alpha" = "a" < "beta" = "b" < "milestone" = "m" < "cr" = "rc" < "snapshot" < "final" = "ga" < "sp". All of those well-known qualifiers
    +> are considered smaller/older than other strings. An empty segment/string is equivalent to 0.
    +>
    +> In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to denote the smallest/greatest version having a given prefix.
    +> For example, "1.2.min" denotes the smallest version in the 1.2 line, "1.2.max" denotes the greatest version in the 1.2 line. A version range of the form "[M.N.*]" is short for "[M.N.min, M.N.max]".
    +>
    +> Numbers and strings are considered incomparable against each other. Where version segments of different kind would collide, comparison will instead assume that the previous
    +> segments are padded with trailing 0 or "ga" segments, respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1".
    +
    +=== Stub Runner for Messaging
    +
    +Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box
    +
    +- Spring Integration
    +- Spring Cloud Stream
    +- Apache Camel
    +- Spring AMQP
    +
    +It also provides points of entry to integrate with any other solution on the market.
    +
    +==== Stub triggering
    +
    +To trigger a message it's enough to use the `StubTrigger` interface:
    +
    +[source,groovy]
    -

    version, classifier and port are optional.

    -
    -
    -
      -
    • -

      If you don’t provide the port then a random one will be picked

      -
    • -
    • -

      If you don’t provide the classifier then the default one will be taken. (NOTE that you can pass an empty classifier like this groupId:artifactId:version:)

      -
    • -
    • -

      If you don’t provide the version then the + will be passed and the latest one will be downloaded

      -
    • -
    +

    package org.springframework.cloud.contract.stubrunner;

    -

    Where port means the port of the WireMock server.

    -
    -
    - - - - - -
    -
    Important
    -
    -Starting from version 1.0.4 as a version 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. -
    +

    import java.util.Collection; +import java.util.Map;

    -

    Taken from Aether Docs:

    +

    public interface StubTrigger {

    -
    -
    -
    -

    This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments. The characters '-', '_', and '.' as well as the mere -transitions from digit to letter and vice versa delimit the version segments. Delimiters are treated as equivalent.

    -
    -
    -

    Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and case-insensitively. However, the following qualifier strings are -recognized and treated specially: "alpha" = "a" < "beta" = "b" < "milestone" = "m" < "cr" = "rc" < "snapshot" < "final" = "ga" < "sp". All of those well-known qualifiers -are considered smaller/older than other strings. An empty segment/string is equivalent to 0.

    -
    -
    -

    In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to denote the smallest/greatest version having a given prefix. -For example, "1.2.min" denotes the smallest version in the 1.2 line, "1.2.max" denotes the greatest version in the 1.2 line. A version range of the form "[M.N.*]" is short for "[M.N.min, M.N.max]".

    -
    -
    -

    Numbers and strings are considered incomparable against each other. Where version segments of different kind would collide, comparison will instead assume that the previous -segments are padded with trailing 0 or "ga" segments, respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1".

    -
    -
    -
    -
    -
    -
    -
    -

    Stub Runner for Messaging

    -
    -

    Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box

    -
    -
    -
      -
    • -

      Spring Integration

      -
    • -
    • -

      Spring Cloud Stream

      -
    • -
    • -

      Apache Camel

      -
    • -
    • -

      Spring AMQP

      -
    • -
    -
    -
    -

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

    -
    -
    -

    Stub triggering

    -
    -

    To trigger a message it’s enough to use the StubTrigger interface:

    -
    -
    +
    -
    package org.springframework.cloud.contract.stubrunner;
    -
    -import java.util.Collection;
    -import java.util.Map;
    -
    -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.
    -	 *
    -	 * @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.
    -	 *
    -	 * @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();
    -
    -	/**
    +
    /**
    + * 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.
    + *
    + * @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.
    + *
    + * @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();
    +
    +
    +
    +
    +
    	/**
     	 * Returns a mapping of ivy notation of a dependency to all the labels it has.
     	 *
     	 * Feature related to messaging.
     	 */
     	Map<String, Collection<String>> labels();
    -}
    +} +
    +
    +
    +
    +
    For convenience the `StubFinder` interface extends `StubTrigger` so it's enough to use only one in your tests.
    +
    +`StubTrigger` gives you the following options to trigger a message:
    +
    +===== Trigger by label
    +
    +[source,groovy]
    -

    For convenience the StubFinder interface extends StubTrigger so it’s enough to use only one in your tests.

    +

    stubFinder.trigger('return_book_1')

    +
    +
    +
    +
    ====== Trigger by group and artifact ids
    +
    +[source,groovy]
    +
    -

    StubTrigger gives you the following options to trigger a message:

    +

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

    -
    -
    Trigger by label
    -
    stubFinder.trigger('return_book_1')
    +
    ====== Trigger by artifact ids
    +
    +[source,groovy]
    -
    -
    Trigger by group and artifact ids
    -
    -
    -
    stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:camelService', 'return_book_1')
    -
    -
    -
    -
    -
    Trigger by artifact ids
    -
    -
    -
    stubFinder.trigger('camelService', '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. +

    stubFinder.trigger('camelService', 'return_book_1')

    +
    +
    +
    +
    ===== Trigger all messages
    +
    +[source,groovy]
    +
    +
    +
    +

    stubFinder.trigger()

    +
    +
    +
    +
    :input_name: jms:input
    +:output_name: jms:output
    +
    +=== 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.

    +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 `@AutoConfigureMessageVerifier`. + +==== Examples + +===== Stubs structure + +Let us assume that we have the following Maven repository with a deployed stubs for the +`camelService` application. + +[source,bash,indent=0]
    +
    -
    -

    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 @AutoConfigureMessageVerifier.

    -
    -
    -
    -

    Examples

    -
    -
    Stubs structure
    -
    -

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

    -
    -
    -
    -
    └── .m2
    +

    └── .m2 └── repository └── io └── codearte @@ -5300,30 +4770,34 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier

    -
    -
    -
    -

    And the stubs contain the following structure:

    + └── maven-metadata-local.xml

    -
    ├── META-INF
    +
    And the stubs contain the following structure:
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

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

    + └── mappings

    -
    Contract.make {
    +
    Let's consider the following contracts (let' number it with *1*):
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_1' input { triggeredBy('bookReturnedTriggered()') @@ -5335,15 +4809,17 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and number 2

    +}

    -
    Contract.make {
    +
    and number *2*
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_2' input { messageFrom('jms:input') @@ -5363,106 +4839,116 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -
    -
    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')
    +
    ===== 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
    +
    +[source,groovy]
    -

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

    +

    stubFinder.trigger('return_book_1')

    -
    Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)
    +
    Next we'll want to listen to the output of the message sent to `{output_name}`
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

    Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)

    -
    receivedMessage != null
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    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.

    +receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

    -
    camelContext.createProducerTemplate().sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])
    +
    ===== Scenario 2 (output triggered by input)
    +
    +Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
    +
    +[source,groovy]
    -

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

    +

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

    -
    Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)
    +
    Next we'll want to listen to the output of the message sent to `{output_name}`
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

    Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)

    -
    receivedMessage != null
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    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.

    +receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

    -
    camelContext.createProducerTemplate().sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])
    +
    ===== Scenario 3 (input with no output)
    +
    +Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
    +
    +[source,groovy]
    -
    -
    -
    -
    -

    Stub Runner Integration

    -

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Integration. +

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

    +
    +
    +
    +
    :input_name: input
    +:output_name: output
    +
    +=== 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 will automatically download the stubs and register the required
    -routes.

    +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 `@AutoConfigureMessageVerifier`. + +==== Examples + +===== Stubs structure + +Let us assume that we have the following Maven repository with a deployed stubs for the +`integrationService` application. + +[source,bash,indent=0]
    +
    -
    -

    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 @AutoConfigureMessageVerifier.

    -
    -
    -
    -

    Examples

    -
    -
    Stubs structure
    -
    -

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

    -
    -
    -
    -
    └── .m2
    +

    └── .m2 └── repository └── io └── codearte @@ -5473,30 +4959,34 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier

    -
    -
    -
    -

    And the stubs contain the following structure:

    + └── maven-metadata-local.xml

    -
    ├── META-INF
    +
    And the stubs contain the following structure:
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

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

    + └── mappings

    -
    Contract.make {
    +
    Let's consider the following contracts (let' number it with *1*):
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_1' input { triggeredBy('bookReturnedTriggered()') @@ -5508,15 +4998,17 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and number 2

    +}

    -
    Contract.make {
    +
    and number *2*
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_2' input { messageFrom('input') @@ -5536,146 +5028,151 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and the following Spring Integration Route:

    +}

    -
    <?xml version="1.0" encoding="UTF-8"?>
    +
    and the following Spring Integration Route:
    +
    +[source,xml]
    +
    +
    +
    +

    <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/integration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans - http://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> + http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/integration + http://www.springframework.org/schema/integration/spring-integration.xsd">;

    - - -
    -
    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')
    +
    <!-- REQUIRED FOR TESTING -->
    +<bridge input-channel="output"
    +		output-channel="outputTest"/>
    +
    +
    +
    +
    +
    <channel id="outputTest">
    +	<queue/>
    +</channel>
    -

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

    +

    </beans:beans>

    -
    Message<?> receivedMessage = messaging.receive('outputTest')
    +
    ===== 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
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

    stubFinder.trigger('return_book_1')

    -
    receivedMessage != null
    +
    Next we'll want to listen to the output of the message sent to `{output_name}`
    +
    +[source,groovy]
    +
    +
    +
    +

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

    +
    +
    +
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    receivedMessage != null assertJsons(receivedMessage.payload) -receivedMessage.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 output destination.

    +receivedMessage.headers.get('BOOK-NAME') == 'foo'

    -
    messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')
    +
    ===== Scenario 2 (output triggered by input)
    +
    +Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
    +
    +[source,groovy]
    -

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

    +

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

    -
    Message<?> receivedMessage = messaging.receive('outputTest')
    +
    Next we'll want to listen to the output of the message sent to `{output_name}`
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

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

    -
    receivedMessage != null
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    receivedMessage != null assertJsons(receivedMessage.payload) -receivedMessage.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 input destination.

    +receivedMessage.headers.get('BOOK-NAME') == 'foo'

    -
    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
    +
    ===== Scenario 3 (input with no output)
    +
    +Since the route is set for you it's enough to just send a message to the `{input_name}` destination.
    +
    +[source,groovy]
    -
    - - -
    -

    Stub Runner Stream

    -

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Stream. +

    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 will automatically download the stubs and register the required
    -routes.

    -
    -
    - - - - - -
    -
    Warning
    -
    -In Stub Runner’s integration with Stream the messageFrom or sentTo Strings are resolved -first as a destination of a channel, and then if there is no such destination it’s resolved as a +routes. + +WARNING: In Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings are resolved +first as a `destination` of a channel, and then if there is no such `destination` it's resolved as a channel name. -
    + +==== 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 `@AutoConfigureMessageVerifier`. + +==== Examples + +===== Stubs structure + +Let us assume that we have the following Maven repository with a deployed stubs for the +`streamService` application. + +[source,bash,indent=0] +
    -
    -

    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 @AutoConfigureMessageVerifier.

    -
    -
    -
    -

    Examples

    -
    -
    Stubs structure
    -
    -

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

    -
    -
    -
    -
    └── .m2
    +

    └── .m2 └── repository └── io └── codearte @@ -5686,30 +5183,34 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier

    -
    -
    -
    -

    And the stubs contain the following structure:

    + └── maven-metadata-local.xml

    -
    ├── META-INF
    +
    And the stubs contain the following structure:
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

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

    -
    -
    -

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

    + └── mappings

    -
    Contract.make {
    +
    Let's consider the following contracts (let' number it with *1*):
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_1' input { triggeredBy('bookReturnedTriggered()') } outputMessage { @@ -5717,15 +5218,17 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and number 2

    +}

    -
    Contract.make {
    +
    and number *2*
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'return_book_2' input { messageFrom('bookStorage') @@ -5741,144 +5244,153 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and the following Spring configuration:

    +}

    -
    stubrunner.repositoryRoot: classpath:m2repo/repository/
    -stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
    +
    and the following Spring configuration:
     
    -spring:
    +[source,yaml]
    +
    +
    +
    +

    stubrunner.repositoryRoot: classpath:m2repo/repository/ +stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs

    +
    +
    +

    spring: cloud: stream: bindings: output: destination: returnBook input: - destination: bookStorage + destination: bookStorage

    +
    +
    +

    server: + port: 0

    +
    +
    +

    debug: true

    +
    +
    +
    +
    ===== Scenario 1 (no input message)
     
    -server:
    -  port: 0
    +So as to trigger a message via the `return_book_1` label we'll use the `StubTrigger` interface as follows
     
    -debug: true
    -
    -
    - -
    -
    Scenario 1 (no input message)
    -
    -

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

    -
    -
    -
    -
    stubFinder.trigger('return_book_1')
    +[source,groovy]
    -

    Next we’ll want to listen to the output of the message sent to a channel whose destination is returnBook

    +

    stubFinder.trigger('return_book_1')

    -
    Message<?> receivedMessage = messaging.receive('returnBook')
    +
    Next we'll want to listen to the output of the message sent to a channel whose `destination` is `returnBook`
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

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

    -
    receivedMessage != null
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    receivedMessage != null assertJsons(receivedMessage.payload) -receivedMessage.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 bookStorage destination.

    +receivedMessage.headers.get('BOOK-NAME') == 'foo'

    -
    messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')
    +
    ===== Scenario 2 (output triggered by input)
    +
    +Since the route is set for you it's enough to just send a message to the `bookStorage` `destination`.
    +
    +[source,groovy]
    -

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

    +

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

    -
    Message<?> receivedMessage = messaging.receive('returnBook')
    +
    Next we'll want to listen to the output of the message sent to `returnBook`
    +
    +[source,groovy]
    -

    And the received message would pass the following assertions

    +

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

    -
    receivedMessage != null
    +
    And the received message would pass the following assertions
    +
    +[source,groovy]
    +
    +
    +
    +

    receivedMessage != null assertJsons(receivedMessage.payload) -receivedMessage.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 output destination.

    +receivedMessage.headers.get('BOOK-NAME') == 'foo'

    -
    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
    +
    ===== Scenario 3 (input with no output)
    +
    +Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
    +
    +[source,groovy]
    -
    - - -
    -

    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. +

    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 will automatically download the stubs and register 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 @SpyBean. -Thus it can use the mockito spy functionality to verify and introspect messages sent by the application.

    -
    -
    -

    On the message consumer side, it considers all @RabbitListener annotated endpoints as well as all `SimpleMessageListenerContainer`s on the application context.

    -
    -
    -

    As messages are usually sent to exchanges in AMQP the message contract contains the exchange name as the destination. +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 `@SpyBean`. +Thus it can use the mockito spy functionality to verify and introspect messages sent by the application. + +On the message consumer side, it considers all `@RabbitListener` annotated endpoints as well as all `SimpleMessageListenerContainer`s 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 will look for bindings on the application context that match this exchange. Then it collects the queues from the Spring exchanges and tries to find messages listeners bound to these queues. -The message is triggered to all matching message listeners.

    +The message is triggered to all matching message listeners. + +==== Adding it to the project + +It's enough to 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 `@AutoConfigureMessageVerifier`. + +==== Examples + +===== Stubs structure + +Let us assume that we have the following Maven repository with a deployed stubs for the +`spring-cloud-contract-amqp-test` application. + +[source,bash,indent=0] +
    -
    -

    Adding it to the project

    -

    It’s enough to 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 @AutoConfigureMessageVerifier.

    -
    -
    -
    -

    Examples

    -
    -
    Stubs structure
    -
    -

    Let us assume that we have the following Maven repository with a deployed stubs for the -spring-cloud-contract-amqp-test application.

    -
    -
    -
    -
    └── .m2
    +

    └── .m2 └── repository └── com └── example @@ -5887,26 +5399,30 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier

    -
    -
    -
    -

    And the stubs contain the following structure:

    + └── maven-metadata-local.xml

    -
    ├── META-INF
    +
    And the stubs contain the following structure:
    +
    +[source,bash,indent=0]
    +
    +
    +
    +

    ├── META-INF │   └── MANIFEST.MF └── contracts - └── shouldProduceValidPersonData.groovy -

    -
    -
    -

    Let’s consider the following contract:

    + └── shouldProduceValidPersonData.groovy

    -
    Contract.make {
    +
    Let's consider the following contract:
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { // Human readable description description 'Should produce valid person data' // Label by means of which the output message can be triggered @@ -5922,7 +5438,7 @@ Remember to annotate your test class with @AutoConfigureMessageVerifierTypeId': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person') } // the body of the output message body ([ @@ -5930,150 +5446,128 @@ Remember to annotate your test class with @AutoConfigureMessageVerifier -

    -
    -
    -

    and the following Spring configuration:

    +}

    -
    stubrunner:
    +
    and the following Spring configuration:
    +
    +[source,yaml]
    +
    +
    +
    +

    stubrunner: repositoryRoot: classpath:m2repo/repository/ ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs amqp: enabled: true server: - port: 0 -

    -
    - -
    -
    Triggering the message
    -
    -

    So to trigger a message using the contract above we’ll use the StubTrigger interface as follows.

    + port: 0

    -
    stubTrigger.trigger("contract-test.person.created.event")
    +
    ===== Triggering the message
    +
    +So to trigger a message using the contract above we'll use the `StubTrigger` interface as follows.
    +
    +[source,groovy]
    -

    The message has the destination contract-test.exchange so the Spring AMQP stub runner integration looks for bindings related to this exchange.

    +

    stubTrigger.trigger("contract-test.person.created.event")

    -
    @Bean
    +
    The message has the destination `contract-test.exchange` so the Spring AMQP stub runner integration looks for bindings related to this exchange.
    +
    +[source,java]
    +
    +
    +
    +

    @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. -So the following listener definition is a match and is invoked with the contract message.

    +}

    -
    @Bean
    +
    The binding definition binds the queue `test.queue`.
    +So the following listener definition is a match and is invoked with the contract message.
    +
    +[source,java]
    +
    +
    +
    +

    @Bean public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames("test.queue"); - container.setMessageListener(listenerAdapter); - - return container; -} + container.setMessageListener(listenerAdapter);

    +
    +
    +
    	return container;
    +}
    -
    -

    Also, the following annotated listener represents a match and would be invoked.

    -
    @RabbitListener(bindings = @QueueBinding(
    +
    Also, the following annotated listener represents a match and would be invoked.
    +[source,java]
    +
    +
    +
    +

    @RabbitListener(bindings = @QueueBinding( value = @Queue(value = "test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true"))) public void handlePerson(Person person) { this.person = person; -} -

    -
    -
    - - - - - -
    -
    Note
    -
    -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 that Spring AMQP is trying to connect to a running broker during our tests we configure a mock ConnectionFactory.

    -
    -
    -

    To disable the mocked ConnectionFactory set the property stubrunner.amqp.mockConnection=false

    +}

    -
    stubrunner:
    +
    NOTE: 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 that Spring AMQP is trying to connect to a running broker during our tests we configure a mock `ConnectionFactory`.
    +
    +To disable the mocked ConnectionFactory set the property `stubrunner.amqp.mockConnection=false`
    +
    +[source,yaml]
    +
    +
    +
    +

    stubrunner: amqp: - mockConnection: false -

    -
    - - - -
    -

    Contract DSL

    -
    - - - - - -
    -
    Important
    -
    -Remember that inside the contract file you have to provide the fully qualified name to -the Contract class and the make static import i.e. 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 { …​ } -
    -
    -
    -

    Contract DSL is written in Groovy, but don’t be alarmed if you didn’t use Groovy before. Knowledge of the language is not really needed as our DSL uses only -a tiny subset of it (namely literals, method calls and closures). What’s more the DSL is designed to be programmer-readable without any knowledge of the DSL itself - - it’s statically typed.

    -
    -
    - - - - - -
    -
    Tip
    -
    -Spring Cloud Contract supports defining multiple contracts in a single file! -
    -
    -
    -

    The Contract is present in the spring-cloud-contract-spec module of the Spring Cloud Contract Verifier repository.

    -
    -
    -

    Let’s look at full example of a contract definition.

    + mockConnection: false

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    === Contract DSL
    +
    +IMPORTANT: Remember that inside the contract file you have to provide the fully qualified name to
    +the `Contract` class and the `make` static import i.e. `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 { ... }`
    +
    +Contract DSL is written in Groovy, but don't be alarmed if you didn't use Groovy before. Knowledge of the language is not really needed as our DSL uses only
    +a tiny subset of it (namely literals, method calls and closures). What's more the DSL is designed to be programmer-readable without any knowledge of the DSL itself -
    + it's statically typed.
    +
    +TIP: Spring Cloud Contract supports defining multiple contracts in a single file!
    +
    +The Contract is present in the `spring-cloud-contract-spec` module of the Spring Cloud Contract Verifier repository.
    +
    +Let's look at full example of a contract definition.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method 'PUT' url '/api/12' @@ -6114,72 +5608,38 @@ Spring Cloud Contract supports defining multiple contracts in a single file! response { status 200 } -} -

    -
    -
    -

    Not all features of the DSL are used in example above. If you didn’t find what you are looking for, please check next paragraphs on this page.

    -
    -
    -
    -
    -

    You can easily compile Contracts to WireMock stubs mapping using standalone maven command: mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert.

    -
    -
    -
    -
    -

    Limitations

    -
    - - - - - -
    -
    Warning
    -
    -Spring Cloud Contract Verifier doesn’t support XML properly. Please use JSON or help us implement this feature. -
    -
    -
    - - - - - -
    -
    Warning
    -
    -The support for the verification of size of JSON arrays is experimental. If you want to turn it on please provide -the value of a system property spring.cloud.contract.verifier.assert.size equal to true. By default this feature is set to -false. You can also provide the assertJsonSize property in the plugin configuration. -
    -
    -
    - - - - - -
    -
    Warning
    -
    -Due to the fact that JSON structure can have any form it’s sometimes impossible to parse it properly when using -the value(consumer(…​), producer(…​)) notation when using that in GString. That’s why we highly recommend using the -Groovy Map notation. -
    -
    -
    -
    -

    Common Top-Level elements

    -
    -
    Description
    -
    -

    You can add a description to your contract that is nothing else but an arbitrary text. Example:

    +}

    -
    		org.springframework.cloud.contract.spec.Contract.make {
    +
    Not all features of the DSL are used in example above. If you didn't find what you are looking for, please check next paragraphs on this page.
    +
    +> You can easily compile Contracts to WireMock stubs mapping using standalone maven command: `mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert`.
    +
    +==== Limitations
    +
    +WARNING: Spring Cloud Contract Verifier doesn't support XML properly. Please use JSON or help us implement this feature.
    +
    +WARNING: The support for the verification of size of JSON arrays is experimental. If you want to turn it on please provide
    +the value of a system property `spring.cloud.contract.verifier.assert.size` equal to `true`. By default this feature is set to
    +`false`. You can also provide the `assertJsonSize` property in the plugin configuration.
    +
    +WARNING: Due to the fact that JSON structure can have any form it's sometimes impossible to parse it properly when using
    +the `value(consumer(...), producer(...))` notation when using that in GString. That's why we highly recommend using the
    +Groovy Map notation.
    +
    +==== Common Top-Level elements
    +
    +===== Description
    +
    +You can add a `description` to your contract that is nothing else but an arbitrary text. Example:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +
    +
    		org.springframework.cloud.contract.spec.Contract.make {
     			description('''
     given:
     	An input
    @@ -6188,284 +5648,352 @@ when:
     then:
     	Output
     ''')
    -		}
    + }
    -
    -
    -
    Name
    -
    -

    You can provide a name of your contract. Let’s assume that you’ve provided a name should register a user. -If you do this then the name of the autogenerated test will be equal to validate_should_register_a_user. -Also the name of the stub will be should_register_a_user.json in case of a WireMock stub.

    -
    -
    - - - - - -
    -
    Important
    -
    -Please ensure that the name doesn’t contain any characters that will make the generated test +
    +
    +
    ===== Name
    +
    +You can provide a name of your contract. Let's assume that you've provided a name `should register a user`.
    +If you do this then the name of the autogenerated test will be equal to `validate_should_register_a_user`.
    +Also the name of the stub will be `should_register_a_user.json` in case of a WireMock stub.
    +
    +IMPORTANT: Please ensure that the name doesn't contain any characters that will make the generated test
      not possible to compile. Also remember that if you provide the same name for multiple contracts then your
      autogenerated tests will fail to compile and your generated stubs will override each other.
    -
    + +===== Ignoring contracts + +If you want to ignore a contract you can either set a value of ignored contracts in the plugin configuration +or just set the `ignored` property on the contract itself: + +[source,groovy,indent=0]
    -
    -
    Ignoring contracts
    -

    If you want to ignore a contract you can either set a value of ignored contracts in the plugin configuration -or just set the ignored property on the contract itself:

    -
    -
    -
    -
    org.springframework.cloud.contract.spec.Contract.make {
    +

    org.springframework.cloud.contract.spec.Contract.make { ignored() -}

    -
    -
    -
    -
    -
    -

    HTTP Top-Level Elements

    -
    -

    Following methods can be called in the top-level closure of a contract definition. Request and response are mandatory, priority is optional.

    +}

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    ==== HTTP Top-Level Elements
    +
    +Following methods can be called in the top-level closure of a contract definition. Request and response are mandatory, priority is optional.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    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 { - //... - } - - // 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 { - //... - } - - // Contract priority, which can be used for overriding + //…​ + }

    +
    +
    +
    +
    // 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 {
    +	//...
    +}
    +
    +
    +
    +
    +
    	// Contract priority, which can be used for overriding
     	// contracts (1 is highest). Priority is optional.
     	priority 1
    -}
    +}
    -
    -
    -

    Request

    -
    -

    HTTP protocol requires only method and address to be specified in a request. The same information is mandatory in request definition of the Contract.

    -
    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    ==== Request
    +
    +HTTP protocol requires only **method and address** to be specified in a request. The same information is mandatory in request definition of the Contract.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    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 { + method 'GET'

    +
    +
    +
    +
    	// Path component of request URL is specified as follows.
    +	urlPath('/users')
    +}
    +
    +
    +
    +
    +
    	response {
     		//...
     	}
    -}
    +}
    -
    -

    It is possible to specify whole url instead of just path, but urlPath is the recommended way as it makes the tests host-independent.

    -
    -
    org.springframework.cloud.contract.spec.Contract.make {
    -	request {
    -		method 'GET'
    +
    It is possible to specify whole `url` instead of just path, but `urlPath` is the recommended way as it makes the tests **host-independent**.
     
    -		// Specifying `url` and `urlPath` in one contract is illegal.
    -		url('http://localhost:8888/users')
    -	}
    -
    -	response {
    -		//...
    -	}
    -}
    +[source,groovy,indent=0]
    -

    Request may contain query parameters, which are specified in a closure nested in a call to urlPath or url.

    +

    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 {
    +		//...
    +	}
    +}
    +
    -
    org.springframework.cloud.contract.spec.Contract.make {
    -	request {
    -		//...
    +
    Request may contain **query parameters**, which are specified in a closure nested in a call to `urlPath` or `url`.
     
    -		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 {
    -		//...
    -	}
    -}
    +[source,groovy,indent=0]
    -

    It may contain additional request headers…​

    +

    org.springframework.cloud.contract.spec.Contract.make { + request { + //…​

    +
    +
    +
    +
    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 {
    +		//...
    +	}
    +}
    +
    -
    org.springframework.cloud.contract.spec.Contract.make {
    -	request {
    -		//...
    +
    It may contain additional **request headers**...
     
    -		// Each header is added in form `'Header-Name' : 'Header-Value'`.
    -		// there are also some helper methods
    -		headers {
    -			header 'key': 'value'
    -			contentType(applicationJson())
    -		}
    -
    -		//...
    -	}
    -
    -	response {
    -		//...
    -	}
    -}
    +[source,groovy,indent=0]
    -

    …​and a request body.

    +

    org.springframework.cloud.contract.spec.Contract.make { + request { + //…​

    +
    +
    +
    +
    // Each header is added in form `'Header-Name' : 'Header-Value'`.
    +// there are also some helper methods
    +headers {
    +	header 'key': 'value'
    +	contentType(applicationJson())
    +}
    +
    +
    +
    +
    +
    	//...
    +}
    +
    +
    +
    +
    +
    	response {
    +		//...
    +	}
    +}
    +
    -
    org.springframework.cloud.contract.spec.Contract.make {
    -	request {
    -		//...
    +
    ...and a **request body**.
     
    -		// 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 {
    -		//...
    -	}
    -}
    +[source,groovy,indent=0]
    -
    -
    -

    Response

    -

    Minimal response must contain HTTP status code.

    +

    org.springframework.cloud.contract.spec.Contract.make { + request { + //…​

    +
    +
    +
    +
    	// 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 {
    +		//...
    +	}
    +}
    +
    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    //**Body's format** can also be specified explicitly by invoking one of format functions.
    +//
    +//[source,groovy,indent=0]
    +//----
    +//include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=bodyAsXml,indent=0]
    +//----
    +
    +==== Response
    +
    +Minimal response must contain **HTTP status code**.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { - //... + //…​ } response { // Status code sent by the server // in response to request specified above. status 200 } -} +}

    -
    -
    -

    Besides status response may contain headers and body, which are specified the same way as in the request (see previous paragraph).

    -
    - -
    -

    Dynamic properties

    -
    -

    The contract can contain some dynamic properties - timestamps / ids etc. You don’t want to enforce the consumers to stub their -clocks to always return the same value of time so that it gets matched by the stub. That’s why we allow you to provide the dynamic +

    +
    +
    Besides status response may contain **headers** and **body**, which are specified the same way as in the request (see previous paragraph).
    +
    +==== Dynamic properties
    +
    +The contract can contain some dynamic properties - timestamps / ids etc. You don't want to enforce the consumers to stub their
    +clocks to always return the same value of time so that it gets matched by the stub. That's why we allow you to provide the dynamic
     parts in your contracts in two ways. One is to pass them directly in the
    -body and one to set them in a separate section called testMatchers and stubMatchers.

    +body and one to set them in a separate section called `testMatchers` and `stubMatchers`. + +===== Dynamic properties inside the body + +You can set the properties inside the body either via the `value` method + +[source,groovy,indent=0]
    +
    -
    -
    Dynamic properties inside the body
    -

    You can set the properties inside the body either via the value method

    +

    value(consumer(…​), producer(…​)) +value(c(…​), p(…​)) +value(stub(…​), test(…​)) +value(client(…​), server(…​))

    -
    value(consumer(...), producer(...))
    -value(c(...), p(...))
    -value(stub(...), test(...))
    -value(client(...), server(...))
    +
    or if you're using the Groovy map notation for body you can use the `$()` method
    +
    +[source,groovy,indent=0]
    -

    or if you’re using the Groovy map notation for body you can use the $() method

    +

    $(consumer(…​), producer(…​)) +$(c(…​), p(…​)) +$(stub(…​), test(…​)) +$(client(…​), server(…​))

    -
    $(consumer(...), producer(...))
    -$(c(...), p(...))
    -$(stub(...), test(...))
    -$(client(...), server(...))
    -
    -
    -
    -

    All of the aforementioned approaches are equal. That means that stub and client methods are aliases over the consumer -method. Let’s take a closer look at what we can do with those values in the subsequent sections.

    -
    -
    -
    Regular expressions
    -
    -

    You can use regular expressions to write your requests in Contract DSL. It is particularly useful when you want to indicate that a given response +

    All of the aforementioned approaches are equal. That means that `stub` and `client` methods are aliases over the `consumer`
    +method. Let's take a closer look at what we can do with those values in the subsequent sections.
    +
    +====== Regular expressions
    +
    +You can use regular expressions to write your requests in Contract DSL. It 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 it when you need to use patterns and not exact values both
    -for your test and your server side tests.

    +for your test and your server side tests. + +Please see the example below: + +[source,groovy,indent=0]
    +
    -

    Please see the example below:

    -
    -
    -
    -
    org.springframework.cloud.contract.spec.Contract.make {
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method('GET') url $(consumer(~/\/[0-9]{2}/), producer('/12')) @@ -6488,16 +6016,18 @@ for your test and your server side tests.

    header 'Content-Type': 'text/plain' } } -}
    -
    -
    -
    -

    You can also provide only one side of the communication using a regular expression. If you do that then automatically we’ll -provide the generated string that matches the provided regular expression. For example:

    +}

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    You can also provide only one side of the communication using a regular expression. If you do that then automatically we'll
    +provide the generated string that matches the provided regular expression. For example:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method 'PUT' url value(consumer(regex('/foo/[0-9]{5}'))) @@ -6517,80 +6047,94 @@ provide the generated string that matches the provided regular expression. For e contentType("application/vnd.fraud.v1+json") } } -} -

    -
    -
    -

    In this example for request and response the opposite side of the communication will have the respective data generated.

    -
    -
    -

    Spring Cloud Contract comes with a series of predefined regular expressions that you can use in your contracts.

    +}

    -
    protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
    -protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/)
    -protected static final Pattern NUMBER = Pattern.compile('-?\\d*(\\.\\d+)?')
    +
    In this example for request and response the opposite side of the communication will have the respective data generated.
    +
    +Spring Cloud Contract comes with a series of predefined regular expressions that you can use in your contracts.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/) +protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(//) +protected static final Pattern NUMBER = Pattern.compile('-?\\d(\\.\\d+)?') 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,4}'); -protected static final Pattern URL = Pattern.compile('((www\\.|(http|https|ftp|news|file)+\\:\\/\\/)[_.a-z0-9-]+\\.[a-z0-9\\/_:@=.+?,##%&~-]*[^.|\\\'|\\# |!|\\(|?|,| |>|<|;|\\)])') +protected static final Pattern HOSTNAME_PATTERN = Pattern.compile('((http[s]?|ftp):\\/)\\/?()(:[0-9]{1,5})?') +protected static final Pattern EMAIL = Pattern.compile('[a-zA-Z0-9._%-]@[a-zA-Z0-9.-]\\.[a-zA-Z]{2,4}'); +protected static final Pattern URL = Pattern.compile('((www\\.|(http|https|ftp|news|file)\\:\\/\\/)[_.a-z0-9-]\\.[a-z0-9\\/_:@=.+?,#%&~-]*[^.|\\\'|\\ |!|\\(|?|,| |>|<|;|\\)])') protected static final Pattern UUID = Pattern.compile('[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-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])') - -String onlyAlphaUnicode() { - return ONLY_ALPHA_UNICODE.pattern() -} - -String number() { - return NUMBER.pattern() -} - -String anyBoolean() { - return TRUE_OR_FALSE.pattern() -} - -String ipAddress() { - return IP_ADDRESS.pattern() -} - -String hostname() { - return HOSTNAME_PATTERN.pattern() -} - -String email() { - return EMAIL.pattern() -} - -String url() { - return URL.pattern() -} - -String uuid(){ - return UUID.pattern() -} - -String isoDate() { - return ANY_DATE.pattern() -} - -String isoDateTime() { - return ANY_DATE_TIME.pattern() -} - -String isoTime() { - return ANY_TIME.pattern() -} -

    +protected static final Pattern ANY_TIME = Pattern.compile('(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])')

    -

    so in your contract you can use it like this

    +

    String onlyAlphaUnicode() { + return ONLY_ALPHA_UNICODE.pattern() +}

    +
    +
    +

    String number() { + return NUMBER.pattern() +}

    +
    +
    +

    String anyBoolean() { + return TRUE_OR_FALSE.pattern() +}

    +
    +
    +

    String ipAddress() { + return IP_ADDRESS.pattern() +}

    +
    +
    +

    String hostname() { + return HOSTNAME_PATTERN.pattern() +}

    +
    +
    +

    String email() { + return EMAIL.pattern() +}

    +
    +
    +

    String url() { + return URL.pattern() +}

    +
    +
    +

    String uuid(){ + return UUID.pattern() +}

    +
    +
    +

    String isoDate() { + return ANY_DATE.pattern() +}

    +
    +
    +

    String isoDateTime() { + return ANY_DATE_TIME.pattern() +}

    +
    +
    +

    String isoTime() { + return ANY_TIME.pattern() +}

    -
    Contract dslWithOptionalsInString = Contract.make {
    +
    so in your contract you can use it like this
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    Contract dslWithOptionalsInString = Contract.make { priority 1 request { method POST() @@ -6599,7 +6143,7 @@ String isoTime() { contentType(applicationJson()) } body( - email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), + email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), callback_url: $(consumer(regex(hostname())), producer('http://partners.com')) ) } @@ -6610,34 +6154,27 @@ String isoTime() { } body( code: value(consumer("123123"), producer(optional("123123"))), - message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]" + message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]" ) } -} -

    -
    - -
    -
    Passing optional parameters
    -
    -

    It is possible to provide optional parameters in your contract. It’s only possible to have optional parameter for the:

    -
    -
    -
      -
    • -

      STUB side of the Request

      -
    • -
    • -

      TEST side of the Response

      -
    • -
    -
    -
    -

    Example:

    +}

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    ====== Passing optional parameters
    +
    +It is possible to provide optional parameters in your contract. It's only possible to have optional parameter for the:
    +
    +- __STUB__ side of the Request
    +- __TEST__ side of the Response
    +
    +Example:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { priority 1 request { method 'POST' @@ -6646,7 +6183,7 @@ String isoTime() { contentType(applicationJson()) } body( - email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), + email: $(consumer(optional(regex(email()))), producer('abc@abc.com')), callback_url: $(consumer(regex(hostname())), producer('http://partners.com')) ) } @@ -6659,48 +6196,56 @@ String isoTime() { code: value(consumer("123123"), producer(optional("123123"))) ) } -} -

    -
    -
    -

    By wrapping a part of the body with the optional() method you are in fact creating a regular expression that should be present 0 or more times.

    -
    -
    -

    That way for the example above the following test would be generated if you pick Spock:

    +}

    -
    """
    +
    By wrapping a part of the body with the `optional()` method you are in fact creating a regular expression that should be present 0 or more times.
    +
    +That way for the example above the following test would be generated if you pick Spock:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    """ given: def request = given() .header("Content-Type", "application/json") - .body('''{"email":"abc@abc.com","callback_url":"http://partners.com"}''') - - when: - def response = given().spec(request) - .post("/users/password") - - then: + .body('''{"email":"abc@abc.com","callback_url":"http://partners.com"}''')

    +
    +
    +
    +
    when:
    + def response = given().spec(request)
    +   .post("/users/password")
    +
    +
    +
    +
    +
     then:
       response.statusCode == 404
       response.header('Content-Type')  == 'application/json'
      and:
       DocumentContext parsedJson = JsonPath.parse(response.body.asString())
       assertThatJson(parsedJson).field("code").matches("(123123)?")
    -"""
    +"""
    -
    -

    and the following stub:

    -
    -
    '''
    -{
    +
    and the following stub:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +
    +

    { "request" : { "url" : "/users/password", "method" : "POST", - "bodyPatterns" : [ { - "matchesJsonPath" : "$[?(@.email =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4})?/)]" + "bodyPatterns" : @[a-zA-Z0-9.-]\\\\.[a-zA-Z]{2,4})?/)]" }, { "matchesJsonPath" : "$[?(@.callback_url =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]" } ], @@ -6712,29 +6257,29 @@ String isoTime() { }, "response" : { "status" : 404, - "body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}", + "body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}", "headers" : { "Content-Type" : "application/json" } }, "priority" : 1 } -''' -

    - - -
    -
    Executing custom methods on server side
    -
    -

    It is also possible to define a method call to be executed on the server side during the test. Such a method can be added to the class defined as "baseClassForTests" -in the configuration. Example:

    -
    -
    -

    Contract

    +'''

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    ====== Executing custom methods on server side
    +
    +It is also possible to define a method call to be executed on the server side during the test. Such a method can be added to the class defined as "baseClassForTests"
    +in the configuration. Example:
    +
    +*Contract*
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method 'PUT' url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12')) @@ -6754,112 +6299,92 @@ in the configuration. Example:

    ) status 200 } -}
    -
    -
    -
    -

    Base class

    +}

    -
    abstract class BaseMockMvcSpec extends Specification {
    +
    *Base class*
     
    -	def setup() {
    -		RestAssuredMockMvc.standaloneSetup(new PairIdController())
    -	}
    -
    -	void isProperCorrelationId(Integer correlationId) {
    -		assert correlationId == 123456
    -	}
    -
    -	void isEmpty(String value) {
    -		assert value == null
    -	}
    -
    -}
    +[source,groovy,indent=0]
    - - -
    -
    Dynamic properties in matchers sections
    -
    -

    If you’ve been working with Pact this might seem familiar. Quite a few users -are used to having a separation between the body and setting dynamic parts of your contract.

    -
    -

    That’s why you can profit from two separate sections. One is called stubMatchers where you can -define the dynamic values that should end up in a stub. You can set it in the request or inputMessage -part of your contract. The other is called testMatchers which is present in the response or -outputMessage side of the contract.

    +

    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
    +}
    +
    -

    Currently we support only JSON Path based matchers with the following matching possibilities. -For stubMatchers:

    +

    }

    -
    -
      -
    • -

      byEquality() - the value taken from the response via the provided JSON Path needs -to be equal to the provided value in the contract

      -
    • -
    • -

      byRegex(…​) - the value taken from the response via the provided JSON Path needs -to match the regex

      -
    • -
    • -

      byDate() - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Date

      -
    • -
    • -

      byTimestamp() - the value taken from the response via the provided JSON Path needs -to match the regex for ISO DateTime

      -
    • -
    • -

      byTime() - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Time

      -
    • -
    -
    -
    -

    For testMatchers:

    -
    -
    -
      -
    • -

      byEquality() - the value taken from the response via the provided JSON Path needs -to be equal to the provided value in the contract

      -
    • -
    • -

      byRegex(…​) - the value taken from the response via the provided JSON Path needs -to match the regex

      -
    • -
    • -

      byDate() - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Date

      -
    • -
    • -

      byTimestamp() - the value taken from the response via the provided JSON Path needs -to match the regex for ISO DateTime

      -
    • -
    • -

      byTime() - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Time

      -
    • -
    • -

      byType() - the value taken from the response via the provided JSON Path needs to +

      +
      +
      ===== Dynamic properties in matchers sections
      +
      +If you've been working with https://docs.pact.io/[Pact] this might seem familiar. Quite a few users
      +are used to having a separation between the body and setting dynamic parts of your contract.
      +
      +That's why you can profit from two separate sections. One is called `stubMatchers` where you can
      +define the dynamic values that should end up in a stub. You can set it in the `request` or `inputMessage`
      +part of your contract. The other is called `testMatchers` which is present in the `response` or
      +`outputMessage` side of the contract.
      +
      +Currently we support only JSON Path based matchers with the following matching possibilities.
      +For `stubMatchers`:
      +
      +- `byEquality()` - the value taken from the response via the provided JSON Path needs
      +to be equal to the provided value in the contract
      +- `byRegex(...)` - the value taken from the response via the provided JSON Path needs
      +to match the regex
      +- `byDate()` - the value taken from the response via the provided JSON Path needs to
      +match the regex for ISO Date
      +- `byTimestamp()` - the value taken from the response via the provided JSON Path needs
      +to match the regex for ISO DateTime
      +- `byTime()` - the value taken from the response via the provided JSON Path needs to
      +match the regex for ISO Time
      +
      +For `testMatchers`:
      +
      +- `byEquality()` - the value taken from the response via the provided JSON Path needs
      +to be equal to the provided value in the contract
      +- `byRegex(...)` - the value taken from the response via the provided JSON Path needs
      +to match the regex
      +- `byDate()` - the value taken from the response via the provided JSON Path needs to
      +match the regex for ISO Date
      +- `byTimestamp()` - the value taken from the response via the provided JSON Path needs
      +to match the regex for ISO DateTime
      +- `byTime()` - the value taken from the response via the provided JSON Path needs to
      +match the regex for ISO Time
      +- `byType()` - the value taken from the 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 where you can set minOccurrence and maxOccurrence.
      -That way you can assert on the size of the collection.

      -
    • -
    +`byType` can take a closure where you can set `minOccurrence` and `maxOccurrence`. +That way you can assert on the size of the collection. + +Let's take a look at the following example: + +[source,groovy,indent=0] +
    -

    Let’s take a look at the following example:

    -
    -
    -
    -
    Contract contractDsl = Contract.make {
    +

    Contract contractDsl = Contract.make { request { method 'GET' urlPath '/get' @@ -6955,54 +6480,50 @@ That way you can assert on the size of the collection.

    contentType(applicationJson()) } } -}
    -
    -
    -
    -

    In this example we’re providing the dynamic portions of the contract in the matchers sections. - For the request part you can see that for all fields but valueWithoutAMatcher we’re setting - explicitly the values of regular expressions we’d like the stub to contain. For the valueWithoutAMatcher - the verification will take place in the same way as without the usage of matchers - the test - will perform an equality check in this case.

    -
    -
    -

    For the response side in the testMatchers section we’re defining all the dynamic parts - in a similar manner. The only difference is that we have the byType matchers too. In that - case we’re checking 4 fields in the way that we’re verifying whether the response from the test - has a value whose JSON path matching the given field is of the same type as the one defined in the response body and:

    -
    -
    -
      -
    • -

      for $.valueWithTypeMatch - we’re just checking the whether the type is the same

      -
    • -
    • -

      for $.valueWithMin - we’re checking the type and assert if the size is greater or equal to the min occurrence

      -
    • -
    • -

      for $.valueWithMax - we’re checking the type and assert if the size is smaller or equal to the max occurrence

      -
    • -
    • -

      for $.valueWithMinMax - we’re checking the type and assert if the size is between the min and max occurrence

      -
    • -
    -
    -
    -

    The resulting test would look more or less like this (note that we’re separating the autogenerated -assertions and the one from matchers with an and section):

    +}

    -
    // given:
    +
    In this example we're providing the dynamic portions of the contract in the matchers sections.
    + For the request part you can see that for all fields but `valueWithoutAMatcher` we're setting
    + explicitly the values of regular expressions we'd like the stub to contain. For the `valueWithoutAMatcher`
    + the verification will take place in the same way as without the usage of matchers - the test
    + will perform an equality check in this case.
    +
    +For the response side in the `testMatchers` section we're defining all the dynamic parts
    + in a similar manner. The only difference is that we have the `byType` matchers too. In that
    + case we're checking 4 fields in the way that we're verifying whether the response from the test
    + has a value whose JSON path matching the given field is of the same type as the one defined in the response body and:
    +
    + - for `$.valueWithTypeMatch` - we're just checking the whether the type is the same
    + - for `$.valueWithMin` - we're checking the type and assert if the size is greater or equal to the min occurrence
    + - for `$.valueWithMax` - we're checking the type and assert if the size is smaller or equal to the max occurrence
    + - for `$.valueWithMinMax` - we're checking the type and assert if the size is between the min and max occurrence
    +
    +The resulting test would look more or less like this (note that we're separating the autogenerated
    +assertions and the one from matchers with an `and` section):
    +
    +[source,java,indent=0]
    +
    +
    +
    +
    +
    // 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\"}");
    -
    -// when:
    +   .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\"}");
    +
    +
    +
    +
    +
    // when:
      ResponseOptions response = given().spec(request)
    -   .get("/get");
    -
    -// then:
    +   .get("/get");
    +
    +
    +
    +
    +
    // then:
      assertThat(response.statusCode()).isEqualTo(200);
      assertThat(response.header("Content-Type")).matches("application/json.*");
     // and:
    @@ -7024,15 +6545,19 @@ assertions and the one from matchers with an and section):

    assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class); assertThat(parsedJson.read("$.valueWithMax", java.util.Collection.class).size()).isLessThanOrEqualTo(3); assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class); - assertThat(parsedJson.read("$.valueWithMinMax", java.util.Collection.class).size()).isStrictlyBetween(1, 3);
    + assertThat(parsedJson.read("$.valueWithMinMax", java.util.Collection.class).size()).isStrictlyBetween(1, 3);
    -
    -

    and the WireMock stub like this:

    -
    -
    				'''
    +
    and the WireMock stub like this:
    +
    +[source,json,indent=0]
    +
    +
    +
    +
    +
    				'''
     {
       "request" : {
         "urlPath" : "/get",
    @@ -7082,68 +6607,78 @@ assertions and the one from matchers with an and section):

    } } } -'''
    +'''
    - - -
    -

    JAX-RS support

    -
    -

    We support JAX-RS 2 Client API. Base class needs to define protected WebTarget webTarget and server initialization, right now the only option how to test JAX-RS API is to start a web server.

    -
    -
    -

    Request with a body needs to have a content type set otherwise application/octet-stream is going to be used.

    -
    -
    -

    In order to use JAX-RS mode, use the following settings:

    -
    -
    testMode === 'JAXRSCLIENT'
    +
    ==== JAX-RS support
    +
    +We support JAX-RS 2 Client API. Base class needs to define `protected WebTarget webTarget` and server initialization, right now the only option how to test JAX-RS API is to start a web server.
    +
    +Request with a body needs to have a content type set otherwise `application/octet-stream` is going to be used.
    +
    +In order to use JAX-RS mode, use the following settings:
    +
    +[source,groovy,indent=0]
    -

    Example of a test API generated:

    +

    testMode === 'JAXRSCLIENT'

    -
    '''
    - // when:
    -  Response response = webTarget
    -    .path("/users")
    -    .queryParam("limit", "10")
    -    .queryParam("offset", "20")
    -    .queryParam("filter", "email")
    -    .queryParam("sort", "name")
    -    .queryParam("search", "55")
    -    .queryParam("age", "99")
    -    .queryParam("name", "Denis.Stepanov")
    -    .queryParam("email", "bob@email.com")
    -    .request()
    -    .method("GET");
    +
    Example of a test API generated:
     
    -  String responseAsString = response.readEntity(String.class);
    -
    - // then:
    +[source,groovy,indent=0]
    +
    +
    +
    +
    +
    +
    // when:
    + Response response = webTarget
    +   .path("/users")
    +   .queryParam("limit", "10")
    +   .queryParam("offset", "20")
    +   .queryParam("filter", "email")
    +   .queryParam("sort", "name")
    +   .queryParam("search", "55")
    +   .queryParam("age", "99")
    +   .queryParam("name", "Denis.Stepanov")
    +   .queryParam("email", "bob@email.com")
    +   .request()
    +   .method("GET");
    +
    +
    +
    +
    +
    String responseAsString = response.readEntity(String.class);
    +
    +
    +
    +
    +
     // then:
       assertThat(response.getStatus()).isEqualTo(200);
      // and:
       DocumentContext parsedJson = JsonPath.parse(responseAsString);
       assertThatJson(parsedJson).field("property1").isEqualTo("a");
    -'''
    +'''
    -
    -
    -

    Async support

    -
    -

    If you’re using asynchronous communication on the server side (your controllers are returning -Callable, DeferredResult etc. then inside your contract you have to provide in the response -section a async() method. Example:

    -
    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    ==== Async support
    +
    +If you're using asynchronous communication on the server side (your controllers are returning
    +`Callable`, `DeferredResult` etc. then inside your contract you have to provide in the `response`
    +section a `async()` method. Example:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method GET() url '/get' @@ -7153,35 +6688,25 @@ section a async() method. Example:

    body 'Passed' async() } -}
    +}

    -
    - -
    -

    Working with Context Paths

    -
    -

    Spring Cloud Contract supports context paths.

    -
    -
    - - - - - -
    -
    Important
    -
    -The only thing that changes in order to fully support context paths is the switch -on the PRODUCER side. The autogenerated tests need to be using the EXPLICIT mode. -
    -
    -
    -

    The consumer side remains untouched, in order for the generated test to pass you have to switch the EXPLICIT mode.

    -
    -
    -
    Maven
    +
    -
    <plugin>
    +
    ==== Working with Context Paths
    +
    +Spring Cloud Contract supports context paths.
    +
    +IMPORTANT: The only thing that changes in order to fully support context paths is the switch
    +on the *PRODUCER* side. The autogenerated tests need to be using the *EXPLICIT* mode.
    +
    +The consumer side remains untouched, in order for the generated test to pass you have to switch the *EXPLICIT* mode.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.Maven
    +
    +
    +
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <version>${spring-cloud-contract.version}</version> @@ -7189,27 +6714,31 @@ on the PRODUCER side. The autogenerated tests need to be using <configuration> <testMode>EXPLICIT</testMode> </configuration> -</plugin> -

    -
    -
    -
    Gradle
    -
    -
    contracts {
    -		testMode = 'EXPLICIT'
    -}
    -
    -
    -
    -

    That way you’ll generate a test that DOES NOT use MockMvc. It means that you’re generating -real requests and you need to setup your generated test’s base class to work on a real socket.

    -
    -
    -

    Let’s imagine the following contract:

    +</plugin>

    -
    org.springframework.cloud.contract.spec.Contract.make {
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    contracts { + testMode = 'EXPLICIT' +}

    +
    +
    +
    +
    That way you'll generate a test that *DOES NOT* use MockMvc. It means that you're generating
    +real requests and you need to setup your generated test's base class to work on a real socket.
    +
    +Let's imagine the following contract:
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    org.springframework.cloud.contract.spec.Contract.make { request { method 'GET' url '/my-context-path/url' @@ -7217,60 +6746,61 @@ real requests and you need to setup your generated test’s base class to wo response { status 200 } -} -

    -
    -
    -

    Here is an example of how to set up a base class and Rest Assured for everything to work correctly.

    +}

    -
    import com.jayway.restassured.RestAssured;
    +
    Here is an example of how to set up a base class and Rest Assured for everything to work correctly.
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    import com.jayway.restassured.RestAssured; import org.junit.Before; import org.springframework.boot.context.embedded.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class ContextPathTestingBaseClass { - - @LocalServerPort int port; - - @Before +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;
     	}
    -}
    +}
    -
    -

    That way all:

    -
    -
    -
      -
    • -

      all your requests in the autogenerated tests will be sent to the real endpoint with your context path included (e.g. /my-context-path/url)

      -
    • -
    • -

      your contracts reflect that you have a context path, thus your generated stubs will also -have that information (e.g. in the stubs you’ll see that you have too call /my-context-path/url)

      -
    • -
    -
    - -
    -

    Messaging Top-Level Elements

    -
    -

    The DSL for messaging looks a little bit different than the one that focuses on HTTP.

    -
    -
    -
    Output triggered by a method
    -
    -

    The output message can be triggered by calling a method (e.g. a Scheduler was started and a message was sent)

    -
    -
    def dsl = Contract.make {
    +
    That way all:
    +
    +- all your requests in the autogenerated tests will be sent to the real endpoint with your context path included (e.g. `/my-context-path/url`)
    +- your contracts reflect that you have a context path, thus your generated stubs will also
    + have that information (e.g. in the stubs you'll see that you have too call `/my-context-path/url`)
    +
    +==== Messaging Top-Level Elements
    +
    +The DSL for messaging looks a little bit different than the one that focuses on HTTP.
    +
    +===== Output triggered by a method
    +
    +The output message can be triggered by calling a method (e.g. a Scheduler was started and a message was sent)
    +
    +[source,groovy]
    +
    +
    +
    +

    def dsl = Contract.make { // Human readable description description 'Some description' // Label by means of which the output message can be triggered @@ -7291,22 +6821,22 @@ have that information (e.g. in the stubs you’ll see that you have too call header('BOOK-NAME', 'foo') } } -} -

    -
    -
    -

    In this case the output message will be sent to output if a method called bookReturnedTriggered will be executed. In the message publisher’s side -we will generate a test that will call 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.

    +}

    -
    def dsl = Contract.make {
    +
    In this case the output message will be sent to `output` if a method called `bookReturnedTriggered` will be executed. In the message *publisher's* side
    +we will generate a test that will call 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.
    +
    +[source,groovy]
    +
    +
    +
    +

    def dsl = Contract.make { description 'Some Description' label 'some_label' // input is a message @@ -7331,24 +6861,24 @@ we will generate a test that will call that method to trigger the message. On th header('BOOK-NAME', 'foo') } } -} -

    -
    -
    -

    In this case the output message will be sent to output if a proper message will be received on the input destination. In the message publisher’s side -we will generate a test that will send the input message to the defined destination. On the consumer side you can either send a message to the input -destination or use the some_label to trigger the message.

    -
    - -
    -
    Consumer / Producer
    -
    -

    In HTTP you have a notion of client/stub and `server/test notation. You can use them also in messaging but we’re providing also the consumer and produer methods -as presented below (note you can use either $ or value methods to provide consumer and producer parts)

    +}

    -
    Contract.make {
    +
    In this case the output message will be sent to `output` if a proper message will be received on the `input` destination. In the message *publisher's* side
    +we will generate a test that will send the input message to the defined destination. On the *consumer* side you can either send a message to the input
    +destination or use the `some_label` to trigger the message.
    +
    +===== Consumer / Producer
    +
    +In HTTP you have a notion of `client`/`stub and `server`/`test` notation. You can use them also in messaging but we're providing also the `consumer` and `produer` methods
    +as presented below (note you can use either `$` or `value` methods to provide `consumer` and `producer` parts)
    +
    +[source,groovy]
    +
    +
    +
    +

    Contract.make { label 'some_label' input { messageFrom value(consumer('jms:output'), producer('jms:input')) @@ -7365,21 +6895,22 @@ as presented below (note you can use either $ or value bookName: 'foo' ]) } -} -

    -
    - - -
    -

    Multiple contracts in one file

    -
    -

    It’s possible to define multiple contracts in one file. An example of such a contract can look like this

    +}

    -
    import org.springframework.cloud.contract.spec.Contract
    +
    ==== Multiple contracts in one file
     
    -[
    +It's possible to define multiple contracts in one file. An example of such a contract can look like this
    +
    +[source,groovy,indent=0]
    +
    +
    +
    +

    import org.springframework.cloud.contract.spec.Contract

    +
    +
    +

    [ Contract.make { name("should post a user") request { @@ -7399,131 +6930,138 @@ as presented below (note you can use either $ or value status 200 } } -] -

    -
    -
    -

    In this example one contract has the name field and the other doesn’t. This will lead to generation of -two tests that will look more or less like this:

    +]

    -
    package org.springframework.cloud.contract.verifier.tests.com.hello;
    +
    In this example one contract has the `name` field and the other doesn't. This will lead to generation of
    +two tests that will look more or less like this:
     
    -import com.example.TestBase;
    +[source,java,indent=0]
    +
    +
    +
    +

    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 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); - } - -} +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 doesn’t have the name it’s 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 will look like this

    +

    }

    -
    should post a user.json
    -1_WithList.json
    +
    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 doesn't have the name it's 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 will look like this
    +
    +[source]
    -

    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 -contract had index 1 in the list of contracts in the file).

    +

    should post a user.json +1_WithList.json

    -
    - - - - - -
    -
    Tip
    -
    -As you can see it’s much better if you name your contracts since then your tests +
    +
    +
    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
    +contract had index `1` in the list of contracts in the file).
    +
    +TIP: As you can see it's much better if you name your contracts since then your tests
      are far more meaningful.
    -
    -
    - - -
    -

    Customization

    -
    -

    Extending the DSL

    -
    -

    It is possible to provide your own functions to the DSL. The key requirement for this + + +=== Customization + +==== Extending the DSL + +It is possible to provide your own functions to the DSL. The key requirement for this feature was to maintain the static compatibility. Below you will be able to see an example -of:

    -
    -
    -
      -
    • -

      creation of a JAR with reusable classes

      -
    • -
    • -

      referencing of these classes in the DSLs

      -
    • -
    -
    -
    -

    The full example can be found here.

    -
    -
    -
    Common JAR
    -
    -

    Below you can find three classes that we will reuse in the DSLs.

    -
    -
    -

    PatternUtils contains functions used by both the consumer and the producer.

    -
    -
    -
    -
    package com.example;
    +of:
     
    -import java.util.regex.Pattern;
    +- creation of a JAR with reusable classes
    +- referencing of these classes in the DSLs
     
    -/**
    +The full example can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here].
    +
    +===== Common JAR
    +
    +Below you can find three classes that we will reuse in the DSLs.
    +
    +*PatternUtils* contains functions used by both the **consumer** and the **producer**.
    +
    +[source,java]
    +
    +
    +
    +

    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. @@ -7537,7 +7075,7 @@ import java.util.regex.Pattern; * } * </pre> * - * Notice that we're using both {@code $()} for dynamic values + * Notice that we’re using both {@code $()} for dynamic values * and {@code c()} for the consumer side. * * @author Marcin Grzejszczak @@ -7545,37 +7083,50 @@ import java.util.regex.Pattern; public class PatternUtils { public static Pattern tooYoung() { return Pattern.compile("[0-1][0-9]"); - } - - public static Pattern oldEnough() { - return Pattern.compile("[2-9][0-9]"); - } - - public static Pattern anyName() { - return Pattern.compile("[a-zA-Z]+"); - } - - /** + }

    +
    +
    +
    +
    public static Pattern oldEnough() {
    +	return Pattern.compile("[2-9][0-9]");
    +}
    +
    +
    +
    +
    +
    public static Pattern anyName() {
    +	return Pattern.compile("[a-zA-Z]+");
    +}
    +
    +
    +
    +
    +
    	/**
     	 * Makes little sense but it's just an example ;)
     	 */
     	public static Pattern ok() {
     		return Pattern.compile("OK");
     	}
    -}
    +}
    -
    -

    ConsumerUtils contains functions used by the consumer.

    -
    -
    package com.example;
    +
    *ConsumerUtils* contains functions used by the **consumer**.
     
    -import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
    -import org.springframework.cloud.contract.spec.internal.DslProperty;
    -
    -/**
    - * DSL Properties passed to the DSL from the consumer's perspective.
    +[source,java]
    +
    +
    +
    +

    package com.example;

    +
    +
    +

    import org.springframework.cloud.contract.spec.internal.ClientDslProperty; +import org.springframework.cloud.contract.spec.internal.DslProperty;

    +
    +
    +

    / + * 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 @@ -7584,7 +7135,7 @@ import org.springframework.cloud.contract.spec.internal.DslProperty; * @author Marcin Grzejszczak */ 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 @@ -7605,9 +7156,11 @@ public class ConsumerUtils { */ public static ClientDslProperty oldEnough() { return new ClientDslProperty(PatternUtils.oldEnough()); - } - - /** + }

    +
    +
    +
    +
    	/**
     	 * Consumer side property. By using the {@link ClientDslProperty}
     	 * you can omit most of boilerplate code from the perspective
     	 * of dynamic values. Example
    @@ -7627,20 +7180,25 @@ public class ConsumerUtils {
     	public static DslProperty anyName() {
     		return new DslProperty<>(PatternUtils.anyName(), "marcin");
     	}
    -}
    +}
    -
    -

    ProducerUtils contains functions used by the producer.

    -
    -
    package com.example;
    +
    *ProducerUtils* contains functions used by the **producer**.
     
    -import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
    -
    -/**
    - * DSL Properties passed to the DSL from the producer's perspective.
    +[source,java]
    +
    +
    +
    +

    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 @@ -7648,9 +7206,11 @@ import org.springframework.cloud.contract.spec.internal.ServerDslProperty; * * @author Marcin Grzejszczak */ -public class ProducerUtils { - - /** +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
    @@ -7670,84 +7230,118 @@ public class ProducerUtils {
     	public static ServerDslProperty ok() {
     		return new ServerDslProperty(PatternUtils.ok());
     	}
    -}
    +}
    -
    -
    -
    Adding the dependency to 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 dependency in project’s dependencies
    -
    -

    First add the common jar dependency as a test dependency. That way since your -contracts files are available at test resources path, automatically the -common jar classes will be visible in your Groovy files.

    -
    -
    -
    Maven
    +
    -
    <dependency>
    +
    ===== Adding the dependency to 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 dependency in project's dependencies
    +
    +First add the common jar dependency as a test dependency. That way since your
    +contracts files are available at test resources path, automatically the
    +common jar classes will be visible in your Groovy files.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.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-SNAPSHOT")
    -
    -
    -
    -
    -
    Test dependency in plugin’s dependencies
    -
    -

    Now you have to add the dependency for the plugin to reuse at runtime.

    -
    -
    -
    Maven
    -
    -
    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/pom.xml[tags=test_dep_in_plugin,indent=0]
    -
    -
    -
    -
    Gradle
    -
    -
    classpath "com.example:beer-common:0.0.1-SNAPSHOT"
    -
    -
    -
    -
    -
    Referencing classes in DSLs
    -
    -

    Now you can reference your classes in your DSL. Example:

    +</dependency>

    -
    package contracts.beer.rest
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    testCompile("com.example:beer-common:0.0.1-SNAPSHOT")

    +
    +
    +
    +
    ====== Test dependency in plugin's dependencies
     
    -import org.springframework.cloud.contract.spec.Contract
    +Now you have to add the dependency for the plugin to reuse at runtime.
     
    -import static com.example.ConsumerUtils.oldEnough
    -import static com.example.ProducerUtils.ok
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.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> + </configuration> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-verifier</artifactId> + <version>${spring-cloud-contract.version}</version> + </dependency> + <dependency> + <groupId>com.example</groupId> + <artifactId>beer-common</artifactId> + <version>${project.version}</version> + <scope>compile</scope> + </dependency> + </dependencies> +</plugin>

    +
    +
    +
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    classpath "com.example:beer-common:0.0.1-SNAPSHOT"

    +
    +
    +
    +
    ====== Referencing classes in DSLs
     
    -Contract.make {
    +Now you can reference your classes in your DSL. Example:
    +
    +[source,groovy]
    +
    +
    +
    +

    package contracts.beer.rest

    +
    +
    +

    import org.springframework.cloud.contract.spec.Contract

    +
    +
    +

    import static com.example.ConsumerUtils.oldEnough +import static com.example.ProducerUtils.ok

    +
    +
    +

    Contract.make { request { description(""" -Represents a successful scenario of getting a beer - -given: +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 + we’ll grant him the beer """) method 'POST' url '/check' @@ -7769,31 +7363,28 @@ then: contentType(applicationJson()) } } -} -

    -
    -
    -
    -
    - -
    -

    Pluggable architecture

    -
    -

    There are cases where you have your contracts defined in other formats -like YAML, RAML or PACT. On the other hand you’d like to profit from -the test and stubs generation. It’s really easy to add your own implementation -of either of those. Also you can customize the way tests are generated (for example you can generate -tests for other languages) and you can do the same for stubs generation (you can generate -stubs for other stub http server implementations).

    -
    -
    -

    Custom contract converter

    -
    -

    Let’s assume that your contract is written in a YAML file like this:

    +}

    -
    request:
    +
    === Pluggable architecture
    +
    +There are cases where you have your contracts defined in other formats
    +like YAML, RAML or PACT. On the other hand you'd like to profit from
    +the test and stubs generation. It's really easy to add your own implementation
    +of either of those. Also you can customize the way tests are generated (for example you can generate
    +tests for other languages) and you can do the same for stubs generation (you can generate
    +stubs for other stub http server implementations).
    +
    +==== Custom contract converter
    +
    +Let's assume that your contract is written in a YAML file like this:
    +
    +[source,yml]
    +
    +
    +
    +

    request: url: /foo method: PUT headers: @@ -7805,17 +7396,20 @@ response: headers: foo2: bar body: - foo2: bar -

    -
    -
    -

    Thanks to the interface

    + foo2: bar

    -
    package org.springframework.cloud.contract.spec
    +
    Thanks to the interface
     
    -/**
    +[source,groovy]
    +
    +
    +
    +

    package org.springframework.cloud.contract.spec

    +
    +
    +

    /** * Converter to be used to convert FROM {@link File} TO {@link Contract} * and from {@link Contract} to {@code T} * @@ -7824,120 +7418,137 @@ response: * @author Marcin Grzejszczak * @since 1.1.0 */ -interface ContractConverter<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) - - /** +interface ContractConverter<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)
    -}
    +}
    -
    -

    you can register your own implementation of a contract structure converter. +

    +
    +
    you can register your own implementation of a contract structure converter.
     Your implementation needs to state the condition on which it should start the
    -conversion. Also you have to define how to perform that conversion in both ways.

    -
    -
    - - - - - -
    -
    Important
    -
    -Once you create your implementation you have to create a /META-INF/spring.factories -file in which you provide the fully qualified name of your implementation. -
    -
    -
    -

    Example of a spring.factories file

    -
    -
    -
    -
    # Converters
    -org.springframework.cloud.contract.spec.ContractConverter=\
    -org.springframework.cloud.contract.verifier.converter.YamlContractConverter
    -
    -
    -
    -

    and the YAML implementation

    -
    -
    -
    -
    package org.springframework.cloud.contract.verifier.converter
    +conversion. Also you have to define how to perform that conversion in both ways.
     
    -import groovy.transform.CompileStatic
    +IMPORTANT: Once you create your implementation you have to create a `/META-INF/spring.factories`
    +file in which you provide the fully qualified name of your implementation.
    +
    +Example of a `spring.factories` file
    +
    +[source]
    +
    +
    +
    +
    +
    + + +

    Converters

    +
    +

    org.springframework.cloud.contract.spec.ContractConverter=\ +org.springframework.cloud.contract.verifier.converter.YamlContractConverter

    +
    +
    +
    +
    and the YAML implementation
    +
    +[source,groovy]
    +
    +
    +
    +

    package org.springframework.cloud.contract.verifier.converter

    +
    +
    +

    import groovy.transform.CompileStatic import org.springframework.cloud.contract.spec.Contract import org.springframework.cloud.contract.spec.ContractConverter import org.springframework.cloud.contract.spec.internal.Headers -import org.yaml.snakeyaml.Yaml - -/** +import org.yaml.snakeyaml.Yaml

    +
    +
    +

    /** * Simple converter from and to a {@link YamlContract} to a collection of {@link Contract} */ @CompileStatic -class YamlContractConverter implements ContractConverter<List<YamlContract>> { - - @Override - public boolean isAccepted(File file) { - String name = file.getName() - return name.endsWith(".yml") || name.endsWith(".yaml") - } - - @Override - public Collection<Contract> convertFrom(File file) { - try { - YamlContract yamlContract = new Yaml().loadAs(new FileInputStream(file), YamlContract.class) - return [Contract.make { - request { - method(yamlContract?.request?.method) - url(yamlContract?.request?.url) - headers { - yamlContract?.request?.headers?.each { String key, Object value -> - header(key, value) - } +class YamlContractConverter implements ContractConverter<List<YamlContract>> {

    +
    +
    +
    +
    @Override
    +public boolean isAccepted(File file) {
    +	String name = file.getName()
    +	return name.endsWith(".yml") || name.endsWith(".yaml")
    +}
    +
    +
    +
    +
    +
    @Override
    +public Collection<Contract> convertFrom(File file) {
    +	try {
    +		YamlContract yamlContract = new Yaml().loadAs(new FileInputStream(file), YamlContract.class)
    +		return [Contract.make {
    +			request {
    +				method(yamlContract?.request?.method)
    +				url(yamlContract?.request?.url)
    +				headers {
    +					yamlContract?.request?.headers?.each { String key, Object value ->
    +						header(key, value)
     					}
    -					body(yamlContract?.request?.body)
     				}
    -				response {
    -					status(yamlContract?.response?.status)
    -					headers {
    -						yamlContract?.response?.headers?.each { String key, Object value ->
    -							header(key, value)
    -						}
    +				body(yamlContract?.request?.body)
    +			}
    +			response {
    +				status(yamlContract?.response?.status)
    +				headers {
    +					yamlContract?.response?.headers?.each { String key, Object value ->
    +						header(key, value)
     					}
    -					body(yamlContract?.response?.body)
     				}
    -			}]
    -		}
    -		catch (FileNotFoundException e) {
    -			throw new IllegalStateException(e)
    -		}
    +				body(yamlContract?.response?.body)
    +			}
    +		}]
     	}
    -
    -	@Override
    +	catch (FileNotFoundException e) {
    +		throw new IllegalStateException(e)
    +	}
    +}
    +
    +
    +
    +
    +
    	@Override
     	public List<YamlContract> convertTo(Collection<Contract> contracts) {
     		return contracts.collect { Contract contract ->
     			YamlContract yamlContract = new YamlContract()
    @@ -7955,25 +7566,27 @@ class YamlContractConverter implements ContractConverter<List<YamlContract
     			return yamlContract
     		}
     	}
    -}
    +}
    -
    -
    Pact converter
    -
    -

    Spring Cloud Contract comes with an out of the box support for Pact representation of contracts. -In other words instead of using the Groovy DSL you can use Pact files. In this section -we will present how to add such a support for your project.

    -
    -
    -
    Pact contract
    -
    -

    We will be working on the following example of a Pact contract. We’ve placed this file under -the src/test/resources/contracts folder.

    -
    -
    {
    +
    ===== Pact converter
    +
    +Spring Cloud Contract comes with an out of the box support for https://docs.pact.io/[Pact] representation of contracts.
    +In other words instead of using the Groovy DSL you can use Pact files. In this section
    +we will present how to add such a support for your project.
    +
    +====== Pact contract
    +
    +We will be working on the following example of a Pact contract. We've placed this file under
    +the `src/test/resources/contracts` folder.
    +
    +[source,javascript,indent=0]
    +
    +
    +
    +

    { "provider": { "name": "Provider" }, @@ -8026,21 +7639,22 @@ the src/test/resources/contracts folder.

    "version": "2.4.18" } } -}
    +}

    -
    -
    -
    -
    Pact for producers
    -
    -

    On the producer side you have add to your plugin configuration two additional dependencies. -One is the Spring Cloud Contract Pact support and the other represents the current -Pact version that you’re using.

    -
    -
    -
    Maven
    +
    -
    <plugin>
    +
    ====== Pact for producers
    +
    +On the producer side you have add to your plugin configuration two additional dependencies.
    +One is the Spring Cloud Contract Pact support and the other represents the current
    +Pact version that you're using.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.Maven
    +
    +
    +
    +

    <plugin> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-maven-plugin</artifactId> <version>${spring-cloud-contract.version}</version> @@ -8060,33 +7674,45 @@ Pact version that you’re using.

    <version>2.4.18</version> </dependency> </dependencies> -</plugin>
    -
    -
    -
    -
    Gradle
    -
    -
    classpath "org.springframework.cloud:spring-cloud-contract-spec-pact:${findProperty('verifierVersion') ?: verifierVersion}"
    -classpath 'au.com.dius:pact-jvm-model:2.4.18'
    -
    -
    -
    -

    When you execute the build of your application a test, looking more or less like this, will be generated

    +</plugin>

    -
    @Test
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    classpath "org.springframework.cloud:spring-cloud-contract-spec-pact:${findProperty('verifierVersion') ?: verifierVersion}" +classpath 'au.com.dius:pact-jvm-model:2.4.18'

    +
    +
    +
    +
    When you execute the build of your application a test, looking more or less like this, will be generated
    +
    +[source,java,indent=0]
    +
    +
    +
    +
    +
    @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:
    +				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
    +
    +
    +
    +
    +
    // when:
    +	ResponseOptions response = given().spec(request)
    +			.put("/fraudcheck");
    +
    +
    +
    +
    +
    	// then:
     		assertThat(response.statusCode()).isEqualTo(200);
     		assertThat(response.header("Content-Type")).isEqualTo("application/vnd.fraud.v1+json;charset=UTF-8");
     	// and:
    @@ -8094,15 +7720,18 @@ public void validate_shouldMarkClientAsFraud() throws Exception {
     		assertThatJson(parsedJson).field("rejectionReason").isEqualTo("Amount too high");
     	// and:
     		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
    -}
    +}
    -
    -

    and the stub looking like this

    -
    -
    {
    +
    and the stub looking like this
    +
    +[source,javascript,indent=0]
    +
    +
    +
    +

    { "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62", "request" : { "url" : "/fraudcheck", @@ -8125,21 +7754,22 @@ public void validate_shouldMarkClientAsFraud() throws Exception { "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8" } } -} +}

    -
    - -
    -
    Pact for consumers
    -
    -

    On the producer side you have add to your project dependencies two additional dependencies. -One is the Spring Cloud Contract Pact support and the other represents the current -Pact version that you’re using.

    -
    -
    -
    Maven
    +
    -
    <dependency>
    +
    ====== Pact for consumers
    +
    +On the producer side you have add to your project dependencies two additional dependencies.
    +One is the Spring Cloud Contract Pact support and the other represents the current
    +Pact version that you're using.
    +
    +[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    +.Maven
    +
    +
    +
    +

    <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-contract-spec-pact</artifactId> <scope>test</scope> @@ -8149,46 +7779,51 @@ Pact version that you’re using.

    <artifactId>pact-jvm-model</artifactId> <version>2.4.18</version> <scope>test</scope> -</dependency>
    -
    -
    -
    -
    Gradle
    -
    -
    testCompile "org.springframework.cloud:spring-cloud-contract-spec-pact"
    -testCompile 'au.com.dius:pact-jvm-model:2.4.18'
    -
    -
    -
    - - -
    -

    Custom test generator

    -
    -

    If you want to generate tests for different languages than Java or you’re -not happy with the way we’re building Java tests for you then you can register -your own implementation to do that.

    -
    -
    -

    Thanks to the interface

    +</dependency>

    -
    package org.springframework.cloud.contract.verifier.builder
    +
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    +.Gradle
    +
    +
    +
    +

    testCompile "org.springframework.cloud:spring-cloud-contract-spec-pact" +testCompile 'au.com.dius:pact-jvm-model:2.4.18'

    +
    +
    +
    +
    ==== Custom test generator
     
    -import groovy.transform.CompileStatic
    +If you want to generate tests for different languages than Java or you're
    +not happy with the way we're building Java tests for you then you can register
    +your own implementation to do that.
    +
    +Thanks to the interface
    +
    +[source,groovy]
    +
    +
    +
    +

    package org.springframework.cloud.contract.verifier.builder

    +
    +
    +

    import groovy.transform.CompileStatic import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties -import org.springframework.cloud.contract.verifier.file.ContractMetadata - -/** +import org.springframework.cloud.contract.verifier.file.ContractMetadata

    +
    +
    +

    /** * Builds a single test. * * @since 1.1.0 */ @CompileStatic -interface SingleTestGenerator { - - /** +interface SingleTestGenerator {

    +
    +
    +
    +
    	/**
     	 * Creates contents of a single test class in which all test scenarios from
     	 * the contract metadata should be placed.
     	 *
    @@ -8201,54 +7836,68 @@ interface SingleTestGenerator {
     	 */
     	String buildClass(ContractVerifierConfigProperties properties, Collection<ContractMetadata> listOfFiles,
     					  String className, String classPackage, String includedDirectoryRelativePath)
    -}
    +}
    -
    -

    you can register your own implementation that generates a test. Again, it’s enough to provide -a proper spring.factories file. Example:

    -
    -
    org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
    -com.example.MyGenerator
    -
    -
    -
    -
    -

    Custom stub generator

    -
    -

    If you want to generate stubs for other stub server than WireMock it’s enough to - plug in your own implementation of this interface:

    -
    -
    -
    -
    package org.springframework.cloud.contract.verifier.converter
    +
    you can register your own implementation that generates a test. Again, it's enough to provide
    +a proper `spring.factories` file. Example:
     
    -import groovy.transform.CompileStatic
    +[source]
    +
    +
    +
    +

    org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ +com.example.MyGenerator

    +
    +
    +
    +
    ==== Custom stub generator
    +
    +If you want to generate stubs for other stub server than WireMock it's enough to
    + plug in your own implementation of this interface:
    +
    +[source,groovy]
    +
    +
    +
    +

    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 - -/** +import org.springframework.cloud.contract.verifier.file.ContractMetadata

    +
    +
    +

    /** * Converts contracts into their stub representation. * * @since 1.1.0 */ @CompileStatic -interface StubGenerator { - - /** - * Returns {@code true} if the converter can handle the file to convert it into a stub. - */ - boolean canHandleFileName(String fileName) - - /** - * Returns the collection of converted contracts into stubs. One contract can - * result in multiple stubs. - */ - Map<Contract, String> convertContents(String rootName, ContractMetadata content) - - /** +interface StubGenerator {

    +
    +
    +
    +
    /**
    + * Returns {@code true} if the converter can handle the file to convert it into a stub.
    + */
    +boolean canHandleFileName(String fileName)
    +
    +
    +
    +
    +
    /**
    + * Returns the collection of converted contracts into stubs. One contract can
    + * result in multiple stubs.
    + */
    +Map<Contract, String> convertContents(String rootName, ContractMetadata content)
    +
    +
    +
    +
    +
    	/**
     	 * Returns 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
    @@ -8259,220 +7908,246 @@ interface StubGenerator {
     	 * converter will create two files {@code 0_foo.json} and {@code 1_foo.json}
     	 */
     	String generateOutputFileNameForInput(String inputFileName)
    -}
    +}
    -
    -

    you can register your own implementation that generate Stubs. Again, it’s enough to provide -a proper spring.factories file. 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.

    -
    -
    - - - - - -
    -
    Tip
    -
    -You can provide multiple stub generator implementations. That way for example from a single -DSL as input you can e.g. produce WireMock stubs and Pact files too! -
    -
    -
    -
    -

    Custom Stub Runner

    -
    -

    If you decide to have a custom stub generation you also need a custom way of running -stubs with your different stub provider.

    -
    -
    -

    Let us assume that you’re using Moco to build your stubs. -You wrote a proper stub generator and your stubs got placed 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. It can look like this:

    -
    -
    -
    -
    package org.springframework.cloud.contract.stubrunner.provider.moco
    +
    you can register your own implementation that generate Stubs. Again, it's enough to provide
    +a proper `spring.factories` file. Example:
     
    -import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
    +[source]
    +
    +
    +

    Stub converters

    +
    +

    org.springframework.cloud.contract.verifier.converter.StubGenerator=\ +org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter

    +
    +
    +
    +
    The default implementation is the WireMock stub generation.
    +
    +TIP: You can provide multiple stub generator implementations. That way for example from a single
    +DSL as input you can e.g. produce WireMock stubs and Pact files too!
    +
    +==== Custom Stub Runner
    +
    +If you decide to have a custom stub generation you also need a custom way of running
    +stubs with your different stub provider.
    +
    +Let us assume that you're using https://github.com/dreamhead/moco[Moco] to build your stubs.
    +You wrote a proper stub generator and your stubs got placed 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. It can look like this:
    +
    +[source,groovy]
    +
    +
    +
    +

    package org.springframework.cloud.contract.stubrunner.provider.moco

    +
    +
    +

    import com.github.dreamhead.moco.bootstrap.arg.HttpArgs import com.github.dreamhead.moco.runner.JsonRunner import org.springframework.cloud.contract.stubrunner.HttpServerStub -import org.springframework.util.SocketUtils - -class MocoHttpServerStub implements HttpServerStub { - - private boolean started - private JsonRunner runner - private int port - - @Override - int port() { - if (!isRunning()) { - return -1 - } - return port +import org.springframework.util.SocketUtils

    +
    +
    +

    class MocoHttpServerStub implements HttpServerStub {

    +
    +
    +
    +
    private boolean started
    +private JsonRunner runner
    +private int port
    +
    +
    +
    +
    +
    @Override
    +int port() {
    +	if (!isRunning()) {
    +		return -1
     	}
    -
    -	@Override
    -	boolean isRunning() {
    -		return started
    -	}
    -
    -	@Override
    -	HttpServerStub start() {
    -		return start(SocketUtils.findAvailableTcpPort())
    -	}
    -
    -	@Override
    -	HttpServerStub start(int port) {
    -		this.port = port
    +	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
     	}
    -
    -	@Override
    -	HttpServerStub stop() {
    -		if (!isRunning()) {
    -			return this
    -		}
    -		this.runner.stop()
    -		return this
    -	}
    -
    -	@Override
    -	HttpServerStub registerMappings(Collection<File> stubFiles) {
    -		List<InputStream> streams = stubFiles.collect { it.newInputStream() }
    -		this.runner = JsonRunner.newJsonRunnerWithStreams(streams,
    -				HttpArgs.httpArgs().withPort(this.port).build())
    -		this.runner.run()
    -		this.started = true
    -		return this
    -	}
    -
    -	@Override
    +	this.runner.stop()
    +	return this
    +}
    +
    +
    +
    +
    +
    @Override
    +HttpServerStub registerMappings(Collection<File> stubFiles) {
    +	List<InputStream> streams = stubFiles.collect { it.newInputStream() }
    +	this.runner = JsonRunner.newJsonRunnerWithStreams(streams,
    +			HttpArgs.httpArgs().withPort(this.port).build())
    +	this.runner.run()
    +	this.started = true
    +	return this
    +}
    +
    +
    +
    +
    +
    	@Override
     	boolean isAccepted(File file) {
     		return file.name.endsWith(".json")
     	}
    -}
    +}
    -
    -

    and just register it in your spring.factories file

    -
    -
    # Example of a custom HTTP Server Stub
    -org.springframework.cloud.contract.stubrunner.HttpServerStub=\
    -org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
    -
    -
    -
    -

    that way you’ll be able to run stubs using Moco.

    -
    -
    - - - - - -
    -
    Important
    -
    -If you don’t provide any implementation then the default one - WireMock based -will be picked. If you provide more than one then the first one on the list will be picked. -
    -
    -
    -
    -

    Custom Stub Downloader

    -
    -

    You can customize the way your stubs are downloaded. If you don’t want to download the JARs -from Nexus / Artifactory in the way we do by default you can set your own implementation. -Below you can find an example of a Stub Downloader Provider that takes json files from the test resources -from classpath, copies them to a temp file and then passes that temporary folder - as a root for the stubs.

    -
    -
    -
    -
    package org.springframework.cloud.contract.stubrunner.provider.moco
    +
    and just register it in your `spring.factories` file
     
    -import org.springframework.cloud.contract.stubrunner.StubConfiguration
    +[source]
    +
    +
    +

    Example of a custom HTTP Server Stub

    +
    +

    org.springframework.cloud.contract.stubrunner.HttpServerStub=\ +org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub

    +
    +
    +
    +
    that way you'll be able to run stubs using Moco.
    +
    +IMPORTANT: If you don't provide any implementation then the default one - WireMock based
    +will be picked. If you provide more than one then the first one on the list will be picked.
    +
    +==== Custom Stub Downloader
    +
    +You can customize the way your stubs are downloaded. If you don't want to download the JARs
    +from Nexus / Artifactory in the way we do by default you can set your own implementation.
    +Below you can find an example of a Stub Downloader Provider that takes `json` files from the test resources
    +from classpath, copies them to a temp file and then passes that temporary folder
    + as a root for the stubs.
    +
    +[source,java]
    +
    +
    +
    +

    package org.springframework.cloud.contract.stubrunner.provider.moco

    +
    +
    +

    import org.springframework.cloud.contract.stubrunner.StubConfiguration import org.springframework.cloud.contract.stubrunner.StubDownloader import org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder import org.springframework.cloud.contract.stubrunner.StubRunnerOptions import org.springframework.core.io.DefaultResourceLoader import org.springframework.core.io.Resource -import org.springframework.core.io.support.PathMatchingResourcePatternResolver - -import java.nio.file.Files - -/** - * Poor man's version of taking stubs from classpath. It needs much more +import org.springframework.core.io.support.PathMatchingResourcePatternResolver

    +
    +
    +

    import java.nio.file.Files

    +
    +
    +

    /** + * Poor man’s version of taking stubs from classpath. It needs much more * love and attention to go to the main sources. * * @author Marcin Grzejszczak */ -class ClasspathStubProvider implements StubDownloaderBuilder { - - private static final int TEMP_DIR_ATTEMPTS = 10000 - - @Override - public StubDownloader build(StubRunnerOptions stubRunnerOptions) { - final StubConfiguration configuration = stubRunnerOptions.getDependencies().first() - PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( - new DefaultResourceLoader()) - try { - String rootFolder = repoRoot(stubRunnerOptions) ?: "**/" + separatedArtifact(configuration) + "/**/*.json" - Resource[] resources = resolver.getResources(rootFolder) - final File tmp = createTempDir() - tmp.deleteOnExit() - // you'd have to write an impl to maintain the folder structure - // this is just for demo - resources.each { Resource resource -> - Files.copy(resource.getInputStream(), new File(tmp, resource.getFile().getName()).toPath()) - } - return new StubDownloader() { - @Override - public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar( - StubConfiguration stubConfiguration) { - return new AbstractMap.SimpleEntry(configuration, tmp) - } - } - } catch (IOException e) { - throw new IllegalStateException(e) +class ClasspathStubProvider implements StubDownloaderBuilder {

    +
    +
    +
    +
    private static final int TEMP_DIR_ATTEMPTS = 10000
    +
    +
    +
    +
    +
    @Override
    +public StubDownloader build(StubRunnerOptions stubRunnerOptions) {
    +	final StubConfiguration configuration = stubRunnerOptions.getDependencies().first()
    +	PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
    +			new DefaultResourceLoader())
    +	try {
    +		String rootFolder = repoRoot(stubRunnerOptions) ?: "**/" + separatedArtifact(configuration) + "/**/*.json"
    +		Resource[] resources = resolver.getResources(rootFolder)
    +		final File tmp = createTempDir()
    +		tmp.deleteOnExit()
    +		// you'd have to write an impl to maintain the folder structure
    +		// this is just for demo
    +		resources.each { Resource resource ->
    +			Files.copy(resource.getInputStream(), new File(tmp, resource.getFile().getName()).toPath())
     		}
    -	}
    -
    -	private String repoRoot(StubRunnerOptions stubRunnerOptions) {
    -		switch (stubRunnerOptions.stubRepositoryRoot) {
    -			case { !it }:
    -				return ""
    -			case { String root -> root.endsWith("**/*.json") }:
    -				return stubRunnerOptions.stubRepositoryRoot
    -			default:
    -				return stubRunnerOptions.stubRepositoryRoot + "/**/*.json"
    +		return new StubDownloader() {
    +			@Override
    +			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
    +					StubConfiguration stubConfiguration) {
    +				return new AbstractMap.SimpleEntry(configuration, tmp)
    +			}
     		}
    +	} catch (IOException e) {
    +		throw new IllegalStateException(e)
     	}
    -
    -	private String separatedArtifact(StubConfiguration configuration) {
    -		return configuration.getGroupId().replace(".", File.separator) +
    -				File.separator + configuration.getArtifactId()
    +}
    +
    +
    +
    +
    +
    private String repoRoot(StubRunnerOptions stubRunnerOptions) {
    +	switch (stubRunnerOptions.stubRepositoryRoot) {
    +		case { !it }:
    +			return ""
    +		case { String root -> root.endsWith("**/*.json") }:
    +			return stubRunnerOptions.stubRepositoryRoot
    +		default:
    +			return stubRunnerOptions.stubRepositoryRoot + "/**/*.json"
     	}
    -
    -	// Taken from Guava
    +}
    +
    +
    +
    +
    +
    private String separatedArtifact(StubConfiguration configuration) {
    +	return configuration.getGroupId().replace(".", File.separator) +
    +			File.separator + configuration.getArtifactId()
    +}
    +
    +
    +
    +
    +
    	// Taken from Guava
     	private File createTempDir() {
     		File baseDir = new File(System.getProperty("java.io.tmpdir"))
     		String baseName = System.currentTimeMillis() + "-"
    @@ -8486,71 +8161,40 @@ class ClasspathStubProvider implements StubDownloaderBuilder {
     				"Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (
     						TEMP_DIR_ATTEMPTS - 1) + ")")
     	}
    -}
    +}
    -
    -

    and just register it in your spring.factories file

    -
    -
    # Example of a custom Stub Downloader Provider
    -org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
    -org.springframework.cloud.contract.stubrunner.provider.moco.ClasspathStubProvider
    +
    and just register it in your `spring.factories` file
    +
    +[source]
    +

    Example of a custom Stub Downloader Provider

    -

    that way you’ll be able to pick a folder with the source of your stubs.

    +

    org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ +org.springframework.cloud.contract.stubrunner.provider.moco.ClasspathStubProvider

    -
    - - - - - -
    -
    Important
    -
    -If you don’t provide any implementation then the default one - Aether based that will download stubs from a remote repo +
    +
    +
    that way you'll be able to pick a folder with the source of your stubs.
    +
    +IMPORTANT: If you don't provide any implementation then the default one - Aether based that will download stubs from a remote repo
     will be picked. If you provide more than one then the first one on the list will be picked.
    -
    -
    -
    - - + +=== Links + +Here you can find interesting links related to Spring Cloud Contract Verifier: + +- https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github Repository] +- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud Contract Samples] +- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud Contract Documentation] +- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest Legacy Documentation] +- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring Cloud Contract Stub Runner Documentation] +- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring Cloud Contract Stub Runner Messaging Documentation] +- https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] +- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin]