diff --git a/reference/html/README.html b/reference/html/README.html index c625cd0ba4..9990b6e5bb 100644 --- a/reference/html/README.html +++ b/reference/html/README.html @@ -1,680 +1,12 @@ - - - + + - - - -Spring Cloud Contract - - - - - - - - - -
-
-

Spring Cloud Contract

-
-
-

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

-
-
-

Spring Cloud Contract workshops

-
-

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

-
-
-
-
-
-

Project page

-
-
-

You can read more about Spring Cloud Contract by going to the project page

-
-
-
-
-

Contributing

-
-
-

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

-
-
-

Sign the Contributor License Agreement

-
-

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

-
-
-
-

Code of Conduct

-
-

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

-
-
-
-

Code Conventions and Housekeeping

-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-
-

Checkstyle

-
-

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

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

Checkstyle configuration

-
-

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

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

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

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

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

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

IDE setup

-
-

Intellij IDEA

-
-

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

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

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

-
-
-
-Code style -
-
Figure 2. Inspection profiles
-
-
-

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

-
-
-
Checkstyle
-

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

-
-
-
-Checkstyle -
-
-
-

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

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

How to Build Spring Cloud Contract

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

Project structure

-
-

The following listing shows the Spring Cloud Contract folder structure:

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

The following list describes each of the top-level folders in the project structure:

-
-
-
    -
  • -

    config: Folder contains setup for Spring Cloud Release Tools automated release process

    -
  • -
  • -

    docker: Folder contains docker images

    -
  • -
  • -

    samples: Folder contains test samples together with standalone ones used also to build documentation

    -
  • -
  • -

    scripts: Contains scripts to build and test Spring Cloud Contract with Maven, Gradle and standalone projects

    -
  • -
  • -

    specs: Contains specifications for the Contract DSL.

    -
  • -
  • -

    spring-cloud-contract-dependencies: Contains Spring Cloud Contract BOM

    -
  • -
  • -

    spring-cloud-contract-shade: Shaded dependencies used by the plugins

    -
  • -
  • -

    spring-cloud-contract-starters: Contains Spring Cloud Contract Starters

    -
  • -
  • -

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

    -
  • -
  • -

    spring-cloud-contract-stub-runner: Contains Stub Runner related modules

    -
  • -
  • -

    spring-cloud-contract-stub-runner-boot: Contains Stub Runner Boot app

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    spring-cloud-contract-wiremock: All WireMock related functionality

    -
  • -
  • -

    tests: Integration tests for different messaging technologies

    -
  • -
-
-
-
-

Commands

-
-

To build the core functionality together with the Maven Plugin, you can run the following -command:

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

Calling that function builds the core, the Maven plugin, and the Gradle plugin and runs -end-to_end tests on the -standalone samples in the proper order (both for Maven and Gradle).

-
-
-

To build only the Gradle Plugin, you can run the following commands:

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

Helpful scripts

-
-

We provide a couple of helpful scripts to build the project.

-
-
-

To build the project in parallel (by default, it uses four cores, but you can change it), -run the following command:

-
-
-
-
./scripts/parallelBuild.sh
-
-
-
-

To use eight 8 cores, run thke following command:

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

To build the project without any integration tests (by default, this uses one core), run -the following command:

-
-
-
-
./scripts/noIntegration.sh
-
-
-
-

To use eight cores, run the following command:

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

To generate the documentation (for both the root project and the maven plugin), run the -following command:

-
-
-
-
./scripts/generateDocs.sh
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/advanced.html b/reference/html/advanced.html index 35de793a89..9990b6e5bb 100644 --- a/reference/html/advanced.html +++ b/reference/html/advanced.html @@ -1,1206 +1,12 @@ - - - + + - - - -Spring Cloud Contract customization - - - - - - - - - -
-
-
-
-

In this section, we describe how to customize various parts of Spring Cloud Contract.

-
-
-
-
-

1. DSL Customization

-
-
- - - - - -
- - -This section is valid only for the Groovy DSL -
-
-
-

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in -the remainder of this section.

-
-
-

1.1. Extending the DSL

-
-

You can provide your own functions to the DSL. The key requirement for this feature is to -maintain the static compatibility. Later in this document, you can see examples of:

-
-
-
    -
  • -

    Creating a JAR with reusable classes.

    -
  • -
  • -

    Referencing of these classes in the DSLs.

    -
  • -
-
-
-

You can find the full example -here.

-
-
-
-

1.2. Common JAR

-
-

The following examples show three classes that can be reused in the DSLs.

-
-
-

PatternUtils contains functions used by both the consumer and the producer. -The following listing shows the PatternUtils class:

-
-
-
-
-
-
package com.example;
+Page Redirection
 
-import java.util.regex.Pattern;
-
-/**
- * If you want to use {@link Pattern} directly in your tests
- * then you can create a class resembling this one. It can
- * contain all the {@link Pattern} you want to use in the DSL.
- *
- * <pre>
- * {@code
- * request {
- *     body(
- *         [ age: $(c(PatternUtils.oldEnough()))]
- *     )
- * }
- * </pre>
- *
- * Notice that we're using both {@code $()} for dynamic values
- * and {@code c()} for the consumer side.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class PatternUtils {
-
-    public static String tooYoung() {
-        //remove::start[]
-        return "[0-1][0-9]";
-        //remove::end[return]
-    }
-
-    public static Pattern oldEnough() {
-        //remove::start[]
-        return Pattern.compile("[2-9][0-9]");
-        //remove::end[return]
-    }
-
-    /**
-     * Makes little sense but it's just an example ;)
-     */
-    public static Pattern ok() {
-        //remove::start[]
-        return Pattern.compile("OK");
-        //remove::end[return]
-    }
-}
-//end::impl[]
-
-
-
-
-
-

ConsumerUtils contains functions used by the consumer. -The following listing shows the ConsumerUtils class:

-
-
-
-
-
-
package com.example;
-
-import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
-
-/**
- * DSL Properties passed to the DSL from the consumer's perspective.
- * That means that on the input side {@code Request} for HTTP
- * or {@code Input} for messaging you can have a regular expression.
- * On the {@code Response} for HTTP or {@code Output} for messaging
- * you have to have a concrete value.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class ConsumerUtils {
-    /**
-     * Consumer side property. By using the {@link ClientDslProperty}
-     * you can omit most of boilerplate code from the perspective
-     * of dynamic values. Example
-     *
-     * <pre>
-     * {@code
-     * request {
-     *     body(
-     *         [ age: $(ConsumerUtils.oldEnough())]
-     *     )
-     * }
-     * </pre>
-     *
-     * That way it's in the implementation that we decide what value we will pass to the consumer
-     * and which one to the producer.
-     *
-     * @author Marcin Grzejszczak
-     */
-    public static ClientDslProperty oldEnough() {
-        //remove::start[]
-        // this example is not the best one and
-        // theoretically you could just pass the regex instead of `ServerDslProperty` but
-        // it's just to show some new tricks :)
-        return new ClientDslProperty(PatternUtils.oldEnough(), 40);
-        //remove::end[return]
-    }
-
-}
-//end::impl[]
-
-
-
-
-
-

ProducerUtils contains functions used by the producer. -The following listing shows the ProducerUtils class:

-
-
-
-
-
-
package com.example;
-
-import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
-
-/**
- * DSL Properties passed to the DSL from the producer's perspective.
- * That means that on the input side {@code Request} for HTTP
- * or {@code Input} for messaging you have to have a concrete value.
- * On the {@code Response} for HTTP or {@code Output} for messaging
- * you can have a regular expression.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class ProducerUtils {
-
-    /**
-     * Producer side property. By using the {@link ProducerUtils}
-     * you can omit most of boilerplate code from the perspective
-     * of dynamic values. Example
-     *
-     * <pre>
-     * {@code
-     * response {
-     *     body(
-     *         [ status: $(ProducerUtils.ok())]
-     *     )
-     * }
-     * </pre>
-     *
-     * That way it's in the implementation that we decide what value we will pass to the consumer
-     * and which one to the producer.
-     */
-    public static ServerDslProperty ok() {
-        // this example is not the best one and
-        // theoretically you could just pass the regex instead of `ServerDslProperty` but
-        // it's just to show some new tricks :)
-        return new ServerDslProperty( PatternUtils.ok(), "OK");
-    }
-}
-//end::impl[]
-
-
-
-
-
-
-

1.3. Adding a Test Dependency in the Project’s Dependencies

-
-

To add a test dependency in the project’s dependencies, you must first add the common jar -dependency as a test dependency. Because your contracts files -are available on the test resources path, the common jar classes automatically become -visible in your Groovy files. The following examples show how to test the dependency:

-
-
-
-
-
Maven
-
-
<dependency>
-    <groupId>com.example</groupId>
-    <artifactId>beer-common</artifactId>
-    <version>${project.version}</version>
-    <scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")
-
-
-
-
-
-
-

1.4. Adding a Test Dependency in the Plugin’s Dependencies

-
-

Now, you must add the dependency for the plugin to reuse at runtime, as the -following example shows:

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <packageWithBaseClasses>com.example</packageWithBaseClasses>
-        <baseClassMappings>
-            <baseClassMapping>
-                <contractPackageRegex>.*intoxication.*</contractPackageRegex>
-                <baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
-            </baseClassMapping>
-        </baseClassMappings>
-    </configuration>
-    <dependencies>
-        <dependency>
-            <groupId>com.example</groupId>
-            <artifactId>beer-common</artifactId>
-            <version>${project.version}</version>
-            <scope>compile</scope>
-        </dependency>
-    </dependencies>
-</plugin>
-
-
-
-
Gradle
-
-
classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"
-
-
-
-
-
-
-

1.5. Referencing Classes in DSLs

-
-

You can now reference your classes in your DSL, as the following example shows:

-
-
-
-
-
-
package contracts.beer.rest
-
-import com.example.ConsumerUtils
-import com.example.ProducerUtils
-import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-    description("""
-Represents a successful scenario of getting a beer
-
-```
-given:
-    client is old enough
-when:
-    he applies for a beer
-then:
-    we'll grant him the beer
-```
-
-""")
-    request {
-        method 'POST'
-        url '/check'
-        body(
-                age: $(ConsumerUtils.oldEnough())
-        )
-        headers {
-            contentType(applicationJson())
-        }
-    }
-    response {
-        status 200
-        body("""
-            {
-                "status": "${value(ProducerUtils.ok())}"
-            }
-            """)
-        headers {
-            contentType(applicationJson())
-        }
-    }
-}
-
-
-
-
-
- - - - - -
- - -You can set the Spring Cloud Contract plugin up by setting convertToYaml to -true. That way, you do NOT have to add the dependency with the extended functionality -to the consumer side, since the consumer side uses YAML contracts instead of Groovy contracts. -
-
-
-
-
-
-

2. WireMock Customization

-
-
-

In this section, we show how to customize the way you work with WireMock.

-
-
-

2.1. Registering Your Own WireMock Extension

-
-

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers -the transformer, which lets you reference a request from a response. If you want to -provide your own extensions, you can register an implementation of the -org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. -Since we use the spring.factories extension approach, you can create an entry in -META-INF/spring.factories file similar to the following:

-
-
-
-
-
-
org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
-org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
-org.springframework.cloud.contract.spec.ContractConverter=\
-org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter
-
-
-
-
-
-

The following example shows a custom extension:

-
-
-
Example 1. TestWireMockExtensions.groovy
-
-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.contract.verifier.dsl.wiremock
-
-import com.github.tomakehurst.wiremock.extension.Extension
-
-/**
- * Extension that registers the default transformer and the custom one
- */
-class TestWireMockExtensions implements WireMockExtensions {
-    @Override
-    List<Extension> extensions() {
-        return [
-                new DefaultResponseTransformer(),
-                new CustomExtension()
-        ]
-    }
-}
-
-class CustomExtension implements Extension {
-
-    @Override
-    String getName() {
-        return "foo-transformer"
-    }
-}
-
-
-
-
-
- - - - - -
- - -Remember to override the applyGlobally() method and set it to false if you -want the transformation to be applied only for a mapping that explicitly requires it. -
-
-
-
-

2.2. Customization of WireMock Configuration

-
-

You can register a bean of type org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer -to customize the WireMock configuration (for example, to add custom transformers). -The following example shows how to do so:

-
-
-
-
-
-
        @Bean
-        WireMockConfigurationCustomizer optionsCustomizer() {
-            return new WireMockConfigurationCustomizer() {
-                @Override
-                public void customize(WireMockConfiguration options) {
-// perform your customization here
-                }
-            };
-        }
-
-
-
-
-
-
-
-
-

3. Using the Pluggable Architecture

-
-
-

You may encounter cases where your contracts have been defined in other formats, -such as YAML, RAML, or PACT. In those cases, you still want to benefit from the automatic -generation of tests and stubs. You can add your own implementation for generating both -tests and stubs. Also, you can customize the way tests are generated (for example, you -can generate tests for other languages) and the way stubs are generated (for example, you -can generate stubs for other HTTP server implementations).

-
-
-

3.1. Custom Contract Converter

-
-

The ContractConverter interface lets you register your own implementation of a contract -structure converter. The following code listing shows the ContractConverter interface:

-
-
-
-
-
-
package org.springframework.cloud.contract.spec;
-
-import java.io.File;
-import java.util.Collection;
-
-/**
- * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
- * {@link Contract} to {@code T}.
- *
- * @param <T> - type to which we want to convert the contract
- * @author Marcin Grzejszczak
- * @since 1.1.0
- */
-public interface ContractConverter<T> extends ContractStorer<T> {
-
-    /**
-     * Should this file be accepted by the converter. Can use the file extension to check
-     * if the conversion is possible.
-     * @param file - file to be considered for conversion
-     * @return - {@code true} if the given implementation can convert the file
-     */
-    boolean isAccepted(File file);
-
-    /**
-     * Converts the given {@link File} to its {@link Contract} representation.
-     * @param file - file to convert
-     * @return - {@link Contract} representation of the file
-     */
-    Collection<Contract> convertFrom(File file);
-
-    /**
-     * Converts the given {@link Contract} to a {@link T} representation.
-     * @param contract - the parsed contract
-     * @return - {@link T} the type to which we do the conversion
-     */
-    T convertTo(Collection<Contract> contract);
-
-}
-
-
-
-
-
-

Your implementation must define the condition on which it should start the -conversion. Also, you must define how to perform that conversion in both directions.

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

The following example shows a typical spring.factories file:

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

3.2. Using the Custom Test Generator

-
-

If you want to generate tests for languages other than Java or you are not happy with the -way the verifier builds Java tests, you can register your own implementation.

-
-
-

The SingleTestGenerator interface lets you register your own implementation. The -following code listing shows the SingleTestGenerator interface:

-
-
-
-
-
-
package org.springframework.cloud.contract.verifier.builder;
-
-import java.nio.file.Path;
-import java.util.Collection;
-
-import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
-import org.springframework.cloud.contract.verifier.file.ContractMetadata;
-
-/**
- * Builds a single test.
- *
- * @since 1.1.0
- */
-public interface SingleTestGenerator {
-
-    /**
-     * Creates contents of a single test class in which all test scenarios from the
-     * contract metadata should be placed.
-     * @param properties - properties passed to the plugin
-     * @param listOfFiles - list of parsed contracts with additional metadata
-     * @param className - the name of the generated test class
-     * @param classPackage - the name of the package in which the test class should be
-     * stored
-     * @param includedDirectoryRelativePath - relative path to the included directory
-     * @return contents of a single test class
-     * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
-     */
-    @Deprecated
-    String buildClass(ContractVerifierConfigProperties properties,
-            Collection<ContractMetadata> listOfFiles, String className,
-            String classPackage, String includedDirectoryRelativePath);
-
-    /**
-     * Creates contents of a single test class in which all test scenarios from the
-     * contract metadata should be placed.
-     * @param properties - properties passed to the plugin
-     * @param listOfFiles - list of parsed contracts with additional metadata
-     * @param generatedClassData - information about the generated class
-     * @param includedDirectoryRelativePath - relative path to the included directory
-     * @return contents of a single test class
-     */
-    String buildClass(ContractVerifierConfigProperties properties,
-            Collection<ContractMetadata> listOfFiles,
-            String includedDirectoryRelativePath, GeneratedClassData generatedClassData);
-
-    class GeneratedClassData {
-
-        public final String className;
-
-        public final String classPackage;
-
-        public final Path testClassPath;
-
-        public GeneratedClassData(String className, String classPackage,
-                Path testClassPath) {
-            this.className = className;
-            this.classPackage = classPackage;
-            this.testClassPath = testClassPath;
-        }
-
-    }
-
-}
-
-
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

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

3.3. Using the Custom Stub Generator

-
-

If you want to generate stubs for stub servers other than WireMock, you can plug in your -own implementation of the StubGenerator interface. The following code listing shows the -StubGenerator interface:

-
-
-
-
-
-
package org.springframework.cloud.contract.verifier.converter;
-
-import java.util.Map;
-
-import org.springframework.cloud.contract.spec.Contract;
-import org.springframework.cloud.contract.verifier.file.ContractMetadata;
-
-/**
- * Converts contracts into their stub representation.
- *
- * @since 1.1.0
- */
-public interface StubGenerator {
-
-    /**
-     * @param fileName - file name
-     * @return {@code true} if the converter can handle the file to convert it into a
-     * stub.
-     */
-    default boolean canHandleFileName(String fileName) {
-        return fileName.endsWith(fileExtension());
-    }
-
-    /**
-     * @param rootName - root name of the contract
-     * @param content - metadata of the contract
-     * @return the collection of converted contracts into stubs. One contract can result
-     * in multiple stubs.
-     */
-    Map<Contract, String> convertContents(String rootName, ContractMetadata content);
-
-    /**
-     * @param inputFileName - name of the input file
-     * @return the name of the converted stub file. If you have multiple contracts in a
-     * single file then a prefix will be added to the generated file. If you provide the
-     * {@link Contract#name} field then that field will override the generated file name.
-     *
-     * Example: name of file with 2 contracts is {@code foo.groovy}, it will be converted
-     * by the implementation to {@code foo.json}. The recursive file converter will create
-     * two files {@code 0_foo.json} and {@code 1_foo.json}
-     */
-    String generateOutputFileNameForInput(String inputFileName);
-
-    /**
-     * Describes the file extension that this stub generator can handle.
-     * @return string describing the file extension
-     */
-    default String fileExtension() {
-        return ".json";
-    }
-
-}
-
-
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

-
-
-
-
-
-
# Stub converters
-org.springframework.cloud.contract.verifier.converter.StubGenerator=\
-org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
-
-
-
-
-
-

The default implementation is the WireMock stub generation.

-
-
- - - - - -
- - -You can provide multiple stub generator implementations. For example, from a single -DSL, you can produce both WireMock stubs and Pact files. -
-
-
-
-

3.4. Using the Custom Stub Runner

-
-

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

-
-
-

Assume that you use Moco to build your stubs and that -you have written a stub generator and placed your stubs in a JAR file.

-
-
-

In order for Stub Runner to know how to run your stubs, you have to define a custom -HTTP Stub server implementation, which might resemble the following example:

-
-
-
-
-
-
package org.springframework.cloud.contract.stubrunner.provider.moco
-
-import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
-import com.github.dreamhead.moco.runner.JsonRunner
-import com.github.dreamhead.moco.runner.RunnerSetting
-import groovy.transform.CompileStatic
-import groovy.util.logging.Commons
-
-import org.springframework.cloud.contract.stubrunner.HttpServerStub
-import org.springframework.util.SocketUtils
-
-@Commons
-@CompileStatic
-class MocoHttpServerStub implements HttpServerStub {
-
-    private boolean started
-    private JsonRunner runner
-    private int port
-
-    @Override
-    int port() {
-        if (!isRunning()) {
-            return -1
-        }
-        return port
-    }
-
-    @Override
-    boolean isRunning() {
-        return started
-    }
-
-    @Override
-    HttpServerStub start() {
-        return start(SocketUtils.findAvailableTcpPort())
-    }
-
-    @Override
-    HttpServerStub start(int port) {
-        this.port = port
-        return this
-    }
-
-    @Override
-    HttpServerStub stop() {
-        if (!isRunning()) {
-            return this
-        }
-        this.runner.stop()
-        return this
-    }
-
-    @Override
-    HttpServerStub registerMappings(Collection<File> stubFiles) {
-        List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
-            .collect {
-            log.info("Trying to parse [${it.name}]")
-            try {
-                return RunnerSetting.aRunnerSetting().addStream(it.newInputStream()).
-                    build()
-            }
-            catch (Exception e) {
-                log.warn("Exception occurred while trying to parse file [${it.name}]", e)
-                return null
-            }
-        }.findAll { it }
-        this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
-            HttpArgs.httpArgs().withPort(this.port).build())
-        this.runner.run()
-        this.started = true
-        return this
-    }
-
-    @Override
-    String registeredMappings() {
-        return ""
-    }
-
-    @Override
-    boolean isAccepted(File file) {
-        return file.name.endsWith(".json")
-    }
-}
-
-
-
-
-
-

Then you can register it in your spring.factories file, as the following -example shows:

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

Now you can run stubs with Moco.

-
-
- - - - - -
- - -If you do not provide any implementation, the default (WireMock) -implementation is used. If you provide more than one, the first one on the list is used. -
-
-
-
-

3.5. Using the Custom Stub Downloader

-
-

You can customize the way your stubs are downloaded by creating an implementation of the -StubDownloaderBuilder interface, as the following example shows:

-
-
-
-
-
-
package com.example;
-
-class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
-
-    @Override
-    public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
-        return new StubDownloader() {
-            @Override
-            public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
-                    StubConfiguration config) {
-                File unpackedStubs = retrieveStubs();
-                return new AbstractMap.SimpleEntry<>(
-                        new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
-                                config.getClassifier()), unpackedStubs);
-            }
-
-            File retrieveStubs() {
-                // here goes your custom logic to provide a folder where all the stubs reside
-            }
-}
-
-
-
-
-
-

Then you can register it in your spring.factories file, as the following -example shows:

-
-
-
-
-
-
# Example of a custom Stub Downloader Provider
-org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
-com.example.CustomStubDownloaderBuilder
-
-
-
-
-
-

Now you can pick a folder with the source of your stubs.

-
-
- - - - - -
- - -If you do not provide any implementation, the default (scanning the classpath) is used. -If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or -stubsMode = StubRunnerProperties.StubsMode.REMOTE, the Aether implementation is used -If you provide more than one, the first one on the list is used. -
-
-
-
-

3.6. Using the SCM Stub Downloader

-
-

Whenever the repositoryRoot starts with a SCM protocol -(currently, we support only git://), the stub downloader tries -to clone the repository and use it as a source of contracts -to generate tests or stubs.

-
-
-

Through environment variables, system properties, or properties set -inside the plugin or the contracts repository configuration, you can -tweak the downloader’s behavior. The following table describes the available -properties:

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

-

* stubrunner.properties.git.branch (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

-

* stubrunner.properties.git.username (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

-

* stubrunner.properties.git.password (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

-

* stubrunner.properties.git.no-of-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

-

* stubrunner.properties.git.wait-between-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of milliseconds to wait between attempts to push the commits to origin

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/appendix.html b/reference/html/appendix.html index 2d99091695..9990b6e5bb 100644 --- a/reference/html/appendix.html +++ b/reference/html/appendix.html @@ -1,457 +1,12 @@ - - - + + - - - -Common application properties - - - - - - - - - -
-
-

Appendix A: Common application properties

-
-
-

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. -This appendix provides a list of common Spring Cloud Contract properties and references to the underlying classes that consume them.

-
-
- - - - - -
- - -Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list. -Also, you can define your own properties. -
-
-
-

A.1. Default application properties

- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameDefaultDescription

stubrunner.amqp.enabled

false

Whether to enable support for Stub Runner and AMQP.

stubrunner.amqp.mockCOnnection

true

Whether to enable support for Stub Runner and AMQP mocked connection factory.

stubrunner.classifier

stubs

The classifier to use by default in ivy co-ordinates for a stub.

stubrunner.cloud.consul.enabled

true

Whether to enable stubs registration in Consul.

stubrunner.cloud.delegate.enabled

true

Whether to enable DiscoveryClient’s Stub Runner implementation.

stubrunner.cloud.enabled

true

Whether to enable Spring Cloud support for Stub Runner.

stubrunner.cloud.eureka.enabled

true

Whether to enable stubs registration in Eureka.

stubrunner.cloud.loadbalancer.enabled

true

Whether to enable Stub Runner’s Spring Cloud Load Balancer integration.

stubrunner.cloud.stubbed.discovery.enabled

true

Whether Service Discovery should be stubbed for Stub Runner. If set to false, stubs will get registered in real service discovery.

stubrunner.cloud.zookeeper.enabled

true

Whether to enable stubs registration in Zookeeper.

stubrunner.consumer-name

You can override the default {@code spring.application.name} of this field by setting a value to this parameter.

stubrunner.delete-stubs-after-test

true

If set to {@code false} will NOT delete stubs from a temporary folder after running tests.

stubrunner.fail-on-no-stubs

true

When enabled, this flag will tell stub runner to throw an exception when no stubs / contracts were found.

stubrunner.generate-stubs

false

When enabled, this flag will tell stub runner to not load the generated stubs, but convert the found contracts at runtime to a stub format and run those stubs.

stubrunner.http-server-stub-configurer

Configuration for an HTTP server stub.

stubrunner.ids

[]

The ids of the stubs to run in "ivy" notation ([groupId]:artifactId:[version]:[classifier][:port]). {@code groupId}, {@code classifier}, {@code version} and {@code port} can be optional.

stubrunner.ids-to-service-ids

Mapping of Ivy notation based ids to serviceIds inside your application. Example "a:b" → "myService" "artifactId" → "myOtherService"

stubrunner.integration.enabled

true

Whether to enable Stub Runner integration with Spring Integration.

stubrunner.jms.enabled

true

Whether to enable Stub Runner integration with Spring JMS.

stubrunner.kafka.enabled

true

Whether to enable Stub Runner integration with Spring Kafka.

stubrunner.kafka.initializer.enabled

true

Whether to allow Stub Runner to take care of polling for messages instead of the KafkaStubMessages component. The latter should be used only on the producer side.

stubrunner.mappings-output-folder

Dumps the mappings of each HTTP server to the selected folder.

stubrunner.max-port

15000

Max value of a port for the automatically started WireMock server.

stubrunner.min-port

10000

Min value of a port for the automatically started WireMock server.

stubrunner.password

Repository password.

stubrunner.properties

Map of properties that can be passed to custom {@link org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder}.

stubrunner.proxy-host

Repository proxy host.

stubrunner.proxy-port

Repository proxy port.

stubrunner.server-id

stubrunner.stream.enabled

true

Whether to enable Stub Runner integration with Spring Cloud Stream.

stubrunner.stubs-mode

Pick where the stubs should come from.

stubrunner.stubs-per-consumer

false

Should only stubs for this particular consumer get registered in HTTP server stub.

stubrunner.username

Repository username.

wiremock.placeholders.enabled

true

Flag to indicate that http URLs in generated wiremock stubs should be filtered to add or resolve a placeholder for a dynamic port.

wiremock.reset-mappings-after-each-test

false

wiremock.rest-template-ssl-enabled

false

wiremock.server.files

[]

wiremock.server.https-port

-1

wiremock.server.https-port-dynamic

false

wiremock.server.port

8080

wiremock.server.port-dynamic

false

wiremock.server.stubs

[]

-
-
-

A.2. Additional application properties

-
- - - - - -
- - -The following properties can be passed as a system property (e.g. stubrunner.properties.git.branch) or via an environment variable (e.g. STUBRUNNER_PROPERTIES_GIT_BRANCH) or as a property inside stub runner’s annotation or a JUnit Rule / Extension. In the latter case you can pass git.branch property name instead of the stubrunner.properties.git.branch one. -
-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 1. Stubrunner Properties Options
NameDefaultDescription

stubrunner.properties.pactbroker.provider-name-with-group-id

false

When using the Pact Broker based approach, you can automatically group id to the provider name.

stubrunner.properties.git.branch

When using the SCM based approach, you can customize the branch name to check out.

stubrunner.properties.git.commit-message

Updating project [$project] with stubs

When using the SCM based approach, you can customize the commit message for created stubs. The $project text will be replaced with the project name.

stubrunner.properties.git.no-of-attempts

10

When using the SCM based approach, you can customize number of retries to push the stubs to Git.

stubrunner.properties.git.username

When using the SCM based approach, you can pass the username to connect to the Git repository.

stubrunner.properties.git.password

When using the SCM based approach, you can pass the password to connect to the Git repository.

stubrunner.properties.git.wait-between-attempts

1000

When using the SCM based approach, you can customize waiting time in ms between trying to push the stubs to Git.

stubrunner.properties.stubs.find-producer

false

When using the Stubs protocol, you can toggle this flag to search for contracts via the group id / artifact id instead of taking the stubs directly from the provided folder.

-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/building.html b/reference/html/building.html index 1b9649c385..9990b6e5bb 100644 --- a/reference/html/building.html +++ b/reference/html/building.html @@ -1,304 +1,12 @@ - - - + + - - - -How to build it - - + - - - - - - -
-
-

How to build it

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

Project structure

-
-

Here you can find the Spring Cloud Contract folder structure

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

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

    -
  • -
  • -

    docker - folder contains docker images

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    specs - contains specifications for the Contract DSL.

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    tests - integration tests for different messaging technologies

    -
  • -
-
-
-
-

Commands

-
-

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

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

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

-
-
-

To build the Gradle Plugin only

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

Helpful scripts

-
-

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

-
-
-

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

-
-
-
-
./scripts/parallelBuild.sh
-
-
-
-

and with 8 cores

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

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

-
-
-
-
./scripts/noIntegration.sh
-
-
-
-

and with 8 cores

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

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

-
-
-
-
./scripts/generateDocs.sh
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/docker-project.html b/reference/html/docker-project.html index 6f9d26cc3b..9990b6e5bb 100644 --- a/reference/html/docker-project.html +++ b/reference/html/docker-project.html @@ -1,607 +1,12 @@ - - - + + - - - -Docker Project - - - - - - - - - -
-
-
-
-

In this section, we publish a springcloud/spring-cloud-contract Docker image -that contains a project that generates tests and runs them in EXPLICIT mode -against a running application.

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

We also publish a spring-cloud/spring-cloud-contract-stub-runner Docker image -that starts the standalone version of Stub Runner.

-
-
-
-
-

1. A Short Introduction to Maven, JARs and Binary storage

-
-
-

Since non-JVM projects can use the Docker image, it is good to -explain the basic terms behind Spring Cloud Contract packaging defaults.

-
-
-

Parts of the following definitions were taken from the Maven Glossary:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    JAR: JAR stands for Java ARchive. Its format is based on -the ZIP file format. Spring Cloud Contract packages the contracts and generated -stubs in a JAR file.

    -
  • -
  • -

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

    -
  • -
  • -

    Classifier: The Maven dependency notation looks as follows: -groupId:artifactId:version:classifier. The classifier is an additional suffix -passed to the dependency — for example, stubs or sources. The same dependency -(for example, com.example:application) can produce multiple artifacts that -differ from each other with the classifier.

    -
  • -
  • -

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

    -
  • -
-
-
-
-
-

2. Generating Tests on the Producer Side

-
-
-

The image searches for contracts under the /contracts folder. -The output from running the tests is available in the -/spring-cloud-contract/build folder (useful for debugging -purposes).

-
-
-

You can mount your contracts and pass the environment variables. -The image then:

-
-
-
    -
  • -

    Generates the contract tests

    -
  • -
  • -

    Runs the tests against the provided URL

    -
  • -
  • -

    Generates the WireMock stubs

    -
  • -
  • -

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

    -
  • -
-
-
-

2.1. Environment Variables

-
-

The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance, and so on. -The following list describes the environment variables:

-
-
-
    -
  • -

    PROJECT_GROUP: Your project’s group ID. Defaults to com.example.

    -
  • -
  • -

    PROJECT_VERSION: Your project’s version. Defaults to 0.0.1-SNAPSHOT.

    -
  • -
  • -

    PROJECT_NAME: Your project’s artifact id. Defaults to example.

    -
  • -
  • -

    PRODUCER_STUBS_CLASSIFIER: Archive classifier used for generated producer stubs. Defaults to stubs.

    -
  • -
  • -

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

    -
  • -
  • -

    REPO_WITH_BINARIES_USERNAME: (optional) Username when the Artifact Manager is secured. Defaults to admin.

    -
  • -
  • -

    REPO_WITH_BINARIES_PASSWORD: (optional) Password when the Artifact Manager is secured. Defaults to password.

    -
  • -
  • -

    PUBLISH_ARTIFACTS: If set to true, publishes the artifact to binary storage. Defaults to true.

    -
  • -
  • -

    PUBLISH_ARTIFACTS_OFFLINE: If set to true, it will publish the artifacts to local .m2. Defaults to false.

    -
  • -
-
-
-

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

-
-
-
    -
  • -

    EXTERNAL_CONTRACTS_GROUP_ID: Group ID of the project with contracts. Defaults to com.example

    -
  • -
  • -

    EXTERNAL_CONTRACTS_ARTIFACT_ID: Artifact ID of the project with contracts.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_CLASSIFIER: Classifier of the project with contracts. Empty by default.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_VERSION: Version of the project with contracts. Defaults to +, equivalent to picking the latest.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL: URL of your Artifact Manager. It defaults to -the value of REPO_WITH_BINARIES_URL environment variable. -If that is not set, it defaults to localhost:8081/artifactory/libs-release-local, -which is the default URL of Artifactory running locally.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME: (optional) Username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication. It defaults to REPO_WITH_BINARIES_USERNAME. If that is not set, it defaults to admin.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD: (optional) Password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication. It defaults to REPO_WITH_BINARIES_PASSWORD. If that is not set, it defaults to password.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_PATH: Path to contracts for the given project, inside the project with contracts. -Defaults to slash-separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. For example, -for group id cat-server-side.dog and artifact id fish, would result in cat/dog/fish for the contracts path.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_WORK_OFFLINE; If set to true, retrieves the artifact with contracts -from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path.

    -
  • -
-
-
- - - - - -
- - -You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL. -
-
-
-

The following environment variables are used when tests are executed:

-
-
-
    -
  • -

    APPLICATION_BASE_URL: URL against which tests should be run. -Remember that it has to be accessible from the Docker container (for example, localhost -does not work)

    -
  • -
  • -

    APPLICATION_USERNAME: (optional) Username for basic authentication to your application.

    -
  • -
  • -

    APPLICATION_PASSWORD: (optional) Password for basic authentication to your application.

    -
  • -
-
-
-
-

2.2. Example of Usage

-
-

In this section, we explore a simple MVC application. To get started, clone the following -git repository and cd to the resulting directory, by running the following commands:

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

The contracts are available in the /contracts folder.

-
-
-

Since we want to run tests, we can run the following command:

-
-
-
-
-
-
$ npm test
-
-
-
-
-
-

However, for learning purposes, we split it into pieces, as follows:

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

Through bash scripts, the following happens:

-
-
-
    -
  • -

    The infrastructure (MongoDb and Artifactory) is set up. -In a real-life scenario, you would run the NodeJS application -with a mocked database. In this example, we want to show how we can -benefit from Spring Cloud Contract in very little time.

    -
  • -
  • -

    Due to those constraints, the contracts also represent the -stateful situation.

    -
    -
      -
    • -

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

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
  • -

    The NodeJS application is started (on port 3000).

    -
  • -
  • -

    The contract tests are generated through Docker, and tests -are run against the running application.

    -
    -
      -
    • -

      The contracts are taken from /contracts folder.

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
  • -

    The stubs are uploaded to Artifactory. You can find them in -localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs are at localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    -
  • -
-
-
-
-
-
-

3. Running Stubs on the Consumer Side

-
-
-

This section describes how to use Docker on the consumer side to fetch and run stubs.

-
-
-

We publish a spring-cloud/spring-cloud-contract-stub-runner Docker image -that starts the standalone version of Stub Runner.

-
-
-

3.1. Environment Variables

-
-

You can run the docker image and pass any of the Common Properties for JUnit and Spring -as environment variables. The convention is that all the -letters should be upper case. -The dot (.) should be replaced with underscore (_) characters. For example, -the stubrunner.repositoryRoot property should be represented -as a STUBRUNNER_REPOSITORY_ROOT environment variable.

-
-
-
-

3.2. Example of Usage

-
-

We want to use the stubs created in this [docker-server-side] step. -Assume that we want to run the stubs on port 9876. You can see the NodeJS code -by cloning the repository and changing to the directory indicated in the following commands:

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

Now we can run the Stub Runner Boot application with the stubs, by running the following -commands:

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

When the preceding commands run,

-
-
-
    -
  • -

    A standalone Stub Runner application gets started.

    -
  • -
  • -

    It downloads the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876.

    -
  • -
  • -

    It gets downloads from Artifactory running at 192.168.0.100:8081/artifactory/libs-release-local.

    -
  • -
  • -

    After a whil, Stub Runner is running on port 8083.

    -
  • -
  • -

    The stubs are running at port 9876.

    -
  • -
-
-
-

On the server side, we built a stateful stub. We can use curl to assert -that the stubs are setup properly. To do so, run the following commands:

-
-
-
-
-
-
# let's execute the first request (no response is returned)
-$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
-# Now time for the second request
-$ curl -X GET http://localhost:9876/api/books
-# You will receive contents of the JSON
-
-
-
-
-
- - - - - -
- - -If you want use the stubs that you have built locally, on your host, -you should set the -e STUBRUNNER_STUBS_MODE=LOCAL environment variable and mount -the volume of your local m2 (-v "${HOME}/.m2/:/root/.m2:ro"). -
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/documentation-overview.html b/reference/html/documentation-overview.html index 09ce319bd1..9990b6e5bb 100644 --- a/reference/html/documentation-overview.html +++ b/reference/html/documentation-overview.html @@ -1,391 +1,12 @@ - - - + + - - - -Spring Cloud Contract Documentation - - - - - - - - - -
-
-
-
-

This section provides a brief overview of Spring Cloud Contract reference documentation. It serves -as a map for the rest of the document.

-
-
-
-
-

1. About the Documentation

-
-
-

The Spring Cloud Contract reference guide is available as

-
-
- -
-
-

Copies of this document may be made for your own use and for distribution to others, -provided that you do not charge any fee for such copies and further provided that each -copy contains this Copyright Notice, whether distributed in print or electronically.

-
-
-
-
-

2. Getting Help

-
-
-

If you have trouble with Spring Cloud Contract, we would like to help.

-
-
- -
-
- - - - - -
- - -All of Spring Cloud Contract is open source, including the documentation. If you find -problems with the docs or if you want to improve them, please get -involved. -
-
-
-
-
-

3. First Steps

-
-
-

If you are getting started with Spring Cloud Contract or 'Spring' in general, start with -the following topics:

-
-
- -
-
-
-
-

4. Working with Spring Cloud Contract

-
-
-

Ready to actually start using Spring Cloud Contract? We have -you covered:

-
- -
- - - - - -
- - -We talk about Provider Contracts when it is the producer of the API that defines the contracts and -publishes it for all its consumers to use. This approach is useful for producers that cannot -directly collaborate with their consumers — for example, when there are too many consumers or -the consumers are external (do not work within the same company). -
-
-
- - - - - -
- - -We use the term, Consumer-Driven Contracts, to refer to workflows where the consumers of an API -play a vital role in the process of creating the contracts. We recommended this approach, because it is easy -to implement when both producer and consumer teams work for the same organizations and the number -of consumers is not extremely large. -
-
-
-
-
-

5. Learning about Spring Cloud Contract Features

-
-
-

Need more details about Spring Cloud Contract’s core features? -The following content is for you:

-
-
- -
-
-
-
-

6. Advanced Topics

-
-
-

Finally, we have a few topics for more advanced users:

-
-
- -
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/getting-started.html b/reference/html/getting-started.html index bdfa2db935..9990b6e5bb 100644 --- a/reference/html/getting-started.html +++ b/reference/html/getting-started.html @@ -1,2644 +1,12 @@ - - - + + - - - -Getting Started - - - - - - - - - -
-
-
-
-

If you are getting started with Spring Cloud Contract, or Spring in general, start by reading -this section. It answers the basic “what?”, “how?” and “why?” questions. It -includes an introduction to Spring Cloud Contract, along with installation instructions. We then -walk you through building your first Spring Cloud Contract application, discussing some core -principles as we go.

-
-
-
-
-

1. Introducing Spring Cloud Contract

-
-
-

Spring Cloud Contract moves TDD to the level of software architecture. -It lets you perform consumer-driven and producer-driven contract testing.

-
-
-

1.1. History

-
-

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

-
-
-

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

-
-
-

1.1.1. Why Do You Need It?

-
-

Assume that we have a system that consists of multiple microservices, as the following -image shows:

-
-
-
-Microservices Architecture -
-
-
-
-

1.1.2. Testing Issues

-
-

If we want to test the application in the top left corner of the image in the preceding -section to determine whether it can communicate with other services, we could do one of -two things:

-
-
-
    -
  • -

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

    -
  • -
  • -

    Mock other microservices in unit and integration tests.

    -
  • -
-
-
-

Both have their advantages but also a lot of disadvantages.

-
-
-

Deploy all microservices and perform end to end tests

-
-
-

Advantages:

-
-
-
    -
  • -

    Simulates production.

    -
  • -
  • -

    Tests real communication between services.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

    To test one microservice, we have to deploy six microservices, a couple of databases, -and other items.

    -
  • -
  • -

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

    -
  • -
  • -

    They take a long time to run.

    -
  • -
  • -

    The feedback comes very late in the process.

    -
  • -
  • -

    They are extremely hard to debug.

    -
  • -
-
-
-

Mock other microservices in unit and integration tests

-
-
-

Advantages:

-
-
-
    -
  • -

    They provide very fast feedback.

    -
  • -
  • -

    They have no infrastructure requirements.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

To solve the aforementioned issues, Spring Cloud Contract was created. The main idea is to -give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses. The following image shows the relationship -of stubs to an application:

-
-
-
-Stubbed Services -
-
-
-

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

-
-
-
-
-

1.2. Purposes

-
-

The main purposes of Spring Cloud Contract are:

-
-
-
    -
  • -

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

    -
  • -
  • -

    To promote the ATDD (acceptance test-driven developement) method and the microservices architectural style.

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

By default, Spring Cloud Contract integrates with Wiremock as the HTTP server stub.

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

1.3. What Is a Contract?

-
-

As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts. In other words, a contract is -an agreement on how the API or message communication should look. Consider the following example:

-
-
-

Assume that you want to send a request that contains the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck URL via -the PUT method. The following listing shows a contract to check whether a client should -be marked as a fraud in both Groovy and YAML:

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

2. A Three-second Tour

-
-
-

This very brief tour walks through using Spring Cloud Contract. It consists of the -following topics:

-
- -
-

You can find a somewhat longer tour -here.

-
-
-

The following UML diagram shows the relationship of the parts within Spring Cloud Contract:

-
-
-
-getting started three second -
-
-
-

2.1. On the Producer Side

-
-

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

-
-
-

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

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

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

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

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

-
-
-

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

-
-
-

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

-
-
-

The following example, from pom.xml, shows how to specify the base test class:

-
-
-
-
-
-
<build>
-        <plugins>
-            <plugin>
-                <groupId>org.springframework.cloud</groupId>
-                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                <version>2.1.2.RELEASE</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <baseClassForTests>com.example.contractTest.BaseTestClass</baseClassForTests> (1)
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.springframework.boot</groupId>
-                <artifactId>spring-boot-maven-plugin</artifactId>
-            </plugin>
-        </plugins>
-    </build>
-
-
-
- - - - - -
1The baseClassForTests element lets you specify your base test class. It must be a child -of a configuration element within spring-cloud-contract-maven-plugin.
-
-
-
-
-

Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -You can now merge the changes, and you can publish both the application and the stub artifacts -in an online repository.

-
-
-
-

2.2. On the Consumer Side

-
-

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

-
-
-

To do so, add the dependency to Spring Cloud Contract Stub Runner, as the -following example shows:

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

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

-
-
-
    -
  • -

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

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

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

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

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

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

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

-
-
-
-
-
-

3. Developing Your First Spring Cloud Contract-based Application

-
-
-

This brief tour walks through using Spring Cloud Contract. It consists of the following topics:

-
- -
-

You can find an even more brief tour -here.

-
-
-

For the sake of this example, the Stub Storage is Nexus/Artifactory.

-
-
-

The following UML diagram shows the relationship of the parts of Spring Cloud Contract:

-
-
-
-Getting started first application -
-
-
-

3.1. On the Producer Side

-
-

To start working with Spring Cloud Contract, you can add Spring Cloud Contract Verifier -dependency and plugin to your build file, as the following example shows:

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

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

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

The easiest way to get started is to go to the Spring Initializr -and add “Web” and “Contract Verifier” as dependencies. Doing so pulls in the previously -mentioned dependencies and everything else you need in the pom.xml file (except for -setting the base test class, which we cover later in this section). The following image -shows the settings to use in the Spring Initializr:

-
-
-
-Spring Initializr with Web and Contract Verifier -
-
-
-
-
-

Now you can add files with REST/ messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts. -Note that the file name does not matter. You can organize your contracts within this -directory with whatever naming scheme you like.

-
-
-

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

-
-
-
-
-
groovy
-
-
package contracts
-
-org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'PUT'
-        url '/fraudcheck'
-        body([
-               "client.id": $(regex('[0-9]{10}')),
-               loanAmount: 99999
-        ])
-        headers {
-            contentType('application/json')
-        }
-    }
-    response {
-        status OK()
-        body([
-               fraudCheckStatus: "FRAUD",
-               "rejection.reason": "Amount too high"
-        ])
-        headers {
-            contentType('application/json')
-        }
-    }
-}
-
-
-
-
yaml
-
-
request:
-  method: PUT
-  url: /fraudcheck
-  body:
-    "client.id": 1234567890
-    loanAmount: 99999
-  headers:
-    Content-Type: application/json
-  matchers:
-    body:
-      - path: $.['client.id']
-        type: by_regex
-        value: "[0-9]{10}"
-response:
-  status: 200
-  body:
-    fraudCheckStatus: "FRAUD"
-    "rejection.reason": "Amount too high"
-  headers:
-    Content-Type: application/json;charset=UTF-8
-
-
-
-
-
-

If you need to use messaging, you can define:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

The following example shows a Camel messaging contract:

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

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

-
-
-

The generated tests may differ, depending on which framework and test type you have setup -in your plugin.

-
-
-

In the next listing, you can find:

-
-
-
    -
  • -

    The default test mode for HTTP contracts in MockMvc

    -
  • -
  • -

    A JAX-RS client with the JAXRS test mode

    -
  • -
  • -

    A WebTestClient-based test (this is particularly recommended while working with -Reactive, Web-Flux-based applications) set with the WEBTESTCLIENT test mode

    -
  • -
  • -

    A Spock-based test with the testFramework property set to SPOCK

    -
  • -
-
-
- - - - - -
- - -You need only one of these test frameworks. MockMvc is the default. To use one -of the other frameworks, add its library to your classpath. -
-
-
-

The following listing shows samples for all frameworks:

-
-
-
-
-
mockmvc
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-    // given:
-        MockMvcRequestSpecification request = given()
-                .header("Content-Type", "application/vnd.fraud.v1+json")
-                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
-
-    // when:
-        ResponseOptions response = given().spec(request)
-                .put("/fraudcheck");
-
-    // then:
-        assertThat(response.statusCode()).isEqualTo(200);
-        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
-    // and:
-        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
-        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
-}
-
-
-
-
jaxrs
-
-
@SuppressWarnings("rawtypes")
-public class FooTest {
-  WebTarget webTarget;
-
-  @Test
-  public void validate_() throws Exception {
-
-    // 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()
-              .build("GET")
-              .invoke();
-      String responseAsString = response.readEntity(String.class);
-
-    // then:
-      assertThat(response.getStatus()).isEqualTo(200);
-
-    // and:
-      DocumentContext parsedJson = JsonPath.parse(responseAsString);
-      assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
-  }
-
-}
-
-
-
-
webtestclient
-
-
@Test
-    public void validate_shouldRejectABeerIfTooYoung() throws Exception {
-        // given:
-            WebTestClientRequestSpecification request = given()
-                    .header("Content-Type", "application/json")
-                    .body("{\"age\":10}");
-
-        // when:
-            WebTestClientResponse response = given().spec(request)
-                    .post("/check");
-
-        // then:
-            assertThat(response.statusCode()).isEqualTo(200);
-            assertThat(response.header("Content-Type")).matches("application/json.*");
-        // and:
-            DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-            assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
-    }
-
-
-
-
spock
-
-
given:
-     ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-        \'\'\'{"bookName":"foo"}\'\'\',
-        ['sample': 'header']
-    )
-
-when:
-     contractVerifierMessaging.send(inputMessage, 'jms:delete')
-
-then:
-     noExceptionThrown()
-     bookWasDeleted()
-
-
-
-
-
-

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

-
-
-

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

-
-
-

The following example, from pom.xml, shows how to specify the base test class:

-
-
-
-
-
-
<build>
-        <plugins>
-            <plugin>
-                <groupId>org.springframework.cloud</groupId>
-                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                <version>2.1.2.RELEASE</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <baseClassForTests>com.example.contractTest.BaseTestClass</baseClassForTests> (1)
-                </configuration>
-            </plugin>
-            <plugin>
-                <groupId>org.springframework.boot</groupId>
-                <artifactId>spring-boot-maven-plugin</artifactId>
-            </plugin>
-        </plugins>
-    </build>
-
-
-
- - - - - -
1The baseClassForTests element lets you specify your base test class. It must be a child -of a configuration element within spring-cloud-contract-maven-plugin.
-
-
-
-
-

The following example shows a minimal (but functional) base test class:

-
-
-
-
-
-
package com.example.contractTest;
-
-import org.junit.Before;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-
-public class BaseTestClass {
-
-    @Before
-    public void setup() {
-        RestAssuredMockMvc.standaloneSetup(new FraudController());
-    }
-}
-
-
-
-
-
-

This minimal class really is all you need to get your tests to work. It serves as a -starting place to which the automatically generated tests attach.

-
-
-

Now we can move on to the implementation. For that, we first need a data class, which we -then use in our controller. The following listing shows the data class:

-
-
-
-
-
-
package com.example.Test;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class LoanRequest {
-
-    @JsonProperty("client.id")
-    private String clientId;
-
-    private Long loanAmount;
-
-    public String getClientId() {
-        return clientId;
-    }
-
-    public void setClientId(String clientId) {
-        this.clientId = clientId;
-    }
-
-    public Long getLoanAmount() {
-        return loanAmount;
-    }
-
-    public void setLoanRequestAmount(Long loanAmount) {
-        this.loanAmount = loanAmount;
-    }
-}
-
-
-
-
-
-

The preceding class provides an object in which we can store the parameters. Because the -client ID in the contract is called client.id, we need to use the -@JsonProperty("client.id") parameter to map it to the clientId field.

-
-
-

Now we can move along to the controller, which the following listing shows:

-
-
-
-
-
-
package com.example.docTest;
-
-import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RestController;
-
-@RestController
-public class FraudController {
-
-    @PutMapping(value = "/fraudcheck", consumes="application/json", produces="application/json")
-    public String check(@RequestBody LoanRequest loanRequest) { (1)
-
-        if (loanRequest.getLoanAmount() > 10000) { (2)
-            return "{fraudCheckStatus: FRAUD, rejection.reason: Amount too high}"; (3)
-        } else {
-            return "{fraudCheckStatus: OK, acceptance.reason: Amount OK}"; (4)
-        }
-    }
-}
-
-
-
- - - - - - - - - - - - - - - - - -
1We map the incoming parameters to a LoanRequest object.
2We check the requested loan amount to see if it is too much.
3If it is too much, we return the JSON (created with a simple string here) that the -test expects.
4If we had a test to catch when the amount is allowable, we could match it to this output.
-
-
-
-
-

The FraudController is about as simple as things get. You can do much more, including -logging, validating the client ID, and so on.

-
-
-

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

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

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

-
-
-
-

3.2. On the Consumer Side

-
-

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

-
-
-

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

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

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

-
-
-
    -
  • -

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

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

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

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

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

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

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

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

4. Step-by-step Guide to Consumer Driven Contracts (CDC) with Contracts on the Producer Side

-
-
-

Consider an example of fraud detection and the loan issuance process. The business -scenario is such that we want to issue loans to people but do not want them to steal from -us. The current implementation of our system grants loans to everybody.

-
-
-

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

-
-
-

Technical remarks

-
-
-
    -
  • -

    Fraud Detection has an artifact-id of http-server

    -
  • -
  • -

    Loan Issuance has an artifact-id of http-client

    -
  • -
  • -

    Both have a group-id of com.example

    -
  • -
  • -

    For the sake of this example the Stub Storage is Nexus/Artifactory

    -
  • -
-
-
-

Social remarks

-
-
-
    -
  • -

    Both the client and the server development teams need to communicate directly and -discuss changes while going through the process

    -
  • -
  • -

    CDC is all about communication

    -
  • -
-
- -
- - - - - -
- - -In this case, the producer owns the contracts. Physically, all of the contracts are -in the producer’s repository. -
-
-
-

4.1. Technical Note

-
-

If you use the SNAPSHOT, Milestone, or Release Candidate versions you need to add the -following section to your build:

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

For simplicity, we use the following acronyms:

-
-
-
    -
  • -

    Loan Issuance (LI): The HTTP client

    -
  • -
  • -

    Fraud Detection (FD): The HTTP server

    -
  • -
  • -

    Spring Cloud Contract (SCC)

    -
  • -
-
-
-
-

4.2. The Consumer Side (Loan Issuance)

-
-

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

-
-
-
    -
  1. -

    Start doing TDD by writing a test for your feature.

    -
  2. -
  3. -

    Write the missing implementation.

    -
  4. -
  5. -

    Clone the Fraud Detection service repository locally.

    -
  6. -
  7. -

    Define the contract locally in the repo of the fraud detection service.

    -
  8. -
  9. -

    Add the Spring Cloud Contract (SCC) plugin.

    -
  10. -
  11. -

    Run the integration tests.

    -
  12. -
  13. -

    File a pull request.

    -
  14. -
  15. -

    Create an initial implementation.

    -
  16. -
  17. -

    Take over the pull request.

    -
  18. -
  19. -

    Write the missing implementation.

    -
  20. -
  21. -

    Deploy your app.

    -
  22. -
  23. -

    Work online.

    -
  24. -
-
-
-

We start with the loan issuance flow, which the following UML diagram shows:

-
-
-
-getting started cdc client -
-
-
-

4.2.1. Start Doing TDD by Writing a Test for Your Feature

-
-

The following listing shows a test that we might use to check whether a loan amount is too -large:

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

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

-
-
-
-

4.2.2. Write the Missing Implementation

-
-

At some point in time, you need to send a request to the Fraud Detection service. Assume -that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the /fraudcheck URL by using the PUT method. -To do so, you might use code similar to the following:

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

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

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

4.2.3. Clone the Fraud Detection service repository locally

-
-

You can start by playing around with the server side contract. To do so, you must first -clone it, by running the following command:

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

4.2.4. Define the Contract Locally in the Repository of the Fraud Detection Service

-
-

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

-
-
- - - - - -
- - -Place the contract in the src/test/resources/contracts/fraud folder. The fraud folder -is important because the producer’s test base class name references that folder. -
-
-
-

The following example shows our contract, in both Groovy and YAML:

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

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

-
-
- - - - - -
- - -You must understand the map notation in order to set up contracts. See the -Groovy docs regarding JSON. -
-
-
-

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

-
-
-
    -
  • -

    If an HTTP request is sent with all of

    -
    -
      -
    • -

      A PUT method on the /fraudcheck endpoint

      -
    • -
    • -

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

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
  • -

    Then an HTTP response is sent to the consumer that

    -
    -
      -
    • -

      Has status 200

      -
    • -
    • -

      Contains a JSON body with the fraudCheckStatus field containing a value of FRAUD and -the rejectionReason field having a value of Amount too high

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
-
-
-

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

-
-
-
-

4.2.5. Add the Spring Cloud Contract Verifier Plugin

-
-

We can add either a Maven or a Gradle plugin. In this example, we show how to add Maven. -First, we add the Spring Cloud Contract BOM, as the following example shows:

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

Next, add the Spring Cloud Contract Verifier Maven plugin, as the following example shows:

-
-
-
-
-
-
            <plugin>
-                <groupId>org.springframework.cloud</groupId>
-                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                <version>${spring-cloud-contract.version}</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
-<!--                    <convertToYaml>true</convertToYaml>-->
-                </configuration>
-                <!-- if additional dependencies are needed e.g. for Pact -->
-                <dependencies>
-                    <dependency>
-                        <groupId>org.springframework.cloud</groupId>
-                        <artifactId>spring-cloud-contract-pact</artifactId>
-                        <version>${spring-cloud-contract.version}</version>
-                    </dependency>
-                </dependencies>
-            </plugin>
-
-
-
-
-
-

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

-
-
-
    -
  • -

    Generate and run tests

    -
  • -
  • -

    Produce and install stubs

    -
  • -
-
-
-

You do not want to generate tests, since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. To do so, run the following commands:

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

Once you run those commands, you should you see something like the following content in the logs:

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

The following line is extremely important:

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

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

-
-
-
-

4.2.6. Running the Integration Tests

-
-

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

-
-
-
    -
  1. -

    Add the Spring Cloud Contract BOM, as follows:

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

    Add the dependency to Spring Cloud Contract Stub Runner, as follows:

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

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

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

Now, when you run your tests, you see something like the following output in the logs:

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

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

-
-
-
-

4.2.7. Filing a Pull Request

-
-

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

-
-
-

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

-
-
-
-
-

4.3. The Producer Side (Fraud Detection server)

-
-

As a developer of the Fraud Detection server (a server to the Loan Issuance service), you -might want to do the following

-
-
-
    -
  • -

    Take over the pull request

    -
  • -
  • -

    Write the missing implementation

    -
  • -
  • -

    Deploy the application

    -
  • -
-
-
-

The following UML diagram shows the fraud detection flow:

-
-
-
-getting started cdc server -
-
-
-

4.3.1. Taking over the Pull Request

-
-

As a reminder, the following listing shows the initial implementation:

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

Then you can run the following commands:

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

You must add the dependencies needed by the autogenerated tests, as follows:

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

In the configuration of the Maven plugin, you must pass the packageWithBaseClasses property, as follows:

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

All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, you should use Rest Assured MVC to -start the server side FraudDetectionController. The following listing shows the -FraudBase class:

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

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

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

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

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

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

-
-
-

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

-
-
-
-

4.3.2. Write the Missing Implementation

-
-

Because you know the expected input and expected output, you can write the missing -implementation as follows:

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

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

-
-
-
-

4.3.3. Deploying Your Application

-
-

Once you finish your work, you can deploy your changes. To do so, you must first merge the -branch by running the following commands:

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

Your CI might run something a command such as ./mvnw clean deploy, which would publish both the -application and the stub artifacts.

-
-
-
-
-

4.4. Consumer Side (Loan Issuance), Final Step

-
-

As a developer of the loan issuance service (a consumer of the Fraud Detection server), I want to:

-
-
-
    -
  • -

    Merge our feature branch to master

    -
  • -
  • -

    Switch to online mode of working

    -
  • -
-
-
-

The following UML diagram shows the final state of the process:

-
-
-
-getting started cdc client final -
-
-
-

4.4.1. Merging a Branch to Master

-
-

The following commands show one way to merge a branch into master with Git:

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

4.4.2. Working Online

-
-

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

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

That’s it. You have finished the tutorial.

-
-
-
-
-
-
-

5. Next Steps

-
-
-

Hopefully, this section provided some of the Spring Cloud Contract basics and got you on your way -to writing your own applications. If you are a task-oriented type of developer, you might -want to jump over to spring.io and check out some of the -getting started guides that solve specific “How do I do that -with Spring?” problems. We also have Spring Cloud Contract-specific -“how-to” reference documentation.

-
-
-

Otherwise, the next logical step is to read Using Spring Cloud Contract. If -you are really impatient, you could also jump ahead and read about -Spring Cloud Contract features.

-
-
-

In addition to that you can check out the following videos:

-
-
-
    -
  • -

    "Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak

    -
  • -
-
-
-
- -
-
-
-
    -
  • -

    "Contract Tests in the Enterprise" by Marcin Grzejszczak

    -
  • -
-
-
-
- -
-
-
-
    -
  • -

    "Why Contract Tests Matter?" by Marcin Grzejszczak

    -
  • -
-
-
-
- -
-
-
-

You can find the default project samples at -samples.

-
-
-

You can find the Spring Cloud Contract workshops here.

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/gradle-project.html b/reference/html/gradle-project.html index 6b1b5d383e..9990b6e5bb 100644 --- a/reference/html/gradle-project.html +++ b/reference/html/gradle-project.html @@ -1,933 +1,12 @@ - - - + + - - - -Gradle Project - - - - - - - - - -
-
- -
-
-

1. Prerequisites

-
-
-

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

-
-
- - - - - -
- - -If you want to use Spock in your projects, you must separately add the -spock-core and spock-spring modules. See Spock’s -documnetation for more information -
-
-
-
-
-

2. Add Gradle Plugin with Dependencies

-
-
-

To add a Gradle plugin with dependencies, you can use code similar to the following:

-
-
-
-
-
Plugin DSL GA versions
-
-
// build.gradle
-plugins {
-  id "groovy"
-  // this will work only for GA versions of Spring Cloud Contract
-  id "org.springframework.cloud.contract" version "${GAVerifierVersion}"
-}
+Page Redirection
 
-dependencyManagement {
-    imports {
-        mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${GAVerifierVersion}"
-    }
-}
-
-dependencies {
-    testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
-    // example with adding Spock core and Spock Spring
-    testCompile "org.spockframework:spock-core:${spockVersion}"
-    testCompile "org.spockframework:spock-spring:${spockVersion}"
-    testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}
-
-
-
-
Plugin DSL non GA versions
-
-
// settings.gradle
-pluginManagement {
-    plugins {
-        id "org.springframework.cloud.contract" version "${verifierVersion}"
-    }
-    repositories {
-        // to pick from local .m2
-        mavenLocal()
-        // for snapshots
-        maven { url "https://repo.spring.io/snapshot" }
-        // for milestones
-        maven { url "https://repo.spring.io/milestone" }
-        // for GA versions
-        gradlePluginPortal()
-    }
-}
-
-// build.gradle
-plugins {
-  id "groovy"
-  id "org.springframework.cloud.contract"
-}
-
-dependencyManagement {
-    imports {
-        mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifierVersion}"
-    }
-}
-
-dependencies {
-    testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
-    // example with adding Spock core and Spock Spring
-    testCompile "org.spockframework:spock-core:${spockVersion}"
-    testCompile "org.spockframework:spock-spring:${spockVersion}"
-    testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}
-
-
-
-
Legacy Plugin Application
-
-
// build.gradle
-buildscript {
-    repositories {
-        mavenCentral()
-    }
-    dependencies {
-        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
-        classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
-        // here you can also pass additional dependencies such as Pact or Kotlin spec e.g.:
-        // classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${verifier_version}"
-    }
-}
-
-apply plugin: 'groovy'
-apply plugin: 'spring-cloud-contract'
-
-dependencyManagement {
-    imports {
-        mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
-    }
-}
-
-dependencies {
-    testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
-    // example with adding Spock core and Spock Spring
-    testCompile "org.spockframework:spock-core:${spockVersion}"
-    testCompile "org.spockframework:spock-spring:${spockVersion}"
-    testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}
-
-
-
-
-
-
-
-

3. Gradle and Rest Assured 2.0

-
-
-

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x -you can add it to the plugins classpath, as the following listing shows:

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

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

-
-
-
-
-

4. Snapshot Versions for Gradle

-
-
-

You can add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as the following listing shows:

-
-
-
-
-
-
/*
- We need to use the [buildscript {}] section when we have to modify
- the classpath for the plugins. If that's not the case this section
- can be skipped.
-
- If you don't need to modify the classpath (e.g. add a Pact dependency),
- then you can just set the [pluginManagement {}] section in [settings.gradle] file.
-
- // settings.gradle
- pluginManagement {
-    repositories {
-        // for snapshots
-        maven {url "https://repo.spring.io/snapshot"}
-        // for milestones
-        maven {url "https://repo.spring.io/milestone"}
-        // for GA versions
-        gradlePluginPortal()
-    }
- }
-
- */
-buildscript {
-    repositories {
-        mavenCentral()
-        mavenLocal()
-        maven { url "https://repo.spring.io/snapshot" }
-        maven { url "https://repo.spring.io/milestone" }
-        maven { url "https://repo.spring.io/release" }
-    }
-}
-
-
-
-
-
-
-
-

5. Add stubs

-
-
-

By default, Spring Cloud Contract Verifier looks for stubs in the -src/test/resources/contracts directory.

-
-
-

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

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

Given the preceding structure, Spring Cloud Contract Verifier creates a test class named -defaultBasePackage.MyService with two methods:

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-
-

6. Running the Plugin

-
-
-

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

-
-
-
-
-

7. Default Setup

-
-
-

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

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

8. Configuring the Plugin

-
-
-

To change the default configuration, you can add a contracts snippet to your Gradle -configuration, as the following listing shows:

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

9. Configuration Options

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsDslDir: Specifies the directory that contains contracts written by using the -GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsProperties: A map that contains properties to be passed to Spring Cloud Contract -components. Those properties might be used by (for example) built-in or custom Stub Downloaders.

    -
  • -
  • -

    sourceSet: Source set where the contracts are stored. If not provided will assume test (e.g. project.sourceSets.test.java for JUnit or project.sourceSets.test.groovy for Spock).

    -
  • -
-
-
-

You can use the following properties when you want to specify the location of the JAR -that contains the contracts:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsMode: Specifies the mode for downloading contracts (whether the -JAR is available offline, remotely, and so on).

    -
  • -
  • -

    deleteStubsAfterTest: If set to false, do not remove any downloaded -contracts from temporary directories.

    -
  • -
  • -

    failOnNoContracts: When enabled, will throw an exception when no contracts were found. Defaults to true.

    -
  • -
  • -

    failOnInProgress: If set to true then if any contracts that are in progress are found, will break the build. On the producer side you need to be explicit about the fact that you have contracts in progress and take into consideration that you might be causing false positive test execution results on the consumer side.. Defaults to true.

    -
  • -
-
-
-

There is also the contractRepository { …​ } closure that contains the following properties

-
-
-
    -
  • -

    repositoryUrl: the URL to the repository with contract definitions

    -
  • -
  • -

    username : Repository username

    -
  • -
  • -

    password : Repository password

    -
  • -
  • -

    proxyPort : the port of the proxy

    -
  • -
  • -

    proxyHost : the host of the proxy

    -
  • -
  • -

    cacheDownloadedContracts : If set to true then will cache the folder where non snapshot contract artifacts got downloaded. Defaults to true.

    -
  • -
-
-
-

You can also turn on the following experimental features in the plugin:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-
-
-

10. Single Base Class for All Tests

-
-
-

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified. The following example shows how to do so:

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

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

-
-
-
-
-

11. Different Base Classes for Contracts

-
-
-

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

-
-
-
    -
  • -

    Follow a convention by providing the packageWithBaseClasses

    -
  • -
  • -

    Provide explicit mapping by using baseClassMappings

    -
  • -
-
-
-

11.1. By Convention

-
-

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

-
-
-
-
-
-
packageWithBaseClasses = 'com.example.base'
-
-
-
-
-
-
-

11.2. By Mapping

-
-

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

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

Let’s assume that you have contracts in the following directories: - - src/test/resources/contract/com/ - - src/test/resources/contract/foo/

-
-
-

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

-
-
-
-
-
-

12. Invoking Generated Tests

-
-
-

To ensure that the provider side is compliant with your defined contracts, you need to run -the following command:

-
-
-
-
-
-
./gradlew generateContractTests test
-
-
-
-
-
-
-
-

13. Pushing Stubs to SCM

-
-
-

If you use the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, you can call the pushStubsToScm -task by running the following command:

-
-
-
-
-
-
$ ./gradlew pushStubsToScm
-
-
-
-
-
-

Under [scm-stub-downloader] you can find all possible -configuration options that you can pass either through -the contractsProperties field (for example, contracts { contractsProperties = [foo:"bar"] }), -through the contractsProperties method (for example, contracts { contractsProperties([foo:"bar"]) }), -or through a system property or an environment variable.

-
-
-
-
-

14. Spring Cloud Contract Verifier on the Consumer Side

-
-
-

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

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

When present, JSON stubs can be used in automated tests to consume a service. The -following example shows how to do so:

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

In the preceding example, LoanApplication makes a call to the FraudDetection service. -This request is handled by a WireMock server configured with stubs that were generated by -Spring Cloud Contract Verifier.

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/howto.html b/reference/html/howto.html index 2be2d87303..9990b6e5bb 100644 --- a/reference/html/howto.html +++ b/reference/html/howto.html @@ -1,2558 +1,12 @@ - - - + + - - - -“How-to” Guides - - - - - - - - - -
-
-
-
-

This section provides answers to some common “how do I do that…​” questions -that often arise when using Spring Cloud Contract. Its coverage is not exhaustive, but it -does cover quite a lot.

-
-
-

If you have a specific problem that we do not cover here, you might want to check out -stackoverflow.com to see if someone has -already provided an answer. Stack Overflow is also a great place to ask new questions (please use -the spring-cloud-contract tag).

-
-
-

We are also more than happy to extend this section. If you want to add a “how-to”, -send us a pull request.

-
-
-
-
-

1. Why use Spring Cloud Contract?

-
-
-

Spring Cloud Contract works great in a polyglot environment. This project has a lot of -really interesting features. Quite a few of these features definitely make -Spring Cloud Contract Verifier stand out on the market of Consumer Driven Contract -(CDC) tooling. The most interesting features include the following:

-
-
-
    -
  • -

    Ability to do CDC with messaging.

    -
  • -
  • -

    Clear and easy to use, statically typed DSL.

    -
  • -
  • -

    Ability to copy-paste your current JSON file to the contract and only edit its elements.

    -
  • -
  • -

    Automatic generation of tests from the defined Contract.

    -
  • -
  • -

    Stub Runner functionality: The stubs are automatically downloaded at runtime from Nexus/Artifactory.

    -
  • -
  • -

    Spring Cloud integration: No discovery service is needed for integration tests.

    -
  • -
  • -

    Spring Cloud Contract integrates with Pact and provides easy hooks to extend its functionality.

    -
  • -
  • -

    Ability to add support for any language & framework through Docker.

    -
  • -
-
-
-
-
-

2. How Can I Write Contracts in a Language Other than Groovy?

-
-
-

You can write a contract in YAML. See this section for more information.

-
-
-

We are working on allowing more ways of describing the contracts. You can check the github-issues for more information.

-
-
-
-
-

3. How Can I Provide Dynamic Values to a Contract?

-
-
-

One of the biggest challenges related to stubs is their reusability. Only if they can be widely used can they serve their purpose. -The hard-coded values (such as dates and IDs) of request and response elements generally make that difficult. -Consider the following JSON request:

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

Now consider the following JSON response:

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

Imagine the pain required to set the proper value of the time field (assume that this content is generated by the -database) by changing the clock in the system or by providing stub implementations of data providers. The same is related -to the field called id. You could create a stubbed implementation of UUID generator, but doing so makes little sense.

-
-
-

So, as a consumer, you want to send a request that matches any form of a time or any UUID. That way, your system -works as usual, generating data without you having to stub out anything. Assume that, in case of the aforementioned -JSON, the most important part is the body field. You can focus on that and provide matching for other fields. In other words, -you would like the stub to work as follows:

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

As far as the response goes, as a consumer, you need a concrete value on which you can operate. -Consequently, the following JSON is valid:

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

In the previous sections, we generated tests from contracts. So, from the producer’s side, the situation looks -much different. We parse the provided contract, and, in the test, we want to send a real request to your endpoints. -So, for the case of a producer for the request, we cannot have any sort of matching. We need concrete values on which the -producer’s backend can work. Consequently, the following JSON would be valid:

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

On the other hand, from the point of view of the validity of the contract, the response does not necessarily have to -contain concrete values for time or id. Suppose you generate those on the producer side. Again, you -have to do a lot of stubbing to ensure that you always return the same values. That is why, from the producer’s side -you might want the following response:

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

How can you then provide a matcher for the consumer and a concrete value for the producer (and the opposite at some other time)? -Spring Cloud Contract lets you provide a dynamic value. That means that it can differ for both -sides of the communication.

-
-
-

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

-
-
- - - - - -
- - -Read the Groovy docs related to JSON to understand how to -properly structure the request and response bodies. -
-
-
-
-
-

4. How to Do Stubs versioning?

-
-
-

This section covers version of the stubs, which you can handle in a number of different ways:

-
- -
-

4.1. API Versioning

-
-

What does versioning really mean? If you refer to the API version, there are -different approaches:

-
-
-
    -
  • -

    Use hypermedia links and do not version your API by any means

    -
  • -
  • -

    Pass the version through headers and URLs

    -
  • -
-
-
-

We do not try to answer the question of which approach is better. You should pick whatever -suits your needs and lets you generate business value.

-
-
-

Assume that you do version your API. In that case, you should provide as many contracts with as many versions as you support. -You can create a subfolder for every version or append it to the contract name — whatever suits you best.

-
-
-
-

4.2. JAR versioning

-
-

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

-
-
-

Assume that you do continuous delivery and deployment, which means that you generate a new version of -the jar each time you go through the pipeline and that the jar can go to production at any time. For example, your jar version -looks like the following (because it got built on the 20.10.2016 at 20:15:21) :

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

In that case your, generated stub jar should look like the following:

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

In this case, you should, inside your application.yml or @AutoConfigureStubRunner when -referencing stubs, provide the latest version of the stubs. You can do that by passing the -+ sign. the following example shows how to do so:

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

If the versioning, however, is fixed (for example, 1.0.4.RELEASE or 2.1.1), you have to set the concrete value of the jar -version. The following example shows how to do so for version 2.1.1:

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

4.3. Development or Production Stubs

-
-

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

-
-
-

The following example works for tests that use the development version of the stubs:

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

The following example works for tests that use the production version of stubs:

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

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

-
-
-
-
-
-

5. How Can I use a Common Repository with Contracts Instead of Storing Them with the Producer?

-
-
-

Another way of storing contracts, rather than having them with the producer, is to keep -them in a common place. This situation can be related to security issues (where the -consumers cannot clone the producer’s code). Also if you keep contracts in a single place, -then you, as a producer, know how many consumers you have and which consumer you may break -with your local changes.

-
-
-

5.1. Repo Structure

-
-

Assume that we have a producer with coordinates of com.example:server and three -consumers: client1, client2, and client3. Then, in the repository with common -contracts, you could have the following setup (which you can check out -here). -The following listing shows such a structure:

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

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

-
-
-

The following example shows a pom.xml inside the server folder:

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

There are no dependencies other than the Spring Cloud Contract Maven Plugin. -Those pom files are necessary for the consumer side to run mvn clean install -DskipTests to locally install -the stubs of the producer project.

-
-
-

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

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

It uses the assembly plugin to build the JAR with all the contracts. The following example -shows such a setup:

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

5.2. Workflow

-
-

The workflow assumes that Spring Cloud Contract is set up both on the consumer and on the -producer side. There is also the proper plugin setup in the common repository with -contracts. The CI jobs are set for a common repository to build an artifact of all -contracts and upload it to Nexus/Artifactory. The following image shows the UML for this -workflow:

-
-
-
-how to common repo -
-
-
-
-

5.3. Consumer

-
-

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

-
-
- - - - - -
- - -You need to have Maven installed locally -
-
-
-
-

5.4. Producer

-
-

As a producer, you can to alter the Spring Cloud Contract Verifier to provide the URL and -the dependency of the JAR that contains the contracts, as follows:

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

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

-
-
-

The rest of the flow looks the same.

-
-
-
-

5.5. How Can I Define Messaging Contracts per Topic Rather than per Producer?

-
-

To avoid messaging contracts duplication in the common repository, when a few producers write messages to one topic, -we could create a structure in which the REST contracts are placed in a folder per producer and messaging -contracts are placed in the folder per topic.

-
-
-

5.5.1. For Maven Projects

-
-

To make it possible to work on the producer side, we should specify an inclusion pattern for -filtering common repository jar files by messaging topics we are interested in. The -includedFiles property of the Maven Spring Cloud Contract plugin -lets us do so. Also, contractsPath need to be specified, since the default path would be -the common repository groupid/artifactid. The following example shows a Maven -plugin for Spring Cloud Contract:

-
-
-
-
-
-
<plugin>
-   <groupId>org.springframework.cloud</groupId>
-   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-   <version>${spring-cloud-contract.version}</version>
-   <configuration>
-      <contractsMode>REMOTE</contractsMode>
-      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
-      <contractDependency>
-         <groupId>com.example</groupId>
-         <artifactId>common-repo-with-contracts</artifactId>
-         <version>+</version>
-      </contractDependency>
-      <contractsPath>/</contractsPath>
-      <baseClassMappings>
-         <baseClassMapping>
-            <contractPackageRegex>.*messaging.*</contractPackageRegex>
-            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
-         </baseClassMapping>
-         <baseClassMapping>
-            <contractPackageRegex>.*rest.*</contractPackageRegex>
-            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
-         </baseClassMapping>
-      </baseClassMappings>
-      <includedFiles>
-         <includedFile>**/${project.artifactId}/**</includedFile>
-         <includedFile>**/${first-topic}/**</includedFile>
-         <includedFile>**/${second-topic}/**</includedFile>
-      </includedFiles>
-   </configuration>
-</plugin>
-
-
-
-
-
- - - - - -
- - -Many of the values in the preceding Maven plugin can be changed. We included it for -illustration purposes rather than trying to provide a “typical” example. -
-
-
-
-

5.5.2. For Gradle Projects

-
-

To work with a Gradle project:

-
-
-
    -
  1. -

    Add a custom configuration for the common repository dependency, as follows:

    -
    -
    -
    -
    -
    ext {
    -    contractsGroupId = "com.example"
    -    contractsArtifactId = "common-repo"
    -    contractsVersion = "1.2.3"
    -}
    -
    -configurations {
    -    contracts {
    -        transitive = false
    -    }
    -}
    -
    -
    -
    -
    -
  2. -
  3. -

    Add the common repository dependency to your classpath, as follows:

    -
    -
    -
    -
    -
    dependencies {
    -    contracts "${contractsGroupId}:${contractsArtifactId}:${contractsVersion}"
    -    testCompile "${contractsGroupId}:${contractsArtifactId}:${contractsVersion}"
    -}
    -
    -
    -
    -
    -
  4. -
  5. -

    Download the dependency to an appropriate folder, as follows:

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

    Unzip the JAR, as follows:

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

    Cleanup unused contracts, as follows:

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

    Create task dependencies, as follows:

    -
    -
    -
    -
    -
    unzipContracts.dependsOn("getContracts")
    -deleteUnwantedContracts.dependsOn("unzipContracts")
    -build.dependsOn("deleteUnwantedContracts")
    -
    -
    -
    -
    -
  12. -
  13. -

    Configure the plugin by specifying the directory that contains the contracts, by setting -the contractsDslDir property, as follows:

    -
    -
    -
    -
    -
    contracts {
    -    contractsDslDir = new File("${buildDir}/unpackedContracts")
    -}
    -
    -
    -
    -
    -
  14. -
-
-
-
-
-
-
-

6. How Can I Use Git as the Storage for Contracts and Stubs?

-
-
-

In the polyglot world, there are languages that do not use binary storages, as -Artifactory or Nexus do. Starting from Spring Cloud Contract version 2.0.0, we provide -mechanisms to store contracts and stubs in a SCM (Source Control Management) repository. Currently, the -only supported SCM is Git.

-
-
-

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

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

Under the META-INF folder:

-
-
-
    -
  • -

    We group applications by groupId (such as com.example).

    -
  • -
  • -

    Each application is represented by its artifactId (for example, beer-api-producer-git).

    -
  • -
  • -

    Next, each application is organized by its version (such as 0.0.1-SNAPSHOT). Starting -from Spring Cloud Contract version 2.1.0, you can specify the versions as follows -(assuming that your versions follow semantic versioning):

    -
    -
      -
    • -

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

      -
      -
        -
      • -

        If you have 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT, and 2.0.0.RELEASE, we assume -that the latest is 2.0.0.BUILD-SNAPSHOT.

        -
      • -
      • -

        If you have 1.0.0.RELEASE and 2.0.0.RELEASE, we assume that the latest is 2.0.0.RELEASE.

        -
      • -
      • -

        If you have a version called latest or +, we will pick that folder.

        -
      • -
      -
      -
    • -
    • -

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

      -
      -
        -
      • -

        If you have 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT, and 2.0.0.RELEASE we assume -that the latest is 2.0.0.RELEASE.

        -
      • -
      • -

        If you have a version called release, we pick that folder.

        -
      • -
      -
      -
    • -
    -
    -
  • -
-
-
-

Finally, there are two folders:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

6.1. Protocol Convention

-
-

To control the type and location of the source of contracts (whether -binary storage or an SCM repository), you can use the protocol in the URL of -the repository. Spring Cloud Contract iterates over registered protocol resolvers -and tries to fetch the contracts (by using a plugin) or stubs (from Stub Runner).

-
-
-

For the SCM functionality, currently, we support the Git repository. To use it, -in the property where the repository URL needs to be placed, you have to prefix -the connection URL with git://. The following listing shows some examples:

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

6.2. Producer

-
-

For the producer, to use the SCM (Source Control Management) approach, we can reuse the -same mechanism we use for external contracts. We route Spring Cloud Contract -to use the SCM implementation from the URL that starts with -the git:// protocol.

-
-
- - - - - -
- - -You have to manually add the pushStubsToScm -goal in Maven or execute (bind) the pushStubsToScm task in -Gradle. We do not push stubs to the origin of your git -repository. -
-
-
-

The following listing includes the relevant parts both Maven and Gradle build files:

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

It is also possible to further customise the publishStubsToScm gradle task. In the following example, -the task is customised to pick contracts from a local git repository:

-
-
-
gradle
-
-
publishStubsToScm {
-    // We want to modify the default set up of the plugin when publish stubs to scm is called
-    // We want to pick contracts from a Git repository
-    contractDependency {
-        stringNotation = "${project.group}:${project.name}:${project.version}"
-    }
-    /*
-    We reuse the contract dependency section to set up the path
-    to the folder that contains the contract definitions. In our case the
-    path will be /groupId/artifactId/version/contracts
-     */
-    contractRepository {
-        repositoryUrl = "git://file://${new File(project.rootDir, "../target")}/contract_empty_git/"
-    }
-    // We set the contracts mode to `LOCAL`
-    contractsMode = "LOCAL"
-    }
-
-
-
-
-
IMPORTANT
-
-

Starting with 2.3.0.RELEASE the customize{} closure previously used for the -publishStubsToScm customization is no longer available. The settings should be applied directly -within the publishStubsToScm closure as in the example above.

-
-
-
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    A git project is cloned to a temporary directory

    -
  • -
  • -

    The SCM stub downloader goes to META-INF/groupId/artifactId/version/contracts folder -to find contracts. For example, for com.example:foo:1.0.0, the path would be -META-INF/com.example/foo/1.0.0/contracts.

    -
  • -
  • -

    Tests are generated from the contracts.

    -
  • -
  • -

    Stubs are created from the contracts.

    -
  • -
  • -

    Once the tests pass, the stubs are committed in the cloned repository.

    -
  • -
  • -

    Finally, a push is sent to that repo’s origin.

    -
  • -
-
-
-
-

6.3. Producer with Contracts Stored Locally

-
-

Another option to use the SCM as the destination for stubs and contracts is to store the -contracts locally, with the producer, and only push the contracts and the stubs to SCM. -The following listing shows the setup required to achieve this with Maven and Gradle:

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

With such a setup:

-
-
-
    -
  • -

    Contracts from the default src/test/resources/contracts directory are picked.

    -
  • -
  • -

    Tests are generated from the contracts.

    -
  • -
  • -

    Stubs are created from the contracts.

    -
  • -
  • -

    Once the tests pass:

    -
    -
      -
    • -

      The git project is cloned to a temporary directory.

      -
    • -
    • -

      The stubs and contracts are committed in the cloned repository.

      -
    • -
    -
    -
  • -
  • -

    Finally, a push is done to that repository’s origin.

    -
  • -
-
-
-
-

6.4. Keeping Contracts with the Producer and Stubs in an External Repository

-
-

You can also keep the contracts in the producer repository but keep the stubs in an external git repository. -This is most useful when you want to use the base consumer-producer collaboration flow but cannot -use an artifact repository to store the stubs.

-
-
-

To do so, use the usual producer setup and then add the pushStubsToScm goal and set -contractsRepositoryUrl to the repository where you want to keep the stubs.

-
-
-
-

6.5. Consumer

-
-

On the consumer side, when passing the repositoryRoot parameter, -either from the @AutoConfigureStubRunner annotation, the -JUnit rule, JUnit 5 extension, or properties, you can pass the URL of the -SCM repository, prefixed with the git:// protocol. The following example shows how to do so:

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

With such a setup:

-
-
-
    -
  • -

    The git project is cloned to a temporary directory.

    -
  • -
  • -

    The SCM stub downloader goes to thje META-INF/groupId/artifactId/version/ folder -to find stub definitions and contracts. For example, for com.example:foo:1.0.0, the path would be -META-INF/com.example/foo/1.0.0/.

    -
  • -
  • -

    Stub servers are started and fed with mappings.

    -
  • -
  • -

    Messaging definitions are read and used in the messaging tests.

    -
  • -
-
-
-
-
-
-

7. How Can I Use the Pact Broker?

-
-
-

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

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

7.1. How to Work with Pact

-
-

Spring Cloud Contract includes support for the Pact representation of -contracts up until version 4. Instead of using the DSL, you can use Pact files. In this section, we -show how to add Pact support for your project. Note, however, that not all functionality is supported. -Starting with version 3, you can combine multiple matchers for the same element; -you can use matchers for the body, headers, request and path; and you can use value generators. -Spring Cloud Contract currently only supports multiple matchers that are combined by using the AND rule logic. -Next to that, the request and path matchers are skipped during the conversion. -When using a date, time, or datetime value generator with a given format, -the given format is skipped and the ISO format is used.

-
-
-
-

7.2. Pact Converter

-
-

In order to properly support the Spring Cloud Contract way of doing messaging -with Pact, you have to provide some additional meta data entries.

-
-
-

To define the destination to which a message gets sent, you have to -set a metaData entry in the Pact file with the sentTo key equal to the destination to - which a message is to be sent (for example, "metaData": { "sentTo": "activemq:output" }).

-
-
-
-

7.3. Pact Contract

-
-

Spring Cloud Contract can read the Pact JSON definition. You can place the file in the -src/test/resources/contracts folder. Remember to put the spring-cloud-contract-pact dependency to your classpath. The following example shows such a Pact contract:

-
-
-
-
-
-
{
-  "provider": {
-    "name": "Provider"
-  },
-  "consumer": {
-    "name": "Consumer"
-  },
-  "interactions": [
-    {
-      "description": "",
-      "request": {
-        "method": "PUT",
-        "path": "/pactfraudcheck",
-        "headers": {
-          "Content-Type": "application/json"
-        },
-        "body": {
-          "clientId": "1234567890",
-          "loanAmount": 99999
-        },
-        "generators": {
-          "body": {
-            "$.clientId": {
-              "type": "Regex",
-              "regex": "[0-9]{10}"
-            }
-          }
-        },
-        "matchingRules": {
-          "header": {
-            "Content-Type": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "application/json.*"
-                }
-              ],
-              "combine": "AND"
-            }
-          },
-          "body": {
-            "$.clientId": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "[0-9]{10}"
-                }
-              ],
-              "combine": "AND"
-            }
-          }
-        }
-      },
-      "response": {
-        "status": 200,
-        "headers": {
-          "Content-Type": "application/json"
-        },
-        "body": {
-          "fraudCheckStatus": "FRAUD",
-          "rejection.reason": "Amount too high"
-        },
-        "matchingRules": {
-          "header": {
-            "Content-Type": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "application/json.*"
-                }
-              ],
-              "combine": "AND"
-            }
-          },
-          "body": {
-            "$.fraudCheckStatus": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "FRAUD"
-                }
-              ],
-              "combine": "AND"
-            }
-          }
-        }
-      }
-    }
-  ],
-  "metadata": {
-    "pact-specification": {
-      "version": "3.0.0"
-    },
-    "pact-jvm": {
-      "version": "3.5.13"
-    }
-  }
-}
-
-
-
-
-
-
-

7.4. Pact for Producers

-
-

On the producer side, you must add two additional dependencies to your plugin -configuration. One is the Spring Cloud Contract Pact support, and the other represents -the current Pact version that you use. The following listing shows how to do so for both -Maven and Gradle:

-
-
-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
// if additional dependencies are needed e.g. for Pact
-classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"
-
-
-
-
-
-

When you execute the build of your application, a test and stub is generated. The following -example shows a test and stub that came from this process:

-
-
-
-
-
test
-
-
@Test
-    public void validate_shouldMarkClientAsFraud() throws Exception {
-        // given:
-            MockMvcRequestSpecification request = given()
-                    .header("Content-Type", "application/vnd.fraud.v1+json")
-                    .body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
-
-        // when:
-            ResponseOptions response = given().spec(request)
-                    .put("/fraudcheck");
-
-        // then:
-            assertThat(response.statusCode()).isEqualTo(200);
-            assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
-        // and:
-            DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-            assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
-        // and:
-            assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
-    }
-
-
-
-
stub
-
-
{
-  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "request" : {
-    "url" : "/fraudcheck",
-    "method" : "PUT",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['loanAmount'] = 99999)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
-    "headers" : {
-      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
-    },
-    "transformers" : [ "response-template" ]
-  },
-}
-
-
-
-
-
-
-

7.5. Pact for Consumers

-
-

On the consumer side, you must add two additional dependencies to your project -dependencies. One is the Spring Cloud Contract Pact support, and the other represents the -current Pact version that you use. The following listing shows how to do so for both -Maven and Gradle:

-
-
-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-
-
-

7.6. Communicating with the Pact Broker

-
-

Whenever the repositoryRoot property starts with a Pact protocol -(starts with pact://), the stub downloader tries -to fetch the Pact contract definitions from the Pact Broker. -Whatever is set after pact:// is parsed as the Pact Broker URL.

-
-
-

By setting environment variables, system properties, or properties set -inside the plugin or contracts repository configuration, you can -tweak the downloader’s behavior. The following table describes the -properties:

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 1. Pact Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

-

* stubrunner.properties.pactbroker.host (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

The URL of the Pact Broker.

* pactbroker.port (plugin prop)

-

* stubrunner.properties.pactbroker.port (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

The port of Pact Broker.

* pactbroker.protocol (plugin prop)

-

* stubrunner.properties.pactbroker.protocol (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

The protocol of Pact Broker.

* pactbroker.tags (plugin prop)

-

* stubrunner.properties.pactbroker.tags (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

The tags that should be used to fetch the stub.

* pactbroker.auth.scheme (plugin prop)

-

* stubrunner.properties.pactbroker.auth.scheme (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

The kind of authentication that should be used to connect to the Pact Broker.

* pactbroker.auth.username (plugin prop)

-

* stubrunner.properties.pactbroker.auth.username (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

The username to use when connecting to the Pact Broker.

* pactbroker.auth.password (plugin prop)

-

* stubrunner.properties.pactbroker.auth.password (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

The password to use when connecting to the Pact Broker.

* pactbroker.provider-name-with-group-id (plugin prop)

-

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name is a combination of groupId:artifactId. If false, only artifactId is used.

-
-
-

7.7. Flow: Consumer Contract approach with Pact Broker | Consumer Side

-
-

The consumer uses the Pact framework to generate Pact files. The -Pact files are sent to the Pact Broker. You can find an example of such a setup -here.

-
-
-
-

7.8. Flow: Consumer Contract Approach with Pact Broker on the Producer Side

-
-

For the producer to use the Pact files from the Pact Broker, we can reuse the -same mechanism we use for external contracts. We route Spring Cloud Contract -to use the Pact implementation with the URL that contains -the pact:// protocol. You can pass the URL to the -Pact Broker. You can find an example of such a setup -here. -The following listing shows the configuration details for both Maven and Gradle:

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

With such a setup:

-
-
-
    -
  • -

    Pact files are downloaded from the Pact Broker.

    -
  • -
  • -

    Spring Cloud Contract converts the Pact files into tests and stubs.

    -
  • -
  • -

    The JAR with the stubs gets automatically created, as usual.

    -
  • -
-
-
-
-

7.9. Flow: Producer Contract approach with Pact on the Consumer Side

-
-

In the scenario where you do not want to do the consumer contract approach -(for every single consumer, define the expectations) but you prefer -to do producer contracts (the producer provides the contracts and -publishes stubs), you can use Spring Cloud Contract with the -Stub Runner option. You can find an example of such a setup -here.

-
-
-

Remember to add the Stub Runner and Spring Cloud Contract Pact modules -as test dependencies.

-
-
-

The following listing shows the configuration details for both Maven and Gradle:

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

Next, you can pass the URL of the Pact Broker to repositoryRoot, prefixed -with pact:// protocol (for example, pact://http://localhost:8085), as the following -example shows:

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

With such a setup:

-
-
-
    -
  • -

    Pact files are downloaded from the Pact Broker.

    -
  • -
  • -

    Spring Cloud Contract converts the Pact files into stub definitions.

    -
  • -
  • -

    The stub servers are started and fed with stubs.

    -
  • -
-
-
-
-
-
-

8. How Can I Debug the Request/Response Being Sent by the Generated Tests Client?

-
-
-

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

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

9. How Can I Debug the Mapping, Request, or Response Being Sent by WireMock?

-
-
-

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

-
-
-

To turn off this feature, set WireMock logging to ERROR, as follows:

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

10. How Can I See What Got Registered in the HTTP Server Stub?

-
-
-

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

-
-
-
-
-

11. How Can I Reference Text from File?

-
-
-

In version 1.2.0, we added this ability. You can call a file(…​) method in the -DSL and provide a path relative to where the contract lies. -If you use YAML, you can use the bodyFromFile property.

-
-
-
-
-

12. How Can I Generate Pact, YAML, or X files from Spring Cloud Contract Contracts?

-
-
-

Spring Cloud Contract comes with a ToFileContractsTransformer class that lets you dump -contracts as files for the given ContractConverter. It contains a static void main -method that lets you execute the transformer as an executable. It takes the following -arguments:

-
-
-
    -
  • -

    argument 1 : FQN: Fully qualified name of the ContractConverter (for example, PactContractConverter). REQUIRED.

    -
  • -
  • -

    argument 2 : path: Path where the dumped files should be stored. OPTIONAL — defaults to target/converted-contracts.

    -
  • -
  • -

    argument 3 : path: Path were the contracts should be searched for. OPTIONAL — defaults to src/test/resources/contracts.

    -
  • -
-
-
-

After executing the transformer, the Spring Cloud Contract files are processed and, -depending on the provided FQN of the ContractTransformer, the contracts are transformed -to the required format and dumped to the provided folder.

-
-
-

The following example shows how to configure Pact integration for both Maven and Gradle:

-
-
-
-
-
maven
-
-
<plugin>
-    <groupId>org.codehaus.mojo</groupId>
-    <artifactId>exec-maven-plugin</artifactId>
-    <version>1.6.0</version>
-    <executions>
-        <execution>
-            <id>convert-dsl-to-pact</id>
-            <phase>process-test-classes</phase>
-            <configuration>
-                <classpathScope>test</classpathScope>
-                <mainClass>
-                    org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer
-                </mainClass>
-                <arguments>
-                    <argument>
-                        org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter
-                    </argument>
-                    <argument>${project.basedir}/target/pacts</argument>
-                    <argument>
-                        ${project.basedir}/src/test/resources/contracts
-                    </argument>
-                </arguments>
-            </configuration>
-            <goals>
-                <goal>java</goal>
-            </goals>
-        </execution>
-    </executions>
-</plugin>
-
-
-
-
gradle
-
-
task convertContracts(type: JavaExec) {
-    main = "org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer"
-    classpath = sourceSets.test.compileClasspath
-    args("org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter",
-            "${project.rootDir}/build/pacts", "${project.rootDir}/src/test/resources/contracts")
-}
-
-test.dependsOn("convertContracts")
-
-
-
-
-
-
-
-

13. How Can I Work with Transitive Dependencies?

-
-
-

The Spring Cloud Contract plugins add the tasks that create the stubs jar for you. One -problem that arises is that, when reusing the stubs, you can mistakenly import all of -that stub’s dependencies. When building a Maven artifact, even though you have a couple -of different jars, all of them share one pom, as the following listing shows:

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

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

-
-
-
    -
  • -

    Mark all application dependencies as optional

    -
  • -
  • -

    Create a separate artifactid for the stubs

    -
  • -
  • -

    Exclude dependencies on the consumer side

    -
  • -
-
-
-

13.1. How Can I Mark All Application Dependencies as Optional?

-
-

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

-
-
-
-

13.2. How can I Create a Separate artifactid for the Stubs?

-
-

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

-
-
-
-

13.3. How can I 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.

-
-
-
-
-
-

14. How can I Generate Spring REST Docs Snippets from the Contracts?

-
-
-

When you want to include the requests and responses of your API by using Spring REST Docs, -you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. -To do so, include the following dependencies (if you have not already done so):

-
-
-
-
-
maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-starter-contract-verifier</artifactId>
-    <scope>test</scope>
-</dependency>
-<dependency>
-    <groupId>org.springframework.restdocs</groupId>
-    <artifactId>spring-restdocs-mockmvc</artifactId>
-    <optional>true</optional>
-</dependency>
-
-
-
-
gradle
-
-
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
-
-
-
-
-
-

Next, you need to make some changes to your base class. The following examples use -WebAppContext and the standalone option with RestAssured:

-
-
-
-
-
WebAppContext
-
-
package com.example.fraud;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.restdocs.JUnitRestDocumentation;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = Application.class)
-public abstract class FraudBaseWithWebAppSetup {
-
-    private static final String OUTPUT = "target/generated-snippets";
-
-    @Rule
-    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
-
-    @Rule
-    public TestName testName = new TestName();
-
-    @Autowired
-    private WebApplicationContext context;
-
-    @Before
-    public void setup() {
-        RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
-                .apply(documentationConfiguration(this.restDocumentation))
-                .alwaysDo(document(
-                        getClass().getSimpleName() + "_" + testName.getMethodName()))
-                .build());
-    }
-
-    protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
-        assert rejectionReason == null;
-    }
-
-}
-
-
-
-
Standalone
-
-
package com.example.fraud;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-
-import org.springframework.restdocs.JUnitRestDocumentation;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
-
-public abstract class FraudBaseWithStandaloneSetup {
-
-    private static final String OUTPUT = "target/generated-snippets";
-
-    @Rule
-    public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
-
-    @Rule
-    public TestName testName = new TestName();
-
-    @Before
-    public void setup() {
-        RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
-                .standaloneSetup(new FraudDetectionController())
-                .apply(documentationConfiguration(this.restDocumentation))
-                .alwaysDo(document(
-                        getClass().getSimpleName() + "_" + testName.getMethodName())));
-    }
-
-}
-
-
-
-
-
- - - - - -
- - -You need not specify the output directory for the generated snippets (since version 1.2.0.RELEASE of Spring REST Docs). -
-
-
-
-
-

15. How can I Use Stubs from a Location

-
-
-

If you want to fetch contracts or stubs from a given location without cloning a repo or fetching a JAR, just use the stubs:// protocol when providing the repository root argument for Stub Runner or the Spring Cloud Contract plugin. You can read more about this in this section of the documentation.

-
-
-
-
-

16. How can I Generate Stubs at Runtime

-
-
-

If you want to generate stubs at runtime for contracts, it’s enough to switch the generateStubs property in the @AutoConfigureStubRunner annotation, or call the withGenerateStubs(true) method on the JUnit Rule or Extension. You can read more about this in this section of the documentation.

-
-
-
-
-

17. How can I Make The Build Pass if There Are No Contracts or Stubs

-
-
-

If you want Stub Runner not to fail if no stubs were found, it’s enough to switch the generateStubs property in the @AutoConfigureStubRunner annotation, or call the withFailOnNoStubs(false) method on the JUnit Rule or Extension. You can read more about this in this section of the documentation.

-
-
-

If you want the plugins not to fail the build when no contracts were found, you can set the failOnNoStubs flag in Maven or call the contractRepository { failOnNoStubs(false) } Closure in Gradle.

-
-
-
-
-

18. How can I Mark that a Contract Is in Progress

-
-
-

If a contract is in progress, it means that the on the producer side tests will not be generated, but the stub will be. You can read more about this in this section of the documentation.

-
-
-

In a CI build, before going to production, you would like to ensure that no in progress contracts are there on the classpath. That’s because you may lead to false positives. That’s why, by default, in the Spring Cloud Contract plugin, we set the value of failOnInProgress to true. If you want to allow such contracts when tests are to be generated, just set the flag to false.

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/legal.html b/reference/html/legal.html index a926820df1..9990b6e5bb 100644 --- a/reference/html/legal.html +++ b/reference/html/legal.html @@ -1,140 +1,12 @@ - - - + + - - - -Legal - - - - - - - - - -
-
-
-
-

3.0.0-SNAPSHOT

-
-
-

Copyright © 2012-2020

-
-
-

Copies of this document may be made for your own use and for distribution to -others, provided that you do not charge any fee for such copies and further -provided that each copy contains this Copyright Notice, whether distributed in -print or electronically.

-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/links.html b/reference/html/links.html index cbbcea3ac4..9990b6e5bb 100644 --- a/reference/html/links.html +++ b/reference/html/links.html @@ -1,137 +1,12 @@ - - - + + - - - -Links - - + - - - - - - -
-
- -
-
-

The following links may be helpful when working with Spring Cloud Contract:

-
- -
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/maven-project.html b/reference/html/maven-project.html index 43b42ae5a6..9990b6e5bb 100644 --- a/reference/html/maven-project.html +++ b/reference/html/maven-project.html @@ -1,1110 +1,12 @@ - - - + + - - - -Maven Project - - - - - - - - - -
-
-
-
-

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

-
- -
-

You can also check the plugin’s documentation here.

-
-
-
-
-

1. Adding the Maven Plugin

-
-
-

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

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

Next, add the Spring Cloud Contract Verifier Maven plugin, as follows:

-
-
-
-
-
-
            <plugin>
-                <groupId>org.springframework.cloud</groupId>
-                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                <version>${spring-cloud-contract.version}</version>
-                <extensions>true</extensions>
-                <configuration>
-                    <packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
-<!--                    <convertToYaml>true</convertToYaml>-->
-                </configuration>
-                <!-- if additional dependencies are needed e.g. for Pact -->
-                <dependencies>
-                    <dependency>
-                        <groupId>org.springframework.cloud</groupId>
-                        <artifactId>spring-cloud-contract-pact</artifactId>
-                        <version>${spring-cloud-contract.version}</version>
-                    </dependency>
-                </dependencies>
-            </plugin>
-
-
-
-
-
-

You can read more in the -spring-cloud-contract-maven-plugin/index.html[Spring -Cloud Contract Maven Plugin Documentation].

-
-
-

Sometimes, regardless of the picked IDE, you can see that the target/generated-test-source folder is not visible on the IDE’s classpath. To ensure that it’s always there, you can add the following entry to your pom.xml

-
-
-
-
-
-
<plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>build-helper-maven-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>add-source</id>
-                        <phase>generate-test-sources</phase>
-                        <goals>
-                            <goal>add-test-source</goal>
-                        </goals>
-                        <configuration>
-                            <sources>
-                                <source>${project.build.directory}/generated-test-sources/contracts/</source>
-                            </sources>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-
-
-
-
-
-
-
-

2. Maven and Rest Assured 2.0

-
-
-

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

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

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

-
-
-
-
-

3. Using Snapshot and Milestone Versions for Maven

-
-
-

To use Snapshot and Milestone versions, you have to add the following section to your -pom.xml:

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

4. Adding stubs

-
-
-

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

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

Given that structure, Spring Cloud Contract Verifier creates a test class named -defaultBasePackage.MyService with two methods:

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-
-

5. Run plugin

-
-
-

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

-
-
-

If you want to run stubs via Maven it’s enough to call the run goal with the stubs to run as the spring.cloud.contract.verifier.stubs system property as follows:

-
-
-
-
-

mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run \ --Dspring.cloud.contract.verifier.stubs="com.acme:service-name"

-
-
-
-
-
-
-

6. Configure plugin

-
-
-

To change the default configuration, you can add a configuration section to the plugin -definition or the execution definition, as follows:

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

7. Configuration Options

-
-
-
    -
  • -

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. You can also change it to WebTestClient, JaxRsClient, or -Explicit (for real HTTP calls).

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsDirectory: Specifies a directory that contains contracts written with the -Groovyn DSL. The default directory is /src/test/resources/contracts.

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsProperties: A map that contains properties to be passed to Spring Cloud Contract -components. Those properties might be used by (for example) built-in or custom Stub Downloaders.

    -
  • -
  • -

    failOnNoContracts: When enabled, will throw an exception when no contracts were found. Defaults to true.

    -
  • -
  • -

    failOnInProgress: If set to true then if any contracts that are in progress are found, will break the build. On the producer side you need to be explicit about the fact that you have contracts in progress and take into consideration that you might be causing false positive test execution results on the consumer side.. Defaults to true.

    -
  • -
  • -

    incrementalContractTests: When enabled, tests are created only when contracts have changed since last build. Defaults to true.

    -
  • -
  • -

    incrementalContractStubs: When enabled, stubs are created only when contracts have changed since last build. Defaults to true.

    -
  • -
  • -

    incrementalContractStubsJar: When enabled, stubs jar is created only when stubs have changed since last build. Defaults to true.

    -
  • -
-
-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    contractsMode: Picks the mode in which stubs are found and registered.

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

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

-
-
-

The following list describes experimental features that you can turn on in the plugin:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-
-
-

8. Single Base Class for All Tests

-
-
-

When using Spring Cloud Contract Verifier in the default (MockMvc), you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified. The following example shows how to do so:

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

You can also setup the whole context if necessary, as the following example shows:

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

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app, -similar to what you might do in regular integration tests. The following example shows -how to do so:

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

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

-
-
-
-
-

9. Using 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 a value for packageWithBaseClasses

    -
  • -
  • -

    Provide explicit mapping with baseClassMappings

    -
  • -
-
-
-

9.1. By Convention

-
-

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

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

9.2. By Mapping

-
-

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

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

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

-
-
-

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

-
-
-
-
-
-

10. Invoking Generated Tests

-
-
-

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

-
-
-

For Groovy Spock code, you can use the following:

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

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

-
-
-
-
-

11. Pushing Stubs to SCM

-
-
-

If you use the SCM (Source Control Management) repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, you can add the pushStubsToScm -goal. The following example shows how to do so:

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

Under [scm-stub-downloader], you can find all possible -configuration options that you can pass through -the <configuration><contractProperties> map, a system property, -or an environment variable.

-
-
-
-
-

12. Maven Plugin and STS

-
-
-

The following image shows an exception that you may see when you use STS:

-
-
-
-STS Exception -
-
-
-

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

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

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

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

13. Maven Plugin with Spock Tests

-
-
-

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

-
-
-

First of all, you must use a plugin, such as the GMavenPlus plugin, -to add Groovy to your project. In GMavenPlus plugin, you need to explicitly set test sources, including both the -path where your base test classes are defined and the path were the generated contract tests are added. -The following example shows how to do so:

-
-
-
-
-
-
<plugin>
-    <groupId>org.codehaus.gmavenplus</groupId>
-    <artifactId>gmavenplus-plugin</artifactId>
-    <version>1.6.1</version>
-    <executions>
-        <execution>
-            <goals>
-                <goal>compileTests</goal>
-                <goal>addTestSources</goal>
-            </goals>
-        </execution>
-    </executions>
-    <configuration>
-        <testSources>
-            <testSource>
-                <directory>${project.basedir}/src/test/groovy</directory>
-                <includes>
-                    <include>**/*.groovy</include>
-                </includes>
-            </testSource>
-            <testSource>
-                <directory>
-                    ${project.basedir}/target/generated-test-sources/contracts/com/example/beer
-                </directory>
-                <includes>
-                    <include>**/*.groovy</include>
-                    <include>**/*.gvy</include>
-                </includes>
-            </testSource>
-        </testSources>
-    </configuration>
-    <dependencies>
-        <dependency>
-            <groupId>org.codehaus.groovy</groupId>
-            <artifactId>groovy-all</artifactId>
-            <version>${groovy.version}</version>
-            <scope>runtime</scope>
-            <type>pom</type>
-        </dependency>
-    </dependencies>
-
-
-
-
-
-

If you uphold the Spock convention of ending the test class names with Spec, you also need to adjust your Maven -Surefire plugin setup, as the following example shows:

-
-
-
-
-
-
<plugin>
-    <groupId>org.apache.maven.plugins</groupId>
-    <artifactId>maven-surefire-plugin</artifactId>
-    <configuration>
-        <includes>
-            <include>**/*Test.java</include>
-            <include>**/*Spec.java</include>
-        </includes>
-        <failIfNoTests>true</failIfNoTests>
-    </configuration>
-</plugin>
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/migrations.html b/reference/html/migrations.html index c8c70230a3..9990b6e5bb 100644 --- a/reference/html/migrations.html +++ b/reference/html/migrations.html @@ -1,345 +1,12 @@ - - - + + - - - -Migrations - - + - - - - - - -
-
-

Migrations

-
-
- - - - - -
- - -For up to date migration guides please visit -the project’s wiki page. -
-
-
-

This section covers migrating from one version of Spring Cloud Contract Verifier to the -next version. It covers the following versions upgrade paths:

-
-
-

1.0.x → 1.1.x

-
-

This section covers upgrading from version 1.0 to version 1.1.

-
-
-

New structure of generated stubs

-
-

In 1.1.x we have introduced a change to the structure of generated stubs. If you have -been using the @AutoConfigureWireMock notation to use the stubs from the classpath, -it no longer works. The following example shows how the @AutoConfigureWireMock notation -used to work:

-
-
-
-
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
-
-
-
-

You must either change the location of the stubs to: -classpath:…​/META-INF/groupId/artifactId/version/mappings or use the new -classpath-based @AutoConfigureStubRunner, as shown in the following example:

-
-
-
-
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
-
-
-
-

If you do not want to use @AutoConfigureStubRunner and you want to remain with the old -structure, set your plugin tasks accordingly. The following example would work for the -structure presented in the previous snippet.

-
-
-
Maven
-
-
<!-- start of pom.xml -->
+Page Redirection
 
-<properties>
-    <!-- we don't want the verifier to do a jar for us -->
-    <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
-</properties>
-
-<!-- ... -->
-
-<!-- You need to set up the assembly plugin -->
-<build>
-    <plugins>
-        <plugin>
-            <groupId>org.apache.maven.plugins</groupId>
-            <artifactId>maven-assembly-plugin</artifactId>
-            <executions>
-                <execution>
-                    <id>stub</id>
-                    <phase>prepare-package</phase>
-                    <goals>
-                        <goal>single</goal>
-                    </goals>
-                    <inherited>false</inherited>
-                    <configuration>
-                        <attach>true</attach>
-                        <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
-                    </configuration>
-                </execution>
-            </executions>
-        </plugin>
-    </plugins>
-</build>
-<!-- end of pom.xml -->
-
-<!-- start of stub.xml-->
-
-<assembly
-	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
-	<id>stubs</id>
-	<formats>
-		<format>jar</format>
-	</formats>
-	<includeBaseDirectory>false</includeBaseDirectory>
-	<fileSets>
-		<fileSet>
-			<directory>${project.build.directory}/snippets/stubs</directory>
-			<outputDirectory>customer-stubs/mappings</outputDirectory>
-			<includes>
-				<include>**/*</include>
-			</includes>
-		</fileSet>
-		<fileSet>
-			<directory>${basedir}/src/test/resources/contracts</directory>
-			<outputDirectory>customer-stubs/contracts</outputDirectory>
-			<includes>
-				<include>**/*.groovy</include>
-			</includes>
-		</fileSet>
-	</fileSets>
-</assembly>
-
-<!-- end of stub.xml-->
-
-
-
-
Gradle
-
-
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
-//    Preserve directory structure from 1.0.X of spring-cloud-contract
-    from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
-    into "${project.buildDir}/resources/main/customer-stubs"
-}
-
-
-
-
-
-

1.1.x → 1.2.x

-
-

This section covers upgrading from version 1.1 to version 1.2.

-
-
-

Custom HttpServerStub

-
-

HttpServerStub includes a method that was not in version 1.1. The method is -String registeredMappings() If you have classes that implement HttpServerStub, you -now have to implement the registeredMappings() method. It should return a String -representing all mappings available in a single HttpServerStub.

-
-
-

See issue 355 for more -detail.

-
-
-
-

New packages for generated tests

-
-

The flow for setting the generated tests package name will look like this:

-
-
-
    -
  • -

    Set basePackageForTests

    -
  • -
  • -

    If basePackageForTests was not set, pick the package from baseClassForTests

    -
  • -
  • -

    If baseClassForTests was not set, pick packageWithBaseClasses

    -
  • -
  • -

    If nothing got set, pick the default value: -org.springframework.cloud.contract.verifier.tests

    -
  • -
-
-
-

See issue 260 for more -detail.

-
-
-
-

New Methods in TemplateProcessor

-
-

In order to add support for fromRequest.path, the following methods had to be added to the -TemplateProcessor interface:

-
-
-
    -
  • -

    path()

    -
  • -
  • -

    path(int index)

    -
  • -
-
-
-

See issue 388 for more -detail.

-
-
-
-

RestAssured 3.0

-
-

Rest Assured, used in the generated test classes, got bumped to 3.0. If -you manually set versions of Spring Cloud Contract and the release train -you might see the following exception:

-
-
-
-
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
-[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist
-
-
-
-

This exception will occur due to the fact that the tests got generated with -an old version of plugin and at test execution time you have an incompatible -version of the release train (and vice versa).

-
-
-

Done via issue 267

-
-
-
- -
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/project-features.html b/reference/html/project-features.html index e0ae11b49d..9990b6e5bb 100644 --- a/reference/html/project-features.html +++ b/reference/html/project-features.html @@ -1,10819 +1,12 @@ - - - + + - - - -Spring Cloud Contract Features - - - - - - - - - -
-
-
-
-

This section dives into the details of Spring Cloud Contract. Here you can learn about the key -features that you may want to use and customize. If you have not already done so, you -might want to read the "getting-started.html" and -"using.html" sections, so that you have a good grounding of the -basics.

-
-
-
-
-

1. Contract DSL

-
-
-

Spring Cloud Contract supports the DSLs written in the following languages:

-
-
-
    -
  • -

    Groovy

    -
  • -
  • -

    YAML

    -
  • -
  • -

    Java

    -
  • -
  • -

    Kotlin

    -
  • -
-
-
- - - - - -
- - -Spring Cloud Contract supports defining multiple contracts in a single file. -
-
-
-

The following example shows a contract definition:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'PUT'
-        url '/api/12'
-        headers {
-            header 'Content-Type': 'application/vnd.org.springframework.cloud.contract.verifier.twitter-places-analyzer.v1+json'
-        }
-        body '''\
-    [{
-        "created_at": "Sat Jul 26 09:38:57 +0000 2014",
-        "id": 492967299297845248,
-        "id_str": "492967299297845248",
-        "text": "Gonna see you at Warsaw",
-        "place":
-        {
-            "attributes":{},
-            "bounding_box":
-            {
-                "coordinates":
-                    [[
-                        [-77.119759,38.791645],
-                        [-76.909393,38.791645],
-                        [-76.909393,38.995548],
-                        [-77.119759,38.995548]
-                    ]],
-                "type":"Polygon"
-            },
-            "country":"United States",
-            "country_code":"US",
-            "full_name":"Washington, DC",
-            "id":"01fbe706f872cb32",
-            "name":"Washington",
-            "place_type":"city",
-            "url": "https://api.twitter.com/1/geo/id/01fbe706f872cb32.json"
-        }
-    }]
-'''
-    }
-    response {
-        status OK()
-    }
-}
-
-
-
-
yml
-
-
description: Some description
-name: some name
-priority: 8
-ignored: true
-request:
-  url: /foo
-  queryParameters:
-    a: b
-    b: c
-  method: PUT
-  headers:
-    foo: bar
-    fooReq: baz
-  body:
-    foo: bar
-  matchers:
-    body:
-      - path: $.foo
-        type: by_regex
-        value: bar
-    headers:
-      - key: foo
-        regex: bar
-response:
-  status: 200
-  headers:
-    foo2: bar
-    foo3: foo33
-    fooRes: baz
-  body:
-    foo2: bar
-    foo3: baz
-    nullValue: null
-  matchers:
-    body:
-      - path: $.foo2
-        type: by_regex
-        value: bar
-      - path: $.foo3
-        type: by_command
-        value: executeMe($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-    headers:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        command: andMeToo($it)
-
-
-
-
java
-
-
import java.util.Collection;
-import java.util.Collections;
-import java.util.function.Supplier;
+Page Redirection
 
-import org.springframework.cloud.contract.spec.Contract;
-import org.springframework.cloud.contract.verifier.util.ContractVerifierUtil;
-
-class contract_rest implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.description("Some description");
-            c.name("some name");
-            c.priority(8);
-            c.ignored();
-            c.request(r -> {
-                r.url("/foo", u -> {
-                    u.queryParameters(q -> {
-                        q.parameter("a", "b");
-                        q.parameter("b", "c");
-                    });
-                });
-                r.method(r.PUT());
-                r.headers(h -> {
-                    h.header("foo", r.value(r.client(r.regex("bar")), r.server("bar")));
-                    h.header("fooReq", "baz");
-                });
-                r.body(ContractVerifierUtil.map().entry("foo", "bar"));
-                r.bodyMatchers(m -> {
-                    m.jsonPath("$.foo", m.byRegex("bar"));
-                });
-            });
-            c.response(r -> {
-                r.fixedDelayMilliseconds(1000);
-                r.status(r.OK());
-                r.headers(h -> {
-                    h.header("foo2", r.value(r.server(r.regex("bar")), r.client("bar")));
-                    h.header("foo3", r.value(r.server(r.execute("andMeToo($it)")),
-                            r.client("foo33")));
-                    h.header("fooRes", "baz");
-                });
-                r.body(ContractVerifierUtil.map().entry("foo2", "bar")
-                        .entry("foo3", "baz").entry("nullValue", null));
-                r.bodyMatchers(m -> {
-                    m.jsonPath("$.foo2", m.byRegex("bar"));
-                    m.jsonPath("$.foo3", m.byCommand("executeMe($it)"));
-                    m.jsonPath("$.nullValue", m.byNull());
-                });
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-import org.springframework.cloud.contract.spec.withQueryParameters
-
-contract {
-    name = "some name"
-    description = "Some description"
-    priority = 8
-    ignored = true
-    request {
-        url = url("/foo") withQueryParameters  {
-            parameter("a", "b")
-            parameter("b", "c")
-        }
-        method = PUT
-        headers {
-            header("foo", value(client(regex("bar")), server("bar")))
-            header("fooReq", "baz")
-        }
-        body = body(mapOf("foo" to "bar"))
-        bodyMatchers {
-            jsonPath("$.foo", byRegex("bar"))
-        }
-    }
-    response {
-        delay = fixedMilliseconds(1000)
-        status = OK
-        headers {
-            header("foo2", value(server(regex("bar")), client("bar")))
-            header("foo3", value(server(execute("andMeToo(\$it)")), client("foo33")))
-            header("fooRes", "baz")
-        }
-        body = body(mapOf(
-                "foo" to "bar",
-                "foo3" to "baz",
-                "nullValue" to null
-        ))
-        bodyMatchers {
-            jsonPath("$.foo2", byRegex("bar"))
-            jsonPath("$.foo3", byCommand("executeMe(\$it)"))
-            jsonPath("$.nullValue", byNull)
-        }
-    }
-}
-
-
-
-
-
- - - - - -
- - -
-

You can compile contracts to stubs mapping by using the following standalone Maven command:

-
-
-
-
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert
-
-
-
-
-
-

1.1. Contract DSL in Groovy

-
-

If you are not familiar with Groovy, do not worry - you can use Java syntax in the -Groovy DSL files as well.

-
-
-

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy -before. Knowledge of the language is not really needed, as the Contract DSL uses only a -tiny subset of it (only literals, method calls, and closures). Also, the DSL is statically -typed, to make it programmer-readable without any knowledge of the DSL itself.

-
-
- - - - - -
- - -Remember that, inside the Groovy contract file, you have to provide the fully -qualified name to the Contract class and make static imports, such as -org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to -the Contract class (import org.springframework.cloud.spec.Contract) and then call -Contract.make { …​ }. -
-
-
-
-

1.2. Contract DSL in Java

-
-

To write a contract definition in Java, you need to create a class, that implements either the Supplier<Contract> interface for a single contract or Supplier<Collection<Contract>> for multiple contracts.

-
-
-

You can also write the contract definitions under src/test/java (e.g. src/test/java/contracts) so that you don’t have to modify the classpath of your project. In this case you’ll have to provide a new location of contract definitions to your Spring Cloud Contract plugin.

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <contractsDirectory>src/test/java/contracts</contractsDirectory>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-    contractsDslDir = new File(project.rootDir, "src/test/java/contracts")
-}
-
-
-
-
-
-
-

1.3. Contract DSL in Kotlin

-
-

To get started with writing contracts in Kotlin you would need to start with a (newly created) Kotlin Script file (.kts). -Just like the with the Java DSL you can put your contracts in any directory of your choice. -The Maven and Gradle plugins will look at the src/test/resources/contracts directory by default.

-
-
-

You need to explicitly pass the the spring-cloud-contract-spec-kotlin dependency to your project plugin setup.

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- some config -->
-    </configuration>
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-contract-spec-kotlin</artifactId>
-            <version>${spring-cloud-contract.version}</version>
-        </dependency>
-    </dependencies>
-</plugin>
-
-<dependencies>
-        <!-- Remember to add this for the DSL support in the IDE and on the consumer side -->
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-contract-spec-kotlin</artifactId>
-            <scope>test</scope>
-        </dependency>
-</dependencies>
-
-
-
-
Gradle
-
-
buildscript {
-    repositories {
-        // ...
-    }
-    dependencies {
-        classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${scContractVersion}"
-        // remember to add this:
-        classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${scContractVersion}"
-    }
-}
-
-dependencies {
-    // ...
-
-    // Remember to add this for the DSL support in the IDE and on the consumer side
-    testImplementation "org.springframework.cloud:spring-cloud-contract-spec-kotlin"
-}
-
-
-
-
-
- - - - - -
- - -Remember that, inside the Kotlin Script file, you have to provide the fully qualified name to the ContractDSL class. -Generally you would use its contract function like this: org.springframework.cloud.contract.spec.ContractDsl.contract { …​ }. -You can also provide an import to the contract function (import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract) and then call contract { …​ }. -
-
-
-
-

1.4. Contract DSL in YML

-
-

In order to see a schema of a YAML contract, you can check out the YML Schema page.

-
-
-
-

1.5. Limitations

-
- - - - - -
- - -The support for verifying the size of JSON arrays is experimental. If you want -to turn it on, set the value of the following system property to true: -spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. -You can also set the assertJsonSize property in the plugin configuration. -
-
-
- - - - - -
- - -Because JSON structure can have any form, it can be impossible to parse it -properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That -is why you should use the Groovy Map notation. -
-
-
-
-

1.6. Common Top-Level Elements

-
-

The following sections describe the most common top-level elements:

-
- -
-

1.6.1. Description

-
-

You can add a description to your contract. The description is arbitrary text. The -following code shows an example:

-
-
-
-
-
groovy
-
-
            org.springframework.cloud.contract.spec.Contract.make {
-                description('''
-given:
-    An input
-when:
-    Sth happens
-then:
-    Output
-''')
-            }
-
-
-
-
yml
-
-
description: Some description
-name: some name
-priority: 8
-ignored: true
-request:
-  url: /foo
-  queryParameters:
-    a: b
-    b: c
-  method: PUT
-  headers:
-    foo: bar
-    fooReq: baz
-  body:
-    foo: bar
-  matchers:
-    body:
-      - path: $.foo
-        type: by_regex
-        value: bar
-    headers:
-      - key: foo
-        regex: bar
-response:
-  status: 200
-  headers:
-    foo2: bar
-    foo3: foo33
-    fooRes: baz
-  body:
-    foo2: bar
-    foo3: baz
-    nullValue: null
-  matchers:
-    body:
-      - path: $.foo2
-        type: by_regex
-        value: bar
-      - path: $.foo3
-        type: by_command
-        value: executeMe($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-    headers:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        command: andMeToo($it)
-
-
-
-
java
-
-
Contract.make(c -> {
-    c.description("Some description");
-}));
-
-
-
-
kotlin
-
-
contract {
-    description = """
-given:
-    An input
-when:
-    Sth happens
-then:
-    Output
-"""
-}
-
-
-
-
-
-
-

1.6.2. Name

-
-

You can provide a name for your contract. Assume that you provided the following name: -should register a user. If you do so, the name of the autogenerated test is -validate_should_register_a_user. Also, the name of the stub in a WireMock stub is -should_register_a_user.json.

-
-
- - - - - -
- - -You must ensure that the name does not contain any characters that make the -generated test not compile. Also, remember that, if you provide the same name for -multiple contracts, your autogenerated tests fail to compile and your generated stubs -override each other. -
-
-
-

The following example shows how to add a name to a contract:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    name("some_special_name")
-}
-
-
-
-
yml
-
-
name: some name
-
-
-
-
java
-
-
Contract.make(c -> {
-    c.name("some name");
-}));
-
-
-
-
kotlin
-
-
contract {
-    name = "some_special_name"
-}
-
-
-
-
-
-
-

1.6.3. Ignoring Contracts

-
-

If you want to ignore a contract, you can either set a value for ignored contracts in the -plugin configuration or set the ignored property on the contract itself. The following -example shows how to do so:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    ignored()
-}
-
-
-
-
yml
-
-
ignored: true
-
-
-
-
java
-
-
Contract.make(c -> {
-    c.ignored();
-}));
-
-
-
-
kotlin
-
-
contract {
-    ignored = true
-}
-
-
-
-
-
-
-

1.6.4. Contracts in Progress

-
-

A contract in progress will not generate tests on the producer side, but will allow generation of stubs.

-
-
- - - - - -
- - -Use this feature with caution as it may lead to false positives. You generate stubs for your consumers to use without actually having the implementation in place! -
-
-
-

If you want to set a contract in progress the following -example shows how to do so:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    inProgress()
-}
-
-
-
-
yml
-
-
inProgress: true
-
-
-
-
java
-
-
Contract.make(c -> {
-    c.inProgress();
-}));
-
-
-
-
kotlin
-
-
contract {
-    inProgress = true
-}
-
-
-
-
-
-

You can set the value of the failOnInProgress Spring Cloud Contract plugin property to ensure that your build will break when at least one contract in progress remains in your sources.

-
-
-
-

1.6.5. Passing Values from Files

-
-

Starting with version 1.2.0, you can pass values from files. Assume that you have the -following resources in your project:

-
-
-
-
└── src
-    └── test
-        └── resources
-            └── contracts
-                ├── readFromFile.groovy
-                ├── request.json
-                └── response.json
-
-
-
-

Further assume that your contract is as follows:

-
-
-
-
-
groovy
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-    request {
-        method('PUT')
-        headers {
-            contentType(applicationJson())
-        }
-        body(file("request.json"))
-        url("/1")
-    }
-    response {
-        status OK()
-        body(file("response.json"))
-        headers {
-            contentType(applicationJson())
-        }
-    }
-}
-
-
-
-
yml
-
-
request:
-  method: GET
-  url: /foo
-  bodyFromFile: request.json
-response:
-  status: 200
-  bodyFromFile: response.json
-
-
-
-
java
-
-
import java.util.Collection;
-import java.util.Collections;
-import java.util.function.Supplier;
-
-import org.springframework.cloud.contract.spec.Contract;
-
-class contract_rest_from_file implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.request(r -> {
-                r.url("/foo");
-                r.method(r.GET());
-                r.body(r.file("request.json"));
-            });
-            c.response(r -> {
-                r.status(r.OK());
-                r.body(r.file("response.json"));
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        url = url("/1")
-        method = PUT
-        headers {
-            contentType = APPLICATION_JSON
-        }
-        body = bodyFromFile("request.json")
-    }
-    response {
-        status = OK
-        body = bodyFromFile("response.json")
-        headers {
-            contentType = APPLICATION_JSON
-        }
-    }
-}
-
-
-
-
-
-

Further assume that the JSON files is as follows:

-
-
-
-
-
request.json
-
-
{
-  "status": "REQUEST"
-}
-
-
-
-
response.json
-
-
{
-  "status": "RESPONSE"
-}
-
-
-
-
-
-

When test or stub generation takes place, the contents of the request.json and response.json files are passed to the body -of a request or a response. The name of the file needs to be a file with location -relative to the folder in which the contract lays.

-
-
-

If you need to pass the contents of a file in binary form, -you can use the fileAsBytes method in the coded DSL or a bodyFromFileAsBytes field in YAML.

-
-
-

The following example shows how to pass the contents of binary files:

-
-
-
-
-
groovy
-
-
import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-    request {
-        url("/1")
-        method(PUT())
-        headers {
-            contentType(applicationOctetStream())
-        }
-        body(fileAsBytes("request.pdf"))
-    }
-    response {
-        status 200
-        body(fileAsBytes("response.pdf"))
-        headers {
-            contentType(applicationOctetStream())
-        }
-    }
-}
-
-
-
-
yml
-
-
request:
-  url: /1
-  method: PUT
-  headers:
-    Content-Type: application/octet-stream
-  bodyFromFileAsBytes: request.pdf
-response:
-  status: 200
-  bodyFromFileAsBytes: response.pdf
-  headers:
-    Content-Type: application/octet-stream
-
-
-
-
java
-
-
import java.util.Collection;
-import java.util.Collections;
-import java.util.function.Supplier;
-
-import org.springframework.cloud.contract.spec.Contract;
-
-class contract_rest_from_pdf implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.request(r -> {
-                r.url("/1");
-                r.method(r.PUT());
-                r.body(r.fileAsBytes("request.pdf"));
-                r.headers(h -> {
-                    h.contentType(h.applicationOctetStream());
-                });
-            });
-            c.response(r -> {
-                r.status(r.OK());
-                r.body(r.fileAsBytes("response.pdf"));
-                r.headers(h -> {
-                    h.contentType(h.applicationOctetStream());
-                });
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        url = url("/1")
-        method = PUT
-        headers {
-            contentType = APPLICATION_OCTET_STREAM
-        }
-        body = bodyFromFileAsBytes("contracts/request.pdf")
-    }
-    response {
-        status = OK
-        body = bodyFromFileAsBytes("contracts/response.pdf")
-        headers {
-            contentType = APPLICATION_OCTET_STREAM
-        }
-    }
-}
-
-
-
-
-
- - - - - -
- - -You should use this approach whenever you want to work with binary payloads, - both for HTTP and messaging. -
-
-
-
-
-
-
-

2. Contracts for HTTP

-
-
-

Spring Cloud Contract lets you verify applications that use REST or HTTP as a -means of communication. Spring Cloud Contract verifies that, for a request that matches the -criteria from the request part of the contract, the server provides a response that is in -keeping with the response part of the contract. Subsequently, the contracts are used to -generate WireMock stubs that, for any request matching the provided criteria, provide a -suitable response.

-
-
-

2.1. HTTP Top-Level Elements

-
-

You can call the following methods in the top-level closure of a contract definition:

-
-
-
    -
  • -

    request: Mandatory

    -
  • -
  • -

    response : Mandatory

    -
  • -
  • -

    priority: Optional

    -
  • -
-
-
-

The following example shows how to define an HTTP request contract:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    // Definition of HTTP request part of the contract
-    // (this can be a valid request or invalid depending
-    // on type of contract being specified).
-    request {
-        method GET()
-        url "/foo"
-        //...
-    }
-
-    // Definition of HTTP response part of the contract
-    // (a service implementing this contract should respond
-    // with following response after receiving request
-    // specified in "request" part above).
-    response {
-        status 200
-        //...
-    }
-
-    // Contract priority, which can be used for overriding
-    // contracts (1 is highest). Priority is optional.
-    priority 1
-}
-
-
-
-
yml
-
-
priority: 8
-request:
-...
-response:
-...
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    // Definition of HTTP request part of the contract
-    // (this can be a valid request or invalid depending
-    // on type of contract being specified).
-    c.request(r -> {
-        r.method(r.GET());
-        r.url("/foo");
-        // ...
-    });
-
-    // Definition of HTTP response part of the contract
-    // (a service implementing this contract should respond
-    // with following response after receiving request
-    // specified in "request" part above).
-    c.response(r -> {
-        r.status(200);
-        // ...
-    });
-
-    // Contract priority, which can be used for overriding
-    // contracts (1 is highest). Priority is optional.
-    c.priority(1);
-});
-
-
-
-
kotlin
-
-
contract {
-    // Definition of HTTP request part of the contract
-    // (this can be a valid request or invalid depending
-    // on type of contract being specified).
-    request {
-        method = GET
-        url = url("/foo")
-        // ...
-    }
-
-    // Definition of HTTP response part of the contract
-    // (a service implementing this contract should respond
-    // with following response after receiving request
-    // specified in "request" part above).
-    response {
-        status = OK
-        // ...
-    }
-
-    // Contract priority, which can be used for overriding
-    // contracts (1 is highest). Priority is optional.
-    priority = 1
-}
-
-
-
-
-
- - - - - -
- - -If you want to make your contract have a higher priority, -you need to pass a lower number to the priority tag or method. For example, a priority with -a value of 5 has higher priority than a priority with a value of 10. -
-
-
-
-

2.2. HTTP Request

-
-

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

-
-
-

The following example shows a contract for a request:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        // HTTP request method (GET/POST/PUT/DELETE).
-        method 'GET'
-
-        // Path component of request URL is specified as follows.
-        urlPath('/users')
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
method: PUT
-url: /foo
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // HTTP request method (GET/POST/PUT/DELETE).
-        r.method("GET");
-
-        // Path component of request URL is specified as follows.
-        r.urlPath("/users");
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // HTTP request method (GET/POST/PUT/DELETE).
-        method = method("GET")
-
-        // Path component of request URL is specified as follows.
-        urlPath = path("/users")
-    }
-    response {
-        // ...
-        status = code(200)
-    }
-}
-
-
-
-
-
-

You can specify an absolute rather than a relative url, but using urlPath is -the recommended way, as doing so makes the tests be host-independent.

-
-
-

The following example uses url:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'GET'
-
-        // Specifying `url` and `urlPath` in one contract is illegal.
-        url('http://localhost:8888/users')
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-  method: PUT
-  urlPath: /foo
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        r.method("GET");
-
-        // Specifying `url` and `urlPath` in one contract is illegal.
-        r.url("http://localhost:8888/users");
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        method = GET
-
-        // Specifying `url` and `urlPath` in one contract is illegal.
-        url("http://localhost:8888/users")
-    }
-    response {
-        // ...
-        status = OK
-    }
-}
-
-
-
-
-
-

request may contain query parameters, as the following example (which uses urlPath) shows:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        //...
-        method GET()
-
-        urlPath('/users') {
-
-            // Each parameter is specified in form
-            // `'paramName' : paramValue` where parameter value
-            // may be a simple literal or one of matcher functions,
-            // all of which are used in this example.
-            queryParameters {
-
-                // If a simple literal is used as value
-                // default matcher function is used (equalTo)
-                parameter 'limit': 100
-
-                // `equalTo` function simply compares passed value
-                // using identity operator (==).
-                parameter 'filter': equalTo("email")
-
-                // `containing` function matches strings
-                // that contains passed substring.
-                parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
-
-                // `matching` function tests parameter
-                // against passed regular expression.
-                parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
-
-                // `notMatching` functions tests if parameter
-                // does not match passed regular expression.
-                parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
-            }
-        }
-
-        //...
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-...
-queryParameters:
-  a: b
-  b: c
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // ...
-        r.method(r.GET());
-
-        r.urlPath("/users", u -> {
-
-            // 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.
-            u.queryParameters(q -> {
-
-                // If a simple literal is used as value
-                // default matcher function is used (equalTo)
-                q.parameter("limit", 100);
-
-                // `equalTo` function simply compares passed value
-                // using identity operator (==).
-                q.parameter("filter", r.equalTo("email"));
-
-                // `containing` function matches strings
-                // that contains passed substring.
-                q.parameter("gender",
-                        r.value(r.consumer(r.containing("[mf]")),
-                                r.producer("mf")));
-
-                // `matching` function tests parameter
-                // against passed regular expression.
-                q.parameter("offset",
-                        r.value(r.consumer(r.matching("[0-9]+")),
-                                r.producer(123)));
-
-                // `notMatching` functions tests if parameter
-                // does not match passed regular expression.
-                q.parameter("loginStartsWith",
-                        r.value(r.consumer(r.notMatching(".{0,2}")),
-                                r.producer(3)));
-            });
-        });
-
-        // ...
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // ...
-        method = GET
-
-        // 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.
-        urlPath = path("/users") withQueryParameters {
-            // If a simple literal is used as value
-            // default matcher function is used (equalTo)
-            parameter("limit", 100)
-
-            // `equalTo` function simply compares passed value
-            // using identity operator (==).
-            parameter("filter", equalTo("email"))
-
-            // `containing` function matches strings
-            // that contains passed substring.
-            parameter("gender", value(consumer(containing("[mf]")), producer("mf")))
-
-            // `matching` function tests parameter
-            // against passed regular expression.
-            parameter("offset", value(consumer(matching("[0-9]+")), producer(123)))
-
-            // `notMatching` functions tests if parameter
-            // does not match passed regular expression.
-            parameter("loginStartsWith", value(consumer(notMatching(".{0,2}")), producer(3)))
-        }
-
-        // ...
-    }
-    response {
-        // ...
-        status = code(200)
-    }
-}
-
-
-
-
-
-

request can contain additional request headers, as the following example shows:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        //...
-        method GET()
-        url "/foo"
-
-        // Each header is added in form `'Header-Name' : 'Header-Value'`.
-        // there are also some helper methods
-        headers {
-            header 'key': 'value'
-            contentType(applicationJson())
-        }
-
-        //...
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-...
-headers:
-  foo: bar
-  fooReq: baz
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // ...
-        r.method(r.GET());
-        r.url("/foo");
-
-        // Each header is added in form `'Header-Name' : 'Header-Value'`.
-        // there are also some helper methods
-        r.headers(h -> {
-            h.header("key", "value");
-            h.contentType(h.applicationJson());
-        });
-
-        // ...
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // ...
-        method = GET
-        url = url("/foo")
-
-        // Each header is added in form `'Header-Name' : 'Header-Value'`.
-        // there are also some helper variables
-        headers {
-            header("key", "value")
-            contentType = APPLICATION_JSON
-        }
-
-        // ...
-    }
-    response {
-        // ...
-        status = OK
-    }
-}
-
-
-
-
-
-

request may contain additional request cookies, as the following example shows:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        //...
-        method GET()
-        url "/foo"
-
-        // Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
-        // there are also some helper methods
-        cookies {
-            cookie 'key': 'value'
-            cookie('another_key', 'another_value')
-        }
-
-        //...
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-...
-cookies:
-  foo: bar
-  fooReq: baz
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // ...
-        r.method(r.GET());
-        r.url("/foo");
-
-        // Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
-        // there are also some helper methods
-        r.cookies(ck -> {
-            ck.cookie("key", "value");
-            ck.cookie("another_key", "another_value");
-        });
-
-        // ...
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // ...
-        method = GET
-        url = url("/foo")
-
-        // Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
-        // there are also some helper methods
-        cookies {
-            cookie("key", "value")
-            cookie("another_key", "another_value")
-        }
-
-        // ...
-    }
-
-    response {
-        // ...
-        status = code(200)
-    }
-}
-
-
-
-
-
-

request may contain a request body, as the following example shows:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        //...
-        method GET()
-        url "/foo"
-
-        // Currently only JSON format of request body is supported.
-        // Format will be determined from a header or body's content.
-        body '''{ "login" : "john", "name": "John The Contract" }'''
-    }
-
-    response {
-        //...
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-...
-body:
-  foo: bar
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // ...
-        r.method(r.GET());
-        r.url("/foo");
-
-        // Currently only JSON format of request body is supported.
-        // Format will be determined from a header or body's content.
-        r.body("{ \"login\" : \"john\", \"name\": \"John The Contract\" }");
-    });
-
-    c.response(r -> {
-        // ...
-        r.status(200);
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // ...
-        method = GET
-        url = url("/foo")
-
-        // Currently only JSON format of request body is supported.
-        // Format will be determined from a header or body's content.
-        body = body("{ \"login\" : \"john\", \"name\": \"John The Contract\" }")
-    }
-    response {
-        // ...
-        status = OK
-    }
-}
-
-
-
-
-
-

request can contain multipart elements. To include multipart elements, use the -multipart method/section, as the following examples show:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'PUT'
-        url '/multipart'
-        headers {
-            contentType('multipart/form-data;boundary=AaB03x')
-        }
-        multipart(
-                // key (parameter name), value (parameter value) pair
-                formParameter: $(c(regex('".+"')), p('"formParameterValue"')),
-                someBooleanParameter: $(c(regex(anyBoolean())), p('true')),
-                // a named parameter (e.g. with `file` name) that represents file with
-                // `name` and `content`. You can also call `named("fileName", "fileContent")`
-                file: named(
-                        // name of the file
-                        name: $(c(regex(nonEmpty())), p('filename.csv')),
-                        // content of the file
-                        content: $(c(regex(nonEmpty())), p('file content')),
-                        // content type for the part
-                        contentType: $(c(regex(nonEmpty())), p('application/json')))
-        )
-    }
-    response {
-        status OK()
-    }
-}
-org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method "PUT"
-        url "/multipart"
-        headers {
-            contentType('multipart/form-data;boundary=AaB03x')
-        }
-        multipart(
-                file: named(
-                        name: value(stub(regex('.+')), test('file')),
-                        content: value(stub(regex('.+')), test([100, 117, 100, 97] as byte[]))
-                )
-        )
-    }
-    response {
-        status 200
-    }
-}
-
-
-
-
yml
-
-
request:
-  method: PUT
-  url: /multipart
-  headers:
-    Content-Type: multipart/form-data;boundary=AaB03x
-  multipart:
-    params:
-      # key (parameter name), value (parameter value) pair
-      formParameter: '"formParameterValue"'
-      someBooleanParameter: true
-    named:
-      - paramName: file
-        fileName: filename.csv
-        fileContent: file content
-  matchers:
-    multipart:
-      params:
-        - key: formParameter
-          regex: ".+"
-        - key: someBooleanParameter
-          predefined: any_boolean
-      named:
-        - paramName: file
-          fileName:
-            predefined: non_empty
-          fileContent:
-            predefined: non_empty
-response:
-  status: 200
-
-
-
-
java
-
-
import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.function.Supplier;
-
-import org.springframework.cloud.contract.spec.Contract;
-import org.springframework.cloud.contract.spec.internal.DslProperty;
-import org.springframework.cloud.contract.spec.internal.Request;
-import org.springframework.cloud.contract.verifier.util.ContractVerifierUtil;
-
-class contract_multipart implements Supplier<Collection<Contract>> {
-
-    private static Map<String, DslProperty> namedProps(Request r) {
-        Map<String, DslProperty> map = new HashMap<>();
-        // name of the file
-        map.put("name", r.$(r.c(r.regex(r.nonEmpty())), r.p("filename.csv")));
-        // content of the file
-        map.put("content", r.$(r.c(r.regex(r.nonEmpty())), r.p("file content")));
-        // content type for the part
-        map.put("contentType", r.$(r.c(r.regex(r.nonEmpty())), r.p("application/json")));
-        return map;
-    }
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.request(r -> {
-                r.method("PUT");
-                r.url("/multipart");
-                r.headers(h -> {
-                    h.contentType("multipart/form-data;boundary=AaB03x");
-                });
-                r.multipart(ContractVerifierUtil.map()
-                        // key (parameter name), value (parameter value) pair
-                        .entry("formParameter",
-                                r.$(r.c(r.regex("\".+\"")),
-                                        r.p("\"formParameterValue\"")))
-                        .entry("someBooleanParameter",
-                                r.$(r.c(r.regex(r.anyBoolean())), r.p("true")))
-                        // a named parameter (e.g. with `file` name) that represents file
-                        // with
-                        // `name` and `content`. You can also call `named("fileName",
-                        // "fileContent")`
-                        .entry("file", r.named(namedProps(r))));
-            });
-            c.response(r -> {
-                r.status(r.OK());
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        method = PUT
-        url = url("/multipart")
-        multipart {
-            field("formParameter", value(consumer(regex("\".+\"")), producer("\"formParameterValue\"")))
-            field("someBooleanParameter", value(consumer(anyBoolean), producer("true")))
-            field("file",
-                named(
-                    // name of the file
-                    value(consumer(regex(nonEmpty)), producer("filename.csv")),
-                    // content of the file
-                    value(consumer(regex(nonEmpty)), producer("file content")),
-                    // content type for the part
-                    value(consumer(regex(nonEmpty)), producer("application/json"))
-                )
-            )
-        }
-        headers {
-            contentType = "multipart/form-data;boundary=AaB03x"
-        }
-    }
-    response {
-        status = OK
-    }
-}
-
-
-
-
-
-

In the preceding example, we define parameters in either of two ways:

-
-
-
Coded DSL
-
    -
  • -

    Directly, by using the map notation, where the value can be a dynamic property (such as -formParameter: $(consumer(…​), producer(…​))).

    -
  • -
  • -

    By using the named(…​) method that lets you set a named parameter. A named parameter -can set a name and content. You can call it either by using a method with two arguments, -such as named("fileName", "fileContent"), or by using a map notation, such as -named(name: "fileName", content: "fileContent").

    -
  • -
-
-
-
YAML
-
    -
  • -

    The multipart parameters are set in the multipart.params section.

    -
  • -
  • -

    The named parameters (the fileName and fileContent for a given parameter name) -can be set in the multipart.named section. That section contains -the paramName (the name of the parameter), fileName (the name of the file), -fileContent (the content of the file) fields.

    -
  • -
  • -

    The dynamic bits can be set via the matchers.multipart section.

    -
    -
      -
    • -

      For parameters, use the params section, which can accept -regex or a predefined regular expression.

      -
    • -
    • -

      for named params, use the named section where first you -define the parameter name with paramName. Then you can pass the -parametrization of either fileName or fileContent in a -regex or in a predefined regular expression.

      -
    • -
    -
    -
  • -
-
-
-

From the contract in the preceding example, the generated test and stubs look as follows:

-
-
-
-
-
Test
-
-
// given:
-  MockMvcRequestSpecification request = given()
-    .header("Content-Type", "multipart/form-data;boundary=AaB03x")
-    .param("formParameter", "\"formParameterValue\"")
-    .param("someBooleanParameter", "true")
-    .multiPart("file", "filename.csv", "file content".getBytes());
-
- // when:
-  ResponseOptions response = given().spec(request)
-    .put("/multipart");
-
- // then:
-  assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-
Stub
-
-
            '''
-{
-  "request" : {
-    "url" : "/multipart",
-    "method" : "PUT",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "multipart/form-data;boundary=AaB03x.*"
-      }
-    },
-    "bodyPatterns" : [ {
-        "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
-    }, {
-        "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
-    }, {
-      "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "transformers" : [ "response-template", "foo-transformer" ]
-  }
-}
-    '''
-
-
-
-
-
-
-

2.3. HTTP Response

-
-

The response must contain an HTTP status code and may contain other information. The -following code shows an example:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        //...
-        method GET()
-        url "/foo"
-    }
-    response {
-        // Status code sent by the server
-        // in response to request specified above.
-        status OK()
-    }
-}
-
-
-
-
yml
-
-
response:
-...
-status: 200
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        // ...
-        r.method(r.GET());
-        r.url("/foo");
-    });
-    c.response(r -> {
-        // Status code sent by the server
-        // in response to request specified above.
-        r.status(r.OK());
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        // ...
-        method = GET
-        url =url("/foo")
-    }
-    response {
-        // Status code sent by the server
-        // in response to request specified above.
-        status = OK
-    }
-}
-
-
-
-
-
-

Besides status, the response may contain headers, cookies, and a body, which are -specified the same way as in the request (see HTTP Request).

-
-
- - - - - -
- - -In the Groovy DSL, you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus -methods to provide a meaningful status instead of a digit. For example, you can call -OK() for a status 200 or BAD_REQUEST() for 400. -
-
-
-
-

2.4. Dynamic properties

-
-

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not -want to force the consumers to stub their clocks to always return the same value of time -so that it gets matched by the stub.

-
-
-

For the Groovy DSL, you can provide the dynamic parts in your contracts -in two ways: pass them directly in the body or set them in a separate section called -bodyMatchers.

-
-
- - - - - -
- - -Before 2.0.0, these were set by using testMatchers and stubMatchers. -See the migration guide for more information. -
-
-
-

For YAML, you can use only the matchers section.

-
-
- - - - - -
- - -Entries inside the matchers must reference existing elements of the payload. For more information check this issue. -
-
-
-

2.4.1. Dynamic Properties inside the Body

-
- - - - - -
- - -This section is valid only for the Coded DSL (Groovy, Java etc.). Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can set the properties inside the body either with the value method or, if you use -the Groovy map notation, with $(). The following example shows how to set dynamic -properties with the value method:

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

Both approaches work equally well. The stub and client methods are aliases over the consumer -method. Subsequent sections take a closer look at what you can do with those values.

-
-
-
-

2.4.2. Regular Expressions

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can use regular expressions to write your requests in the contract DSL. Doing so is -particularly useful when you want to indicate that a given response should be provided -for requests that follow a given pattern. Also, you can use regular expressions when you -need to use patterns and not exact values both for your tests and your server-side tests.

-
-
-

Make sure that regex matches a whole region of a sequence, as, internally, a call to -Pattern.matches() -is called. For instance, abc does not match aabc, but .abc does. -There are several additional known limitations as well.

-
-
-

The following example shows how to use regular expressions to write a request:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method('GET')
-        url $(consumer(~/\/[0-9]{2}/), producer('/12'))
-    }
-    response {
-        status OK()
-        body(
-                id: $(anyNumber()),
-                surname: $(
-                        consumer('Kowalsky'),
-                        producer(regex('[a-zA-Z]+'))
-                ),
-                name: 'Jan',
-                created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
-                correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
-                        producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
-                )
-        )
-        headers {
-            header 'Content-Type': 'text/plain'
-        }
-    }
-}
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.request(r -> {
-        r.method("GET");
-        r.url(r.$(r.consumer(r.regex("\\/[0-9]{2}")), r.producer("/12")));
-    });
-    c.response(r -> {
-        r.status(r.OK());
-        r.body(ContractVerifierUtil.map().entry("id", r.$(r.anyNumber()))
-                .entry("surname", r.$(r.consumer("Kowalsky"),
-                        r.producer(r.regex("[a-zA-Z]+")))));
-        r.headers(h -> {
-            h.header("Content-Type", "text/plain");
-        });
-    });
-});
-
-
-
-
kotlin
-
-
contract {
-    request {
-        method = method("GET")
-        url = url(v(consumer(regex("\\/[0-9]{2}")), producer("/12")))
-    }
-    response {
-        status = OK
-        body(mapOf(
-                "id" to v(anyNumber),
-                "surname" to v(consumer("Kowalsky"), producer(regex("[a-zA-Z]+")))
-        ))
-        headers {
-            header("Content-Type", "text/plain")
-        }
-    }
-}
-
-
-
-
-
-

You can also provide only one side of the communication with a regular expression. If you -do so, then the contract engine automatically provides the generated string that matches -the provided regular expression. The following code shows an example for Groovy:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'PUT'
-        url value(consumer(regex('/foo/[0-9]{5}')))
-        body([
-                requestElement: $(consumer(regex('[0-9]{5}')))
-        ])
-        headers {
-            header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
-        }
-    }
-    response {
-        status OK()
-        body([
-                responseElement: $(producer(regex('[0-9]{7}')))
-        ])
-        headers {
-            contentType("application/vnd.fraud.v1+json")
-        }
-    }
-}
-
-
-
-

In the preceding example, the opposite side of the communication has the respective data -generated for request and response.

-
-
-

Spring Cloud Contract comes with a series of predefined regular expressions that you can -use in your contracts, as the following example shows:

-
-
-
-
public static RegexProperty onlyAlphaUnicode() {
-    return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
-}
-
-public static RegexProperty alphaNumeric() {
-    return new RegexProperty(ALPHA_NUMERIC).asString();
-}
-
-public static RegexProperty number() {
-    return new RegexProperty(NUMBER).asDouble();
-}
-
-public static RegexProperty positiveInt() {
-    return new RegexProperty(POSITIVE_INT).asInteger();
-}
-
-public static RegexProperty anyBoolean() {
-    return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
-}
-
-public static RegexProperty anInteger() {
-    return new RegexProperty(INTEGER).asInteger();
-}
-
-public static RegexProperty aDouble() {
-    return new RegexProperty(DOUBLE).asDouble();
-}
-
-public static RegexProperty ipAddress() {
-    return new RegexProperty(IP_ADDRESS).asString();
-}
-
-public static RegexProperty hostname() {
-    return new RegexProperty(HOSTNAME_PATTERN).asString();
-}
-
-public static RegexProperty email() {
-    return new RegexProperty(EMAIL).asString();
-}
-
-public static RegexProperty url() {
-    return new RegexProperty(URL).asString();
-}
-
-public static RegexProperty httpsUrl() {
-    return new RegexProperty(HTTPS_URL).asString();
-}
-
-public static RegexProperty uuid() {
-    return new RegexProperty(UUID).asString();
-}
-
-public static RegexProperty isoDate() {
-    return new RegexProperty(ANY_DATE).asString();
-}
-
-public static RegexProperty isoDateTime() {
-    return new RegexProperty(ANY_DATE_TIME).asString();
-}
-
-public static RegexProperty isoTime() {
-    return new RegexProperty(ANY_TIME).asString();
-}
-
-public static RegexProperty iso8601WithOffset() {
-    return new RegexProperty(ISO8601_WITH_OFFSET).asString();
-}
-
-public static RegexProperty nonEmpty() {
-    return new RegexProperty(NON_EMPTY).asString();
-}
-
-public static RegexProperty nonBlank() {
-    return new RegexProperty(NON_BLANK).asString();
-}
-
-
-
-

In your contract, you can use it as follows (example for the Groovy DSL):

-
-
-
-
Contract dslWithOptionalsInString = Contract.make {
-    priority 1
-    request {
-        method POST()
-        url '/users/password'
-        headers {
-            contentType(applicationJson())
-        }
-        body(
-                email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
-                callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
-        )
-    }
-    response {
-        status 404
-        headers {
-            contentType(applicationJson())
-        }
-        body(
-                code: value(consumer("123123"), producer(optional("123123"))),
-                message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
-        )
-    }
-}
-
-
-
-

To make matters even simpler, you can use a set of predefined objects that automatically -assume that you want a regular expression to be passed. -All of those methods start with the any prefix, as follows:

-
-
-
-
T anyAlphaUnicode();
-
-T anyAlphaNumeric();
-
-T anyNumber();
-
-T anyInteger();
-
-T anyPositiveInt();
-
-T anyDouble();
-
-T anyHex();
-
-T aBoolean();
-
-T anyIpAddress();
-
-T anyHostname();
-
-T anyEmail();
-
-T anyUrl();
-
-T anyHttpsUrl();
-
-T anyUuid();
-
-T anyDate();
-
-T anyDateTime();
-
-T anyTime();
-
-T anyIso8601WithOffset();
-
-T anyNonBlankString();
-
-T anyNonEmptyString();
-
-T anyOf(String... values);
-
-
-
-

The following example shows how you can reference those methods:

-
-
-
-
-
groovy
-
-
Contract contractDsl = Contract.make {
-    name "foo"
-    label 'trigger_event'
-    input {
-        triggeredBy('toString()')
-    }
-    outputMessage {
-        sentTo 'topic.rateablequote'
-        body([
-                alpha            : $(anyAlphaUnicode()),
-                number           : $(anyNumber()),
-                anInteger        : $(anyInteger()),
-                positiveInt      : $(anyPositiveInt()),
-                aDouble          : $(anyDouble()),
-                aBoolean         : $(aBoolean()),
-                ip               : $(anyIpAddress()),
-                hostname         : $(anyHostname()),
-                email            : $(anyEmail()),
-                url              : $(anyUrl()),
-                httpsUrl         : $(anyHttpsUrl()),
-                uuid             : $(anyUuid()),
-                date             : $(anyDate()),
-                dateTime         : $(anyDateTime()),
-                time             : $(anyTime()),
-                iso8601WithOffset: $(anyIso8601WithOffset()),
-                nonBlankString   : $(anyNonBlankString()),
-                nonEmptyString   : $(anyNonEmptyString()),
-                anyOf            : $(anyOf('foo', 'bar'))
-        ])
-    }
-}
-
-
-
-
kotlin
-
-
contract {
-    name = "foo"
-    label = "trigger_event"
-    input {
-        triggeredBy = "toString()"
-    }
-    outputMessage {
-        sentTo = sentTo("topic.rateablequote")
-        body(mapOf(
-                "alpha" to v(anyAlphaUnicode),
-                "number" to v(anyNumber),
-                "anInteger" to v(anyInteger),
-                "positiveInt" to v(anyPositiveInt),
-                "aDouble" to v(anyDouble),
-                "aBoolean" to v(aBoolean),
-                "ip" to v(anyIpAddress),
-                "hostname" to v(anyAlphaUnicode),
-                "email" to v(anyEmail),
-                "url" to v(anyUrl),
-                "httpsUrl" to v(anyHttpsUrl),
-                "uuid" to v(anyUuid),
-                "date" to v(anyDate),
-                "dateTime" to v(anyDateTime),
-                "time" to v(anyTime),
-                "iso8601WithOffset" to v(anyIso8601WithOffset),
-                "nonBlankString" to v(anyNonBlankString),
-                "nonEmptyString" to v(anyNonEmptyString),
-                "anyOf" to v(anyOf('foo', 'bar'))
-        ))
-        headers {
-            header("Content-Type", "text/plain")
-        }
-    }
-}
-
-
-
-
-
-
Limitations
-
- - - - - -
- - -Due to certain limitations of the Xeger library that generates a string out of -a regex, do not use the $ and ^ signs in your regex if you rely on automatic -generation. See Issue 899. -
-
-
- - - - - -
- - -Do not use a LocalDate instance as a value for $ (for example, $(consumer(LocalDate.now()))). -It causes a java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. -See Issue 900. -
-
-
-
-
-

2.4.3. Passing Optional Parameters

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can provide optional parameters in your contract. However, you can provide -optional parameters only for the following:

-
-
-
    -
  • -

    The STUB side of the Request

    -
  • -
  • -

    The TEST side of the Response

    -
  • -
-
-
-

The following example shows how to provide optional parameters:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    priority 1
-    name "optionals"
-    request {
-        method 'POST'
-        url '/users/password'
-        headers {
-            contentType(applicationJson())
-        }
-        body(
-                email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
-                callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
-        )
-    }
-    response {
-        status 404
-        headers {
-            header 'Content-Type': 'application/json'
-        }
-        body(
-                code: value(consumer("123123"), producer(optional("123123")))
-        )
-    }
-}
-
-
-
-
java
-
-
org.springframework.cloud.contract.spec.Contract.make(c -> {
-    c.priority(1);
-    c.name("optionals");
-    c.request(r -> {
-        r.method("POST");
-        r.url("/users/password");
-        r.headers(h -> {
-            h.contentType(h.applicationJson());
-        });
-        r.body(ContractVerifierUtil.map()
-                .entry("email",
-                        r.$(r.consumer(r.optional(r.regex(r.email()))),
-                                r.producer("abc@abc.com")))
-                .entry("callback_url", r.$(r.consumer(r.regex(r.hostname())),
-                        r.producer("https://partners.com"))));
-    });
-    c.response(r -> {
-        r.status(404);
-        r.headers(h -> {
-            h.header("Content-Type", "application/json");
-        });
-        r.body(ContractVerifierUtil.map().entry("code", r.value(
-                r.consumer("123123"), r.producer(r.optional("123123")))));
-    });
-});
-
-
-
-
kotlin
-
-
contract { c ->
-    priority = 1
-    name = "optionals"
-    request {
-        method = POST
-        url = url("/users/password")
-        headers {
-            contentType = APPLICATION_JSON
-        }
-        body = body(mapOf(
-                "email" to v(consumer(optional(regex(email))), producer("abc@abc.com")),
-                "callback_url" to v(consumer(regex(hostname)), producer("https://partners.com"))
-        ))
-    }
-    response {
-        status = NOT_FOUND
-        headers {
-            header("Content-Type", "application/json")
-        }
-        body(mapOf(
-                "code" to value(consumer("123123"), producer(optional("123123")))
-        ))
-    }
-}
-
-
-
-
-
-

By wrapping a part of the body with the optional() method, you create a regular -expression that must be present 0 or more times.

-
-
-

If you use Spock, the following test would be generated from the previous example:

-
-
-
-
-
groovy
-
-
                    """\
-package com.example
-
-import com.jayway.jsonpath.DocumentContext
-import com.jayway.jsonpath.JsonPath
-import spock.lang.Specification
-import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
-import io.restassured.response.ResponseOptions
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
-import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
-
-@SuppressWarnings("rawtypes")
-class FooSpec extends Specification {
-
-\tdef validate_optionals() throws Exception {
-\t\tgiven:
-\t\t\tMockMvcRequestSpecification request = given()
-\t\t\t\t\t.header("Content-Type", "application/json")
-\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
-
-\t\twhen:
-\t\t\tResponseOptions response = given().spec(request)
-\t\t\t\t\t.post("/users/password")
-
-\t\tthen:
-\t\t\tresponse.statusCode() == 404
-\t\t\tresponse.header("Content-Type") == 'application/json'
-
-\t\tand:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
-\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
-\t}
-
-}
-"""
-
-
-
-
-
-

The following stub would also be generated:

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

2.4.4. Executing Custom Methods on the Server Side

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can define a method call that runs on the server side during the test. Such a -method can be added to the class defined as baseClassForTests in the configuration. The -following code shows an example of the contract portion of the test case:

-
-
-
-
-
groovy
-
-
method GET()
-
-
-
-
java
-
-
r.method(r.GET());
-
-
-
-
kotlin
-
-
method = GET
-
-
-
-
-
-

The following code shows the base class portion of the test case:

-
-
-
-
abstract class BaseMockMvcSpec extends Specification {
-
-    def setup() {
-        RestAssuredMockMvc.standaloneSetup(new PairIdController())
-    }
-
-    void isProperCorrelationId(Integer correlationId) {
-        assert correlationId == 123456
-    }
-
-    void isEmpty(String value) {
-        assert value == null
-    }
-
-}
-
-
-
- - - - - -
- - -You cannot use both a String and execute to perform concatenation. For -example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to -improper results. Instead, call header('Authorization', execute('authToken()')) and -ensure that the authToken() method returns everything you need. -
-
-
-

The type of the object read from the JSON can be one of the following, depending on the -JSON path:

-
-
-
    -
  • -

    String: If you point to a String value in the JSON.

    -
  • -
  • -

    JSONArray: If you point to a List in the JSON.

    -
  • -
  • -

    Map: If you point to a Map in the JSON.

    -
  • -
  • -

    Number: If you point to Integer, Double, and other numeric type in the JSON.

    -
  • -
  • -

    Boolean: If you point to a Boolean in the JSON.

    -
  • -
-
-
-

In the request part of the contract, you can specify that the body should be taken from -a method.

-
-
- - - - - -
- - -You must provide both the consumer and the producer side. The execute part -is applied for the whole body, not for parts of it. -
-
-
-

The following example shows how to read an object from JSON:

-
-
-
-
Contract contractDsl = Contract.make {
-    request {
-        method 'GET'
-        url '/something'
-        body(
-                $(c('foo'), p(execute('hashCode()')))
-        )
-    }
-    response {
-        status OK()
-    }
-}
-
-
-
-

The preceding example results in calling the hashCode() method in the request body. -It should resemble the following code:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .body(hashCode());
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/something");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-
-

2.4.5. Referencing the Request from the Response

-
-

The best situation is to provide fixed values, but sometimes you need to reference a -request in your response.

-
-
-

If you write contracts in the Groovy DSL, you can use the fromRequest() method, which lets -you reference a bunch of elements from the HTTP request. You can use the following -options:

-
-
-
    -
  • -

    fromRequest().url(): Returns the request URL and query parameters.

    -
  • -
  • -

    fromRequest().query(String key): Returns the first query parameter with a given name.

    -
  • -
  • -

    fromRequest().query(String key, int index): Returns the nth query parameter with a -given name.

    -
  • -
  • -

    fromRequest().path(): Returns the full path.

    -
  • -
  • -

    fromRequest().path(int index): Returns the nth path element.

    -
  • -
  • -

    fromRequest().header(String key): Returns the first header with a given name.

    -
  • -
  • -

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    -
  • -
  • -

    fromRequest().body(): Returns the full request body.

    -
  • -
  • -

    fromRequest().body(String jsonPath): Returns the element from the request that -matches the JSON Path.

    -
  • -
-
-
-

If you use the YAML contract definition or the Java one, you have to use the -Handlebars {{{ }}} notation with custom Spring Cloud Contract -functions to achieve this. In that case, you can use the following options:

-
-
-
    -
  • -

    {{{ request.url }}}: Returns the request URL and query parameters.

    -
  • -
  • -

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. -For example, for a key of thing, the first entry is {{{ request.query.thing.[0] }}}

    -
  • -
  • -

    {{{ request.path }}}: Returns the full path.

    -
  • -
  • -

    {{{ request.path.[index] }}}: Returns the nth path element. For example, -the first entry is `{{{ request.path.[0] }}}

    -
  • -
  • -

    {{{ request.headers.key }}}: Returns the first header with a given name.

    -
  • -
  • -

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    -
  • -
  • -

    {{{ request.body }}}: Returns the full request body.

    -
  • -
  • -

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that -matches the JSON Path. For example, for a JSON path of $.here, use {{{ jsonpath this '$.here' }}}

    -
  • -
-
-
-

Consider the following contract:

-
-
-
-
-
groovy
-
-
Contract contractDsl = Contract.make {
-    request {
-        method 'GET'
-        url('/api/v1/xxxx') {
-            queryParameters {
-                parameter('foo', 'bar')
-                parameter('foo', 'bar2')
-            }
-        }
-        headers {
-            header(authorization(), 'secret')
-            header(authorization(), 'secret2')
-        }
-        body(foo: 'bar', baz: 5)
-    }
-    response {
-        status OK()
-        headers {
-            header(authorization(), "foo ${fromRequest().header(authorization())} bar")
-        }
-        body(
-                url: fromRequest().url(),
-                path: fromRequest().path(),
-                pathIndex: fromRequest().path(1),
-                param: fromRequest().query('foo'),
-                paramIndex: fromRequest().query('foo', 1),
-                authorization: fromRequest().header('Authorization'),
-                authorization2: fromRequest().header('Authorization', 1),
-                fullBody: fromRequest().body(),
-                responseFoo: fromRequest().body('$.foo'),
-                responseBaz: fromRequest().body('$.baz'),
-                responseBaz2: "Bla bla ${fromRequest().body('$.foo')} bla bla",
-                rawUrl: fromRequest().rawUrl(),
-                rawPath: fromRequest().rawPath(),
-                rawPathIndex: fromRequest().rawPath(1),
-                rawParam: fromRequest().rawQuery('foo'),
-                rawParamIndex: fromRequest().rawQuery('foo', 1),
-                rawAuthorization: fromRequest().rawHeader('Authorization'),
-                rawAuthorization2: fromRequest().rawHeader('Authorization', 1),
-                rawResponseFoo: fromRequest().rawBody('$.foo'),
-                rawResponseBaz: fromRequest().rawBody('$.baz'),
-                rawResponseBaz2: "Bla bla ${fromRequest().rawBody('$.foo')} bla bla"
-        )
-    }
-}
-Contract contractDsl = Contract.make {
-    request {
-        method 'GET'
-        url('/api/v1/xxxx') {
-            queryParameters {
-                parameter('foo', 'bar')
-                parameter('foo', 'bar2')
-            }
-        }
-        headers {
-            header(authorization(), 'secret')
-            header(authorization(), 'secret2')
-        }
-        body(foo: "bar", baz: 5)
-    }
-    response {
-        status OK()
-        headers {
-            contentType(applicationJson())
-        }
-        body('''
-                {
-                    "responseFoo": "{{{ jsonPath request.body '$.foo' }}}",
-                    "responseBaz": {{{ jsonPath request.body '$.baz' }}},
-                    "responseBaz2": "Bla bla {{{ jsonPath request.body '$.foo' }}} bla bla"
-                }
-        '''.toString())
-    }
-}
-
-
-
-
yml
-
-
request:
-  method: GET
-  url: /api/v1/xxxx
-  queryParameters:
-    foo:
-      - bar
-      - bar2
-  headers:
-    Authorization:
-      - secret
-      - secret2
-  body:
-    foo: bar
-    baz: 5
-response:
-  status: 200
-  headers:
-    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
-  body:
-    url: "{{{ request.url }}}"
-    path: "{{{ request.path }}}"
-    pathIndex: "{{{ request.path.1 }}}"
-    param: "{{{ request.query.foo }}}"
-    paramIndex: "{{{ request.query.foo.1 }}}"
-    authorization: "{{{ request.headers.Authorization.0 }}}"
-    authorization2: "{{{ request.headers.Authorization.1 }}"
-    fullBody: "{{{ request.body }}}"
-    responseFoo: "{{{ jsonpath this '$.foo' }}}"
-    responseBaz: "{{{ jsonpath this '$.baz' }}}"
-    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"
-
-
-
-
java
-
-
package contracts.beer.rest;
-
-import java.util.function.Supplier;
-
-import org.springframework.cloud.contract.spec.Contract;
-
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.map;
-
-class shouldReturnStatsForAUser implements Supplier<Contract> {
-
-    @Override
-    public Contract get() {
-        return Contract.make(c -> {
-            c.request(r -> {
-                r.method("POST");
-                r.url("/stats");
-                r.body(map().entry("name", r.anyAlphaUnicode()));
-                r.headers(h -> {
-                    h.contentType(h.applicationJson());
-                });
-            });
-            c.response(r -> {
-                r.status(r.OK());
-                r.body(map()
-                        .entry("text",
-                                "Dear {{{jsonPath request.body '$.name'}}} thanks for your interested in drinking beer")
-                        .entry("quantity", r.$(r.c(5), r.p(r.anyNumber()))));
-                r.headers(h -> {
-                    h.contentType(h.applicationJson());
-                });
-            });
-        });
-    }
-
-}
-
-
-
-
kotlin
-
-
package contracts.beer.rest
-
-import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        method = method("POST")
-        url = url("/stats")
-        body(mapOf(
-            "name" to anyAlphaUnicode
-        ))
-        headers {
-            contentType = APPLICATION_JSON
-        }
-    }
-    response {
-        status = OK
-        body(mapOf(
-            "text" to "Don't worry ${fromRequest().body("$.name")} thanks for your interested in drinking beer",
-            "quantity" to v(c(5), p(anyNumber))
-        ))
-        headers {
-            contentType = fromRequest().header(CONTENT_TYPE)
-        }
-    }
-}
-
-
-
-
-
-

Running a JUnit test generation leads to a test that resembles the following example:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Authorization", "secret")
-   .header("Authorization", "secret2")
-   .body("{\"foo\":\"bar\",\"baz\":5}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .queryParam("foo","bar")
-   .queryParam("foo","bar2")
-   .get("/api/v1/xxxx");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
- assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
- assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
- assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
- assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
- assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
- assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
- assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
- assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
-
-
-
-

As you can see, elements from the request have been properly referenced in the response.

-
-
-

The generated WireMock stub should resemble the following example:

-
-
-
-
{
-  "request" : {
-    "urlPath" : "/api/v1/xxxx",
-    "method" : "POST",
-    "headers" : {
-      "Authorization" : {
-        "equalTo" : "secret2"
-      }
-    },
-    "queryParameters" : {
-      "foo" : {
-        "equalTo" : "bar2"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
-    "headers" : {
-      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
-    },
-    "transformers" : [ "response-template" ]
-  }
-}
-
-
-
-

Sending a request such as the one presented in the request part of the contract results -in sending the following response body:

-
-
-
-
{
-  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
-  "path" : "/api/v1/xxxx",
-  "pathIndex" : "v1",
-  "param" : "bar",
-  "paramIndex" : "bar2",
-  "authorization" : "secret",
-  "authorization2" : "secret2",
-  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
-  "responseFoo" : "bar",
-  "responseBaz" : 5,
-  "responseBaz2" : "Bla bla bar bla bla"
-}
-
-
-
- - - - - -
- - -This feature works only with WireMock versions greater than or equal -to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s -response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into -proper values. Additionally, it registers two helper functions: -
-
-
-
    -
  • -

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    -
  • -
  • -

    jsonpath: For a given parameter, find an object in the request body.

    -
  • -
-
-
-
-

2.4.6. Dynamic Properties in the Matchers Sections

-
-

If you work with Pact, the following discussion may seem familiar. -Quite a few users are used to having a separation between the body and setting the -dynamic parts of a contract.

-
-
-

You can use the bodyMatchers section for two reasons:

-
-
-
    -
  • -

    Define the dynamic values that should end up in a stub. -You can set it in the request or inputMessage part of your contract.

    -
  • -
  • -

    Verify the result of your test. -This section is present in the response or outputMessage side of the -contract.

    -
  • -
-
-
-

Currently, Spring Cloud Contract Verifier supports only JSON path-based matchers with the -following matching possibilities:

-
-
-
Coded DSL
-
-
    -
  • -

    For the stubs (in tests on the consumer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the consumer’s request in the provided JSON path must be -equal to the value provided in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the consumer’s request in the provided JSON path must -match the regex. You can also pass the type of the expected matched value (for example, asString(), asLong(), and so on).

      -
    • -
    • -

      byDate(): The value taken from the consumer’s request in the provided JSON path must -match the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the consumer’s request in the provided JSON path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the consumer’s request in the provided JSON path must -match the regex for an ISO Time value.

      -
    • -
    -
    -
  • -
  • -

    For the verification (in generated tests on the Producer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the producer’s response in the provided JSON path must be -equal to the provided value in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the producer’s response in the provided JSON path must -match the regex.

      -
    • -
    • -

      byDate(): The value taken from the producer’s response in the provided JSON path must match -the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the producer’s response in the provided JSON path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the producer’s response in the provided JSON path must match -the regex for an ISO Time value.

      -
    • -
    • -

      byType(): The value taken from the producer’s response in the provided JSON path needs to be -of the same type as the type defined in the body of the response in the contract. -byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the -request side, you should use the closure to assert size of the collection. -That way, you can assert the size of the flattened collection. To check the size of an -unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      -
    • -
    • -

      byCommand(…​): The value taken from the producer’s response in the provided JSON path is -passed as an input to the custom method that you provide. For example, -byCommand('thing($it)') results in calling a thing method to which the value matching the -JSON Path gets passed. The type of the object read from the JSON can be one of the -following, depending on the JSON path:

      -
      -
        -
      • -

        String: If you point to a String value.

        -
      • -
      • -

        JSONArray: If you point to a List.

        -
      • -
      • -

        Map: If you point to a Map.

        -
      • -
      • -

        Number: If you point to Integer, Double, or another kind of number.

        -
      • -
      • -

        Boolean: If you point to a Boolean.

        -
      • -
      -
      -
    • -
    • -

      byNull(): The value taken from the response in the provided JSON path must be null.

      -
    • -
    -
    -
  • -
-
-
-
-
YAML
-
- - - - - -
- - -See the Groovy section for detailed explanation of -what the types mean. -
-
-
-

For YAML, the structure of a matcher resembles the following example:

-
-
-
-
- path: $.thing1
-  type: by_regex
-  value: thing2
-  regexType: as_string
-
-
-
-

Alternatively, if you want to use one of the predefined regular expressions -[only_alpha_unicode, number, any_boolean, ip_address, hostname, -email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, -non_blank], you can use something similar to the following example:

-
-
-
-
- path: $.thing1
-  type: by_regex
-  predefined: only_alpha_unicode
-
-
-
-

The following list shows the allowed list of type values:

-
-
-
    -
  • -

    For stubMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        Two additional fields (minOccurrence and maxOccurrence) are accepted.

        -
      • -
      -
      -
    • -
    -
    -
  • -
  • -

    For testMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        Two additional fields (minOccurrence and maxOccurrence) are accepted.

        -
      • -
      -
      -
    • -
    • -

      by_command

      -
    • -
    • -

      by_null

      -
    • -
    -
    -
  • -
-
-
-

You can also define which type the regular expression corresponds to in the regexType -field. The following list shows the allowed regular expression types:

-
-
-
    -
  • -

    as_integer

    -
  • -
  • -

    as_double

    -
  • -
  • -

    as_float

    -
  • -
  • -

    as_long

    -
  • -
  • -

    as_short

    -
  • -
  • -

    as_boolean

    -
  • -
  • -

    as_string

    -
  • -
-
-
-

Consider the following example:

-
-
-
-
-
groovy
-
-
Contract contractDsl = Contract.make {
-    request {
-        method 'GET'
-        urlPath '/get'
-        body([
-                duck                : 123,
-                alpha               : 'abc',
-                number              : 123,
-                aBoolean            : true,
-                date                : '2017-01-01',
-                dateTime            : '2017-01-01T01:23:45',
-                time                : '01:02:34',
-                valueWithoutAMatcher: 'foo',
-                valueWithTypeMatch  : 'string',
-                key                 : [
-                        'complex.key': 'foo'
-                ]
-        ])
-        bodyMatchers {
-            jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
-            jsonPath('$.duck', byEquality())
-            jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
-            jsonPath('$.alpha', byEquality())
-            jsonPath('$.number', byRegex(number()).asInteger())
-            jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
-            jsonPath('$.date', byDate())
-            jsonPath('$.dateTime', byTimestamp())
-            jsonPath('$.time', byTime())
-            jsonPath("\$.['key'].['complex.key']", byEquality())
-        }
-        headers {
-            contentType(applicationJson())
-        }
-    }
-    response {
-        status OK()
-        body([
-                duck                 : 123,
-                alpha                : 'abc',
-                number               : 123,
-                positiveInteger      : 1234567890,
-                negativeInteger      : -1234567890,
-                positiveDecimalNumber: 123.4567890,
-                negativeDecimalNumber: -123.4567890,
-                aBoolean             : true,
-                date                 : '2017-01-01',
-                dateTime             : '2017-01-01T01:23:45',
-                time                 : "01:02:34",
-                valueWithoutAMatcher : 'foo',
-                valueWithTypeMatch   : 'string',
-                valueWithMin         : [
-                        1, 2, 3
-                ],
-                valueWithMax         : [
-                        1, 2, 3
-                ],
-                valueWithMinMax      : [
-                        1, 2, 3
-                ],
-                valueWithMinEmpty    : [],
-                valueWithMaxEmpty    : [],
-                key                  : [
-                        'complex.key': 'foo'
-                ],
-                nullValue            : null
-        ])
-        bodyMatchers {
-            // asserts the jsonpath value against manual regex
-            jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
-            // asserts the jsonpath value against the provided value
-            jsonPath('$.duck', byEquality())
-            // asserts the jsonpath value against some default regex
-            jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
-            jsonPath('$.alpha', byEquality())
-            jsonPath('$.number', byRegex(number()).asInteger())
-            jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
-            jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
-            jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
-            jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
-            jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
-            // asserts vs inbuilt time related regex
-            jsonPath('$.date', byDate())
-            jsonPath('$.dateTime', byTimestamp())
-            jsonPath('$.time', byTime())
-            // asserts that the resulting type is the same as in response body
-            jsonPath('$.valueWithTypeMatch', byType())
-            jsonPath('$.valueWithMin', byType {
-                // results in verification of size of array (min 1)
-                minOccurrence(1)
-            })
-            jsonPath('$.valueWithMax', byType {
-                // results in verification of size of array (max 3)
-                maxOccurrence(3)
-            })
-            jsonPath('$.valueWithMinMax', byType {
-                // results in verification of size of array (min 1 & max 3)
-                minOccurrence(1)
-                maxOccurrence(3)
-            })
-            jsonPath('$.valueWithMinEmpty', byType {
-                // results in verification of size of array (min 0)
-                minOccurrence(0)
-            })
-            jsonPath('$.valueWithMaxEmpty', byType {
-                // results in verification of size of array (max 0)
-                maxOccurrence(0)
-            })
-            // will execute a method `assertThatValueIsANumber`
-            jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
-            jsonPath("\$.['key'].['complex.key']", byEquality())
-            jsonPath('$.nullValue', byNull())
-        }
-        headers {
-            contentType(applicationJson())
-            header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
-        }
-    }
-}
-
-
-
-
yml
-
-
request:
-  method: GET
-  urlPath: /get/1
-  headers:
-    Content-Type: application/json
-  cookies:
-    foo: 2
-    bar: 3
-  queryParameters:
-    limit: 10
-    offset: 20
-    filter: 'email'
-    sort: name
-    search: 55
-    age: 99
-    name: John.Doe
-    email: 'bob@email.com'
-  body:
-    duck: 123
-    alpha: "abc"
-    number: 123
-    aBoolean: true
-    date: "2017-01-01"
-    dateTime: "2017-01-01T01:23:45"
-    time: "01:02:34"
-    valueWithoutAMatcher: "foo"
-    valueWithTypeMatch: "string"
-    key:
-      "complex.key": 'foo'
-    nullValue: null
-    valueWithMin:
-      - 1
-      - 2
-      - 3
-    valueWithMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinEmpty: []
-    valueWithMaxEmpty: []
-  matchers:
-    url:
-      regex: /get/[0-9]
-      # predefined:
-      # execute a method
-      #command: 'equals($it)'
-    queryParameters:
-      - key: limit
-        type: equal_to
-        value: 20
-      - key: offset
-        type: containing
-        value: 20
-      - key: sort
-        type: equal_to
-        value: name
-      - key: search
-        type: not_matching
-        value: '^[0-9]{2}$'
-      - key: age
-        type: not_matching
-        value: '^\\w*$'
-      - key: name
-        type: matching
-        value: 'John.*'
-      - key: hello
-        type: absent
-    cookies:
-      - key: foo
-        regex: '[0-9]'
-      - key: bar
-        command: 'equals($it)'
-    headers:
-      - key: Content-Type
-        regex: "application/json.*"
-    body:
-      - path: $.duck
-        type: by_regex
-        value: "[0-9]{3}"
-      - path: $.duck
-        type: by_equality
-      - path: $.alpha
-        type: by_regex
-        predefined: only_alpha_unicode
-      - path: $.alpha
-        type: by_equality
-      - path: $.number
-        type: by_regex
-        predefined: number
-      - path: $.aBoolean
-        type: by_regex
-        predefined: any_boolean
-      - path: $.date
-        type: by_date
-      - path: $.dateTime
-        type: by_timestamp
-      - path: $.time
-        type: by_time
-      - path: "$.['key'].['complex.key']"
-        type: by_equality
-      - path: $.nullvalue
-        type: by_null
-      - path: $.valueWithMin
-        type: by_type
-        minOccurrence: 1
-      - path: $.valueWithMax
-        type: by_type
-        maxOccurrence: 3
-      - path: $.valueWithMinMax
-        type: by_type
-        minOccurrence: 1
-        maxOccurrence: 3
-response:
-  status: 200
-  cookies:
-    foo: 1
-    bar: 2
-  body:
-    duck: 123
-    alpha: "abc"
-    number: 123
-    aBoolean: true
-    date: "2017-01-01"
-    dateTime: "2017-01-01T01:23:45"
-    time: "01:02:34"
-    valueWithoutAMatcher: "foo"
-    valueWithTypeMatch: "string"
-    valueWithMin:
-      - 1
-      - 2
-      - 3
-    valueWithMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinEmpty: []
-    valueWithMaxEmpty: []
-    key:
-      'complex.key': 'foo'
-    nulValue: null
-  matchers:
-    headers:
-      - key: Content-Type
-        regex: "application/json.*"
-    cookies:
-      - key: foo
-        regex: '[0-9]'
-      - key: bar
-        command: 'equals($it)'
-    body:
-      - path: $.duck
-        type: by_regex
-        value: "[0-9]{3}"
-      - path: $.duck
-        type: by_equality
-      - path: $.alpha
-        type: by_regex
-        predefined: only_alpha_unicode
-      - path: $.alpha
-        type: by_equality
-      - path: $.number
-        type: by_regex
-        predefined: number
-      - path: $.aBoolean
-        type: by_regex
-        predefined: any_boolean
-      - path: $.date
-        type: by_date
-      - path: $.dateTime
-        type: by_timestamp
-      - path: $.time
-        type: by_time
-      - path: $.valueWithTypeMatch
-        type: by_type
-      - path: $.valueWithMin
-        type: by_type
-        minOccurrence: 1
-      - path: $.valueWithMax
-        type: by_type
-        maxOccurrence: 3
-      - path: $.valueWithMinMax
-        type: by_type
-        minOccurrence: 1
-        maxOccurrence: 3
-      - path: $.valueWithMinEmpty
-        type: by_type
-        minOccurrence: 0
-      - path: $.valueWithMaxEmpty
-        type: by_type
-        maxOccurrence: 0
-      - path: $.duck
-        type: by_command
-        value: assertThatValueIsANumber($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-  headers:
-    Content-Type: application/json
-
-
-
-
-
-

In the preceding example, you can see the dynamic portions of the contract in the -matchers sections. For the request part, you can see that, for all fields but -valueWithoutAMatcher, the values of the regular expressions that the stub should -contain are explicitly set. For the valueWithoutAMatcher, the verification takes place -in the same way as without the use of matchers. In that case, the test performs an -equality check.

-
-
-

For the response side in the bodyMatchers section, we define the dynamic parts in a -similar manner. The only difference is that the byType matchers are also present. The -verifier engine checks four fields to verify whether the response from the test -has a value for which the JSON path matches the given field, is of the same type as the one -defined in the response body, and passes the following check (based on the method being called):

-
-
-
    -
  • -

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    -
  • -
  • -

    For $.valueWithMin, the engine checks the type and asserts whether the size is greater -than or equal to the minimum occurrence.

    -
  • -
  • -

    For $.valueWithMax, the engine checks the type and asserts whether the size is -smaller than or equal to the maximum occurrence.

    -
  • -
  • -

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is -between the minimum and maximum occurrence.

    -
  • -
-
-
-

The resulting test resembles the following example (note that an and section -separates the autogenerated assertions and the assertion from matchers):

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Content-Type", "application/json")
-   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/get");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Content-Type")).matches("application/json.*");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
-// and:
- assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
- assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
- assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
- assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
- assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
- assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
- assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
- assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
- assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
- assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
- assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
- assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
- assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
- assertThatValueIsANumber(parsedJson.read("$.duck"));
- assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
-
-
-
- - - - - -
- - -Notice that, for the byCommand method, the example calls the -assertThatValueIsANumber. This method must be defined in the test base class or be -statically imported to your tests. Notice that the byCommand call was converted to -assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took -the method name and passed the proper JSON path as a parameter to it. -
-
-
-

The resulting WireMock stub is in the following example:

-
-
-
-
                    '''
-{
-  "request" : {
-    "urlPath" : "/get",
-    "method" : "POST",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "application/json.*"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
-    }, {
-      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
-    }, {
-      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.duck == 123)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
-    }, {
-      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
-    }, {
-      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"number\\":123,\\"aBoolean\\":true,\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"time\\":\\"01:02:34\\",\\"valueWithoutAMatcher\\":\\"foo\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMin\\":[1,2,3],\\"valueWithMax\\":[1,2,3],\\"valueWithMinMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4]}",
-    "headers" : {
-      "Content-Type" : "application/json"
-    },
-    "transformers" : [ "response-template" ]
-  }
-}
-'''
-
-
-
- - - - - -
- - -If you use a matcher, the part of the request and response that the -matcher addresses with the JSON Path gets removed from the assertion. In the case of -verifying a collection, you must create matchers for all the elements of the -collection. -
-
-
-

Consider the following example:

-
-
-
-
Contract.make {
-    request {
-        method 'GET'
-        url("/foo")
-    }
-    response {
-        status OK()
-        body(events: [[
-                                 operation          : 'EXPORT',
-                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
-                                 status             : 'OK'
-                         ], [
-                                 operation          : 'INPUT_PROCESSING',
-                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
-                                 status             : 'OK'
-                         ]
-                ]
-        )
-        bodyMatchers {
-            jsonPath('$.events[0].operation', byRegex('.+'))
-            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
-            jsonPath('$.events[0].status', byRegex('.+'))
-        }
-    }
-}
-
-
-
-

The preceding code leads to creating the following test (the code block shows only the assertion section):

-
-
-
-
and:
-    DocumentContext parsedJson = JsonPath.parse(response.body.asString())
-    assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
-    assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
-    assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
-    assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
-    assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
-and:
-    assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
-    assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
-    assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
-
-
-
-

As you can see, the assertion is malformed. Only the first element of the array got -asserted. In order to fix this, you should apply the assertion to the whole $.events -collection and assert it with the byCommand(…​) method.

-
-
-
-
-
-

2.5. Asynchronous Support

-
-

If you use asynchronous communication on the server side (your controllers are -returning Callable, DeferredResult, and so on), then, inside your contract, you must -provide an async() method in the response section. The following code shows an example:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status OK()
-        body 'Passed'
-        async()
-    }
-}
-
-
-
-
yml
-
-
response:
-    async: true
-
-
-
-
java
-
-
class contract implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.request(r -> {
-                // ...
-            });
-            c.response(r -> {
-                r.async();
-                // ...
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        // ...
-    }
-    response {
-        async = true
-        // ...
-    }
-}
-
-
-
-
-
-

You can also use the fixedDelayMilliseconds method or property to add delay to your stubs. -The following example shows how to do so:

-
-
-
-
-
groovy
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status 200
-        body 'Passed'
-        fixedDelayMilliseconds 1000
-    }
-}
-
-
-
-
yml
-
-
response:
-    fixedDelayMilliseconds: 1000
-
-
-
-
java
-
-
class contract implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Collections.singletonList(Contract.make(c -> {
-            c.request(r -> {
-                // ...
-            });
-            c.response(r -> {
-                r.fixedDelayMilliseconds(1000);
-                // ...
-            });
-        }));
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        // ...
-    }
-    response {
-        delay = fixedMilliseconds(1000)
-        // ...
-    }
-}
-
-
-
-
-
-
-

2.6. XML Support for HTTP

-
-

For HTTP contracts, we also support using XML in the request and response body. -The XML body has to be passed within the body element -as a String or GString. Also, body matchers can be provided for -both the request and the response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath -method should be used, with the desired xPath provided as the first argument -and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

-
-
-

The following example shows a Groovy DSL contract with XML in the response body:

-
-
-
-
-
groovy
-
-
                    Contract.make {
-                        request {
-                            method GET()
-                            urlPath '/get'
-                            headers {
-                                contentType(applicationXml())
-                            }
-                        }
-                        response {
-                            status(OK())
-                            headers {
-                                contentType(applicationXml())
-                            }
-                            body """
-<test>
-<duck type='xtype'>123</duck>
-<alpha>abc</alpha>
-<list>
-<elem>abc</elem>
-<elem>def</elem>
-<elem>ghi</elem>
-</list>
-<number>123</number>
-<aBoolean>true</aBoolean>
-<date>2017-01-01</date>
-<dateTime>2017-01-01T01:23:45</dateTime>
-<time>01:02:34</time>
-<valueWithoutAMatcher>foo</valueWithoutAMatcher>
-<key><complex>foo</complex></key>
-</test>"""
-                            bodyMatchers {
-                                xPath('/test/duck/text()', byRegex("[0-9]{3}"))
-                                xPath('/test/duck/text()', byCommand('equals($it)'))
-                                xPath('/test/duck/xxx', byNull())
-                                xPath('/test/duck/text()', byEquality())
-                                xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
-                                xPath('/test/alpha/text()', byEquality())
-                                xPath('/test/number/text()', byRegex(number()))
-                                xPath('/test/date/text()', byDate())
-                                xPath('/test/dateTime/text()', byTimestamp())
-                                xPath('/test/time/text()', byTime())
-                                xPath('/test/*/complex/text()', byEquality())
-                                xPath('/test/duck/@type', byEquality())
-                            }
-                        }
-                    }
-
-
-
-
yml
-
-
include::/opt/jenkins/data/workspace/spring-cloud-contract-master-ci/spring-cloud-contract-verifier/src/test/resources/yml/contract_rest_xml.yml
-
-
-
-
java
-
-
import java.util.function.Supplier;
-
-import org.springframework.cloud.contract.spec.Contract;
-
-class contract_xml implements Supplier<Contract> {
-
-    @Override
-    public Contract get() {
-        return Contract.make(c -> {
-            c.request(r -> {
-                r.method(r.GET());
-                r.urlPath("/get");
-                r.headers(h -> {
-                    h.contentType(h.applicationXml());
-                });
-            });
-            c.response(r -> {
-                r.status(r.OK());
-                r.headers(h -> {
-                    h.contentType(h.applicationXml());
-                });
-                r.body("<test>\n" + "<duck type='xtype'>123</duck>\n"
-                        + "<alpha>abc</alpha>\n" + "<list>\n" + "<elem>abc</elem>\n"
-                        + "<elem>def</elem>\n" + "<elem>ghi</elem>\n" + "</list>\n"
-                        + "<number>123</number>\n" + "<aBoolean>true</aBoolean>\n"
-                        + "<date>2017-01-01</date>\n"
-                        + "<dateTime>2017-01-01T01:23:45</dateTime>\n"
-                        + "<time>01:02:34</time>\n"
-                        + "<valueWithoutAMatcher>foo</valueWithoutAMatcher>\n"
-                        + "<key><complex>foo</complex></key>\n" + "</test>");
-                r.bodyMatchers(m -> {
-                    m.xPath("/test/duck/text()", m.byRegex("[0-9]{3}"));
-                    m.xPath("/test/duck/text()", m.byCommand("equals($it)"));
-                    m.xPath("/test/duck/xxx", m.byNull());
-                    m.xPath("/test/duck/text()", m.byEquality());
-                    m.xPath("/test/alpha/text()", m.byRegex(r.onlyAlphaUnicode()));
-                    m.xPath("/test/alpha/text()", m.byEquality());
-                    m.xPath("/test/number/text()", m.byRegex(r.number()));
-                    m.xPath("/test/date/text()", m.byDate());
-                    m.xPath("/test/dateTime/text()", m.byTimestamp());
-                    m.xPath("/test/time/text()", m.byTime());
-                    m.xPath("/test/*/complex/text()", m.byEquality());
-                    m.xPath("/test/duck/@type", m.byEquality());
-                });
-            });
-        });
-    };
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-contract {
-    request {
-        method = GET
-        urlPath = path("/get")
-        headers {
-            contentType = APPLICATION_XML
-        }
-    }
-    response {
-        status = OK
-        headers {
-            contentType =APPLICATION_XML
-        }
-        body = body("<test>\n" + "<duck type='xtype'>123</duck>\n"
-                + "<alpha>abc</alpha>\n" + "<list>\n" + "<elem>abc</elem>\n"
-                + "<elem>def</elem>\n" + "<elem>ghi</elem>\n" + "</list>\n"
-                + "<number>123</number>\n" + "<aBoolean>true</aBoolean>\n"
-                + "<date>2017-01-01</date>\n"
-                + "<dateTime>2017-01-01T01:23:45</dateTime>\n"
-                + "<time>01:02:34</time>\n"
-                + "<valueWithoutAMatcher>foo</valueWithoutAMatcher>\n"
-                + "<key><complex>foo</complex></key>\n" + "</test>")
-        bodyMatchers {
-            xPath("/test/duck/text()", byRegex("[0-9]{3}"))
-            xPath("/test/duck/text()", byCommand("equals(\$it)"))
-            xPath("/test/duck/xxx", byNull)
-            xPath("/test/duck/text()", byEquality)
-            xPath("/test/alpha/text()", byRegex(onlyAlphaUnicode))
-            xPath("/test/alpha/text()", byEquality)
-            xPath("/test/number/text()", byRegex(number))
-            xPath("/test/date/text()", byDate)
-            xPath("/test/dateTime/text()", byTimestamp)
-            xPath("/test/time/text()", byTime)
-            xPath("/test/*/complex/text()", byEquality)
-            xPath("/test/duck/@type", byEquality)
-        }
-    }
-}
-
-
-
-
-
-

The following example shows an automatically generated test for XML in the response body:

-
-
-
-
@Test
-public void validate_xmlMatches() throws Exception {
-    // given:
-    MockMvcRequestSpecification request = given()
-                .header("Content-Type", "application/xml");
-
-    // when:
-    ResponseOptions response = given().spec(request).get("/get");
-
-    // then:
-    assertThat(response.statusCode()).isEqualTo(200);
-    // and:
-    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
-                    .newDocumentBuilder();
-    Document parsedXml = documentBuilder.parse(new InputSource(
-                new StringReader(response.getBody().asString())));
-    // and:
-    assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
-    assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
-    assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
-    assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
-    assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
-    assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
-    assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
-    }
-
-
-
-
-

2.7. Multiple Contracts in One File

-
-

You can define multiple contracts in one file. Such a contract might resemble the -following example:

-
-
-
-
-
groovy
-
-
import org.springframework.cloud.contract.spec.Contract
-
-[
-    Contract.make {
-        name("should post a user")
-        request {
-            method 'POST'
-            url('/users/1')
-        }
-        response {
-            status OK()
-        }
-    },
-    Contract.make {
-        request {
-            method 'POST'
-            url('/users/2')
-        }
-        response {
-            status OK()
-        }
-    }
-]
-
-
-
-
yml
-
-
---
-name: should post a user
-request:
-  method: POST
-  url: /users/1
-response:
-  status: 200
----
-request:
-  method: POST
-  url: /users/2
-response:
-  status: 200
----
-request:
-  method: POST
-  url: /users/3
-response:
-  status: 200
-
-
-
-
java
-
-
class contract implements Supplier<Collection<Contract>> {
-
-    @Override
-    public Collection<Contract> get() {
-        return Arrays.asList(
-            Contract.make(c -> {
-                c.name("should post a user");
-                // ...
-            }), Contract.make(c -> {
-                // ...
-            }), Contract.make(c -> {
-                // ...
-            })
-        );
-    }
-
-}
-
-
-
-
kotlin
-
-
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
-
-arrayOf(
-    contract {
-        name("should post a user")
-        // ...
-    },
-    contract {
-        // ...
-    },
-    contract {
-        // ...
-    }
-}
-
-
-
-
-
-

In the preceding example, one contract has the name field and the other does not. This -leads to generation of two tests that look more or less like the following:

-
-
-
-
package org.springframework.cloud.contract.verifier.tests.com.hello;
-
-import com.example.TestBase;
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
-import com.jayway.restassured.response.ResponseOptions;
-import org.junit.Test;
-
-import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class V1Test extends TestBase {
-
-    @Test
-    public void validate_should_post_a_user() throws Exception {
-        // given:
-            MockMvcRequestSpecification request = given();
-
-        // when:
-            ResponseOptions response = given().spec(request)
-                    .post("/users/1");
-
-        // then:
-            assertThat(response.statusCode()).isEqualTo(200);
-    }
-
-    @Test
-    public void validate_withList_1() throws Exception {
-        // given:
-            MockMvcRequestSpecification request = given();
-
-        // when:
-            ResponseOptions response = given().spec(request)
-                    .post("/users/2");
-
-        // then:
-            assertThat(response.statusCode()).isEqualTo(200);
-    }
-
-}
-
-
-
-

Notice that, for the contract that has the name field, the generated test method is named -validate_should_post_a_user. The one that does not have the name field is called -validate_withList_1. It corresponds to the name of the file WithList.groovy and the -index of the contract in the list.

-
-
-

The generated stubs are shown in the following example:

-
-
-
-
-
-
should post a user.json
-1_WithList.json
-
-
-
-
-
-

The first file got the name parameter from the contract. The second -got the name of the contract file (WithList.groovy) prefixed with the index (in this -case, the contract had an index of 1 in the list of contracts in the file).

-
-
- - - - - -
- - -It is much better to name your contracts, because doing so makes -your tests far more meaningful. -
-
-
-
-

2.8. Stateful Contracts

-
-

Stateful contracts (known also as scenarios) are contract definitions that should be read -in order. This might be useful in the following situations:

-
-
-
    -
  • -

    You want to execute the contract in a precisely defined order, since you use Spring -Cloud Contract to test your stateful application

    -
  • -
-
-
- - - - - -
- - -We really discourage you from doing that, since contract tests should be stateless. -
-
-
-
    -
  • -

    You want the same endpoint to return different results for the same request.

    -
  • -
-
-
-

To create stateful contracts (or scenarios), you need to -use the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This works regardless -of whether you work with YAML or Groovy. The following listing shows an example:

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

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

-
-
-
    -
  1. -

    login, marked as Started pointing to…​

    -
  2. -
  3. -

    showCart, marked as Step1 pointing to…​

    -
  4. -
  5. -

    logout, marked as Step2 (which closes the scenario).

    -
  6. -
-
-
-

You can find more details about WireMock scenarios at -https://wiremock.org/docs/stateful-behaviour/.

-
-
-
-
-
-

3. Integrations

-
-
-

3.1. JAX-RS

-
-

The Spring Cloud Contract supports the JAX-RS 2 Client API. The base class needs -to define protected WebTarget webTarget and server initialization. The only option for -testing JAX-RS API is to start a web server. Also, a request with a body needs to have a -content type be set. Otherwise, the default of application/octet-stream gets used.

-
-
-

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

-
-
-
-
testMode = 'JAXRSCLIENT'
-
-
-
-

The following example shows a generated test API:

-
-
-
-
                    """\
-package com.example;
-
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import org.junit.Test;
-import org.junit.Rule;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Response;
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static javax.ws.rs.client.Entity.*;
-
-@SuppressWarnings("rawtypes")
-public class FooTest {
-\tWebTarget webTarget;
-
-\t@Test
-\tpublic void validate_() throws Exception {
-
-\t\t// when:
-\t\t\tResponse response = webTarget
-\t\t\t\t\t\t\t.path("/users")
-\t\t\t\t\t\t\t.queryParam("limit", "10")
-\t\t\t\t\t\t\t.queryParam("offset", "20")
-\t\t\t\t\t\t\t.queryParam("filter", "email")
-\t\t\t\t\t\t\t.queryParam("sort", "name")
-\t\t\t\t\t\t\t.queryParam("search", "55")
-\t\t\t\t\t\t\t.queryParam("age", "99")
-\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
-\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
-\t\t\t\t\t\t\t.request()
-\t\t\t\t\t\t\t.build("GET")
-\t\t\t\t\t\t\t.invoke();
-\t\t\tString responseAsString = response.readEntity(String.class);
-
-\t\t// then:
-\t\t\tassertThat(response.getStatus()).isEqualTo(200);
-
-\t\t// and:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
-\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
-\t}
-
-}
-
-"""
-
-
-
-
-

3.2. WebFlux with WebTestClient

-
-

You can work with WebFlux by using WebTestClient. The following listing shows how to -configure WebTestClient as the test mode:

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>WEBTESTCLIENT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-        testMode = 'WEBTESTCLIENT'
-}
-
-
-
-
-
-

The following example shows how to set up a WebTestClient base class and RestAssured -for WebFlux:

-
-
-
-
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
-import org.junit.Before;
-
-public abstract class BeerRestBase {
-
-    @Before
-    public void setup() {
-        RestAssuredWebTestClient.standaloneSetup(
-        new ProducerController(personToCheck -> personToCheck.age >= 20));
-    }
-}
-}
-
-
-
- - - - - -
- - -The WebTestClient mode is faster than the EXPLICIT mode. -
-
-
-
-

3.3. WebFlux with Explicit Mode

-
-

You can also use WebFlux with the explicit mode in your generated tests -to work with WebFlux. The following example shows how to configure using explicit mode:

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-        testMode = 'EXPLICIT'
-}
-
-
-
-
-
-

The following example shows how to set up a base class and RestAssured for Web Flux:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = BeerRestBase.Config.class,
-        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
-        properties = "server.port=0")
-public abstract class BeerRestBase {
-
-    // your tests go here
-
-    // in this config class you define all controllers and mocked services
-@Configuration
-@EnableAutoConfiguration
-static class Config {
-
-    @Bean
-    PersonCheckingService personCheckingService()  {
-        return personToCheck -> personToCheck.age >= 20;
-    }
-
-    @Bean
-    ProducerController producerController() {
-        return new ProducerController(personCheckingService());
-    }
-}
-
-}
-
-
-
-
-

3.4. Working with Context Paths

-
-

Spring Cloud Contract supports context paths.

-
-
- - - - - -
- - -
-

The only change needed to fully support context paths is the switch on the -producer side. Also, the autogenerated tests must use explicit mode. The consumer -side remains untouched. In order for the generated test to pass, you must use explicit -mode. The following example shows how to set the test mode to EXPLICIT:

-
-
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-        testMode = 'EXPLICIT'
-}
-
-
-
-
-
-
-
-

That way, you generate a test that does not use MockMvc. It means that you generate -real requests and you need to set up your generated test’s base class to work on a real -socket.

-
-
-

Consider the following contract:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method 'GET'
-        url '/my-context-path/url'
-    }
-    response {
-        status OK()
-    }
-}
-
-
-
-

The following example shows how to set up a base class and RestAssured:

-
-
-
-
import io.restassured.RestAssured;
-import org.junit.Before;
-import org.springframework.boot.web.server.LocalServerPort;
-import org.springframework.boot.test.context.SpringBootTest;
-
-@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-class ContextPathTestingBaseClass {
-
-    @LocalServerPort int port;
-
-    @Before
-    public void setup() {
-        RestAssured.baseURI = "http://localhost";
-        RestAssured.port = this.port;
-    }
-}
-
-
-
-

If you do it this way:

-
-
-
    -
  • -

    All of your requests in the autogenerated tests are sent to the real endpoint with your -context path included (for example, /my-context-path/url).

    -
  • -
  • -

    Your contracts reflect that you have a context path. Your generated stubs also have -that information (for example, in the stubs, you have to call /my-context-path/url).

    -
  • -
-
-
-
-

3.5. Working with REST Docs

-
-

You can use Spring REST Docs to generate -documentation (for example, in Asciidoc format) for an HTTP API with Spring MockMvc, -WebTestClient, or RestAssured. At the same time that you generate documentation for your API, you can also -generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your -normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be -automatically generated in the REST Docs output directory.

-
-
-
-rest docs -
-
-
-

The following example uses MockMvc:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureMockMvc
-public class ApplicationTests {
-
-    @Autowired
-    private MockMvc mockMvc;
-
-    @Test
-    public void contextLoads() throws Exception {
-        mockMvc.perform(get("/resource"))
-                .andExpect(content().string("Hello World"))
-                .andDo(document("resource"));
-    }
-}
-
-
-
-

This test generates a WireMock stub at target/snippets/stubs/resource.json. It matches -all GET requests to the /resource path. The same example with WebTestClient (used -for testing Spring WebFlux applications) would be as follows:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureWebTestClient
-public class ApplicationTests {
-
-    @Autowired
-    private WebTestClient client;
-
-    @Test
-    public void contextLoads() throws Exception {
-        client.get().uri("/resource").exchange()
-                .expectBody(String.class).isEqualTo("Hello World")
-                .consumeWith(document("resource"));
-    }
-}
-
-
-
-

Without any additional configuration, these tests create a stub with a request matcher -for the HTTP method and all headers except host and content-length. To match the -request more precisely (for example, to match the body of a POST or PUT), we need to -explicitly create a request matcher. Doing so has two effects:

-
-
-
    -
  • -

    Creating a stub that matches only in the way you specify.

    -
  • -
  • -

    Asserting that the request in the test case also matches the same conditions.

    -
  • -
-
-
-

The main entry point for this feature is WireMockRestDocs.verify(), which can be used -as a substitute for the document() convenience method, as the following -example shows:

-
-
-
-
-
-
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureMockMvc
-public class ApplicationTests {
-
-    @Autowired
-    private MockMvc mockMvc;
-
-    @Test
-    public void contextLoads() throws Exception {
-        mockMvc.perform(post("/resource")
-                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
-                .andExpect(status().isOk())
-                .andDo(verify().jsonPath("$.id")
-                .andDo(document("resource"));
-    }
-}
-
-
-
-
-
-

The preceding contract specifies that any valid POST with an id field receives the response -defined in this test. You can chain together calls to .jsonPath() to add additional -matchers. If JSON Path is unfamiliar, the JayWay -documentation can help you get up to speed. The WebTestClient version of this test -has a similar verify() static helper that you insert in the same place.

-
-
-

Instead of the jsonPath and contentType convenience methods, you can also use the -WireMock APIs to verify that the request matches the created stub, as the -following example shows:

-
-
-
-
@Test
-public void contextLoads() throws Exception {
-    mockMvc.perform(post("/resource")
-            .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
-            .andExpect(status().isOk())
-            .andDo(verify()
-                    .wiremock(WireMock.post(
-                        urlPathEquals("/resource"))
-                        .withRequestBody(matchingJsonPath("$.id"))
-                        .andDo(document("post-resource"));
-}
-
-
-
-

The WireMock API is rich. You can match headers, query parameters, and the request body by -regex as well as by JSON path. You can use these features to create stubs with a wider -range of parameters. The preceding example generates a stub resembling the following example:

-
-
-
post-resource.json
-
-
{
-  "request" : {
-    "url" : "/resource",
-    "method" : "POST",
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$.id"
-    }]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "Hello World",
-    "headers" : {
-      "X-Application-Context" : "application:-1",
-      "Content-Type" : "text/plain"
-    }
-  }
-}
-
-
-
- - - - - -
- - -You can use either the wiremock() method or the jsonPath() and contentType() -methods to create request matchers, but you cannot use both approaches. -
-
-
-

On the consumer side, you can make the resource.json generated earlier in this section -available on the classpath (by -Publishing Stubs as JARs, for example). After that, you can create a stub that uses WireMock in a -number of different ways, including by using -@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this -document.

-
-
-

3.5.1. Generating Contracts with REST Docs

-
-

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST -Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts -and the stubs.

-
-
-

Why would you want to use this feature? Some people in the community asked questions -about a situation in which they would like to move to DSL-based contract definition, -but they already have a lot of Spring MVC tests. Using this feature lets you generate -the contract files that you can later modify and move to folders (defined in your -configuration) so that the plugin finds them.

-
-
- - - - - -
- - -You might wonder why this functionality is in the WireMock module. The functionality -is there because it makes sense to generate both the contracts and the stubs. -
-
-
-

Consider the following test:

-
-
-
-
-
-
        this.mockMvc
-                .perform(post("/foo").accept(MediaType.APPLICATION_PDF)
-                        .accept(MediaType.APPLICATION_JSON)
-                        .contentType(MediaType.APPLICATION_JSON)
-                        .content("{\"foo\": 23, \"bar\" : \"baz\" }"))
-                .andExpect(status().isOk()).andExpect(content().string("bar"))
-                // first WireMock
-                .andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
-                        .jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
-                        .contentType(MediaType.valueOf("application/json")))
-                // then Contract DSL documentation
-                .andDo(document("index", SpringCloudContractRestDocs.dslContract()));
-
-
-
-
-
-

The preceding test creates the stub presented in the previous section, generating both -the contract and a documentation file.

-
-
-

The contract is called index.groovy and might resemble the following example:

-
-
-
-
-
-
import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-    request {
-        method 'POST'
-        url '/foo'
-        body('''
-            {"foo": 23 }
-        ''')
-        headers {
-            header('''Accept''', '''application/json''')
-            header('''Content-Type''', '''application/json''')
-        }
-    }
-    response {
-        status OK()
-        body('''
-        bar
-        ''')
-        headers {
-            header('''Content-Type''', '''application/json;charset=UTF-8''')
-            header('''Content-Length''', '''3''')
-        }
-        bodyMatchers {
-            jsonPath('$[?(@.foo >= 20)]', byType())
-        }
-    }
-}
-
-
-
-
-
-

The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be index/dsl-contract.adoc.

-
-
-
-
-
-
-

4. Messaging

-
-
-

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

-
-
-

4.1. Messaging DSL Top-Level Elements

-
-

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences:

-
- -
-

4.1.1. Output Triggered by a Method

-
-

The output message can be triggered by calling a method (such as a Scheduler when a contract was -started and a message was sent), as shown in the following example:

-
-
-
-
-
groovy
-
-
def dsl = Contract.make {
-    // Human readable description
-    description 'Some description'
-    // Label by means of which the output message can be triggered
-    label 'some_label'
-    // input to the contract
-    input {
-        // the contract will be triggered by a method
-        triggeredBy('bookReturnedTriggered()')
-    }
-    // output message of the contract
-    outputMessage {
-        // destination to which the output message will be sent
-        sentTo('output')
-        // the body of the output message
-        body('''{ "bookName" : "foo" }''')
-        // the headers of the output message
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
yml
-
-
# Human readable description
-description: Some description
-# Label by means of which the output message can be triggered
-label: some_label
-input:
-  # the contract will be triggered by a method
-  triggeredBy: bookReturnedTriggered()
-# output message of the contract
-outputMessage:
-  # destination to which the output message will be sent
-  sentTo: output
-  # the body of the output message
-  body:
-    bookName: foo
-  # the headers of the output message
-  headers:
-    BOOK-NAME: foo
-
-
-
-
-
-

In the previous example case, the output message is sent to output if a method called -bookReturnedTriggered is executed. On the message publisher’s side, we generate a -test that calls that method to trigger the message. On the consumer side, you can use -the some_label to trigger the message.

-
-
-
-

4.1.2. Output Triggered by a Message

-
-

The output message can be triggered by receiving a message, as shown in the following -example:

-
-
-
-
-
groovy
-
-
def dsl = Contract.make {
-    description 'Some Description'
-    label 'some_label'
-    // input is a message
-    input {
-        // the message was received from this destination
-        messageFrom('input')
-        // has the following body
-        messageBody([
-                bookName: 'foo'
-        ])
-        // and the following headers
-        messageHeaders {
-            header('sample', 'header')
-        }
-    }
-    outputMessage {
-        sentTo('output')
-        body([
-                bookName: 'foo'
-        ])
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
yml
-
-
# Human readable description
-description: Some description
-# Label by means of which the output message can be triggered
-label: some_label
-# input is a message
-input:
-  messageFrom: input
-  # has the following body
-  messageBody:
-    bookName: 'foo'
-  # and the following headers
-  messageHeaders:
-    sample: 'header'
-# output message of the contract
-outputMessage:
-  # destination to which the output message will be sent
-  sentTo: output
-  # the body of the output message
-  body:
-    bookName: foo
-  # the headers of the output message
-  headers:
-    BOOK-NAME: foo
-
-
-
-
-
-

In the preceding example, the output message is sent to output if a proper message is -received on the input destination. On the message publisher’s side, the engine -generates a test that sends the input message to the defined destination. On the -consumer side, you can either send a message to the input destination or use a label -(some_label in the example) to trigger the message.

-
-
-
-

4.1.3. Consumer/Producer

-
- - - - - -
- - -This section is valid only for Groovy DSL. -
-
-
-

In HTTP, you have a notion of client/stub and `server/test notation. You can also -use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also -provides the consumer and producer methods, as presented in the following example -(note that you can use either $ or value methods to provide consumer and producer -parts):

-
-
-
-
                    Contract.make {
-                name "foo"
-                        label 'some_label'
-                        input {
-                            messageFrom value(consumer('jms:output'), producer('jms:input'))
-                            messageBody([
-                                    bookName: 'foo'
-                            ])
-                            messageHeaders {
-                                header('sample', 'header')
-                            }
-                        }
-                        outputMessage {
-                            sentTo $(consumer('jms:input'), producer('jms:output'))
-                            body([
-                                    bookName: 'foo'
-                            ])
-                        }
-                    }
-
-
-
-
-

4.1.4. Common

-
-

In the input or outputMessage section, you can call assertThat with the name -of a method (for example, assertThatMessageIsOnTheQueue()) that you have defined in the -base class or in a static import. Spring Cloud Contract runs that method -in the generated test.

-
-
-
-
-

4.2. Integrations

-
-

You can use one of the following four integration configurations:

-
-
-
    -
  • -

    Apache Camel

    -
  • -
  • -

    Spring Integration

    -
  • -
  • -

    Spring Cloud Stream

    -
  • -
  • -

    Spring AMQP

    -
  • -
  • -

    Spring JMS (requires embedded broker)

    -
  • -
  • -

    Spring Kafka (requires embedded broker)

    -
  • -
-
-
-

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

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

If you want to use Spring Cloud Stream, remember to add a test dependency on -org.springframework.cloud:spring-cloud-stream, as follows:

-
-
-
-
-
Maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-stream</artifactId>
-    <type>test-jar</type>
-    <scope>test</scope>
-    <classifier>test-binder</classifier>
-</dependency>
-
-
-
-
Gradle
-
-
testImplementation(group: 'org.springframework.cloud', name: 'spring-cloud-stream', classifier: 'test-binder')
-
-
-
-
-
-
-
-

4.2.1. Manual Integration Testing

-
-

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

-
-
-

In a test, you can inject a ContractVerifierMessageExchange to send and receive -messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. -The following example shows how to do so:

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

4.3. Producer Side Messaging Test Generation

-
-

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

-
-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

    Scenario 2: The input message triggers an output message.

    -
  • -
  • -

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

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

4.3.1. Scenario 1: No Input Message

-
-

Consider the following contract:

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

For the preceding example, the following test would be created:

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

4.3.2. Scenario 2: Output Triggered by Input

-
-

Consider the following contract:

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

For the preceding contract, the following test would be created:

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

4.3.3. Scenario 3: No Output Message

-
-

Consider the following contract:

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

For the preceding contract, the following test would be created:

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

4.4. Consumer Stub Generation

-
-

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

-
-
- - - - - -
- - -If you have multiple frameworks on the classpath, Stub Runner needs to -define which one should be used. Assume that you have AMQP, Spring Cloud Stream, and Spring Integration -on the classpath and that you want to use Spring AMQP. Then you need to set -stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. -That way, the only remaining framework is Spring AMQP. -
-
-
-

4.4.1. Stub triggering

-
-

To trigger a message, use the StubTrigger interface, as the following example shows:

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

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

-
-
-

StubTrigger gives you the following options to trigger a message:

-
- -
-
-

4.4.2. Trigger by Label

-
-

The following example shows how to trigger a message with a label:

-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-

4.4.3. Trigger by Group and Artifact Ids

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

4.4.4. Trigger by Artifact IDs

-
-

The following example shows how to trigger a message from artifact IDs:

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

4.4.5. Trigger All Messages

-
-

The following example shows how to trigger all messages:

-
-
-
-
stubFinder.trigger()
-
-
-
-
-
-

4.5. Consumer Side Messaging With Apache Camel

-
-

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

-
-
-

4.5.1. Adding Apache Camel to the Project

-
-

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

-
-
-
-

4.5.2. Disabling the Functionality

-
-

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

-
-
-
-

4.5.3. Examples

-
-

Assume that we have the following Maven repository with deployed stubs for the -camelService application.

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

Further assume that the stubs contain the following structure:

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

Now consider the following contracts (we number them 1 and 2):

-
-
-
-
-
-
Contract.make {
-    label 'return_book_1'
-    input {
-        triggeredBy('bookReturnedTriggered()')
-    }
-    outputMessage {
-        sentTo('jms:output')
-        body('''{ "bookName" : "foo" }''')
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
Contract.make {
-    label 'return_book_2'
-    input {
-        messageFrom('jms:input')
-        messageBody([
-                bookName: 'foo'
-        ])
-        messageHeaders {
-            header('sample', 'header')
-        }
-    }
-    outputMessage {
-        sentTo('jms:output')
-        body([
-                bookName: 'foo'
-        ])
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
-
Scenario 1 (No Input Message)
-
-

To trigger a message from the return_book_1 label, we use the StubTrigger interface, as follows:

-
-
-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-
-

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

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

The received message would then pass the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
-receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 2 (Output Triggered by Input)
-
-

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

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

Next, we want to listen to the output of the message sent to jms:output, as follows:

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

The received message would pass the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
-receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 3 (Input with No Output)
-
-

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

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

4.6. Consumer Side Messaging with Spring Integration

-
-

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

-
-
-

4.6.1. Adding the Runner to the Project

-
-

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

-
-
-
-

4.6.2. Disabling the Functionality

-
-

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

-
-
-
-

4.6.3. Examples

-
-

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

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

Further assume the stubs contain the following structure:

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

Consider the following contracts (numbered 1 and 2):

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

Now consider the following Spring Integration Route:

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

These examples lend themselves to three scenarios:

-
- -
-
Scenario 1 (No Input Message)
-
-

To trigger a message from the return_book_1 label, use the StubTrigger interface, as -follows:

-
-
-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-
-

The following listing shows how to listen to the output of the message sent to jms:output:

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

The received message would pass the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 2 (Output Triggered by Input)
-
-

Since the route is set for you, you can send a message to the jms:output -destination, as follows:

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

The following listing shows how to listen to the output of the message sent to jms:output:

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

The received message passes the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 3 (Input with No Output)
-
-

Since the route is set for you, you can send a message to the jms:input destination, as follows:

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

4.7. Consumer Side Messaging With Spring Cloud Stream

-
-

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

-
-
- - - - - -
- - -If Stub Runner’s integration with the Stream messageFrom or sentTo strings -are resolved first as the destination of a channel and no such destination exists, the -destination is resolved as a channel name. -
-
-
- - - - - -
- - -
-

If you want to use Spring Cloud Stream, remember to add a dependency on -org.springframework.cloud:spring-cloud-stream test support, as follows:

-
-
-
-
-
Maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-stream</artifactId>
-    <type>test-jar</type>
-    <scope>test</scope>
-    <classifier>test-binder</classifier>
-</dependency>
-
-
-
-
Gradle
-
-
testImplementation(group: 'org.springframework.cloud', name: 'spring-cloud-stream', classifier: 'test-binder')
-
-
-
-
-
-
-
-

4.7.1. Adding the Runner to the Project

-
-

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

-
-
-
-

4.7.2. Disabling the Functionality

-
-

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

-
-
-
-

4.7.3. Examples

-
-

Assume that you have the following Maven repository with deployed stubs for the -streamService application:

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

Further assume the stubs contain the following structure:

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

Consider the following contracts (numbered 1 and 2):

-
-
-
-
-
-
Contract.make {
-    label 'return_book_1'
-    input { triggeredBy('bookReturnedTriggered()') }
-    outputMessage {
-        sentTo('returnBook')
-        body('''{ "bookName" : "foo" }''')
-        headers { header('BOOK-NAME', 'foo') }
-    }
-}
-
-
-
-
-
Contract.make {
-    label 'return_book_2'
-    input {
-        messageFrom('bookStorage')
-        messageBody([
-                bookName: 'foo'
-        ])
-        messageHeaders { header('sample', 'header') }
-    }
-    outputMessage {
-        sentTo('returnBook')
-        body([
-                bookName: 'foo'
-        ])
-        headers { header('BOOK-NAME', 'foo') }
-    }
-}
-
-
-
-
-
-

Now consider the following Spring configuration:

-
-
-
-
-
-
stubrunner.repositoryRoot: classpath:m2repo/repository/
-stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
-stubrunner.stubs-mode: remote
-spring:
-  cloud:
-    stream:
-      bindings:
-        output:
-          destination: returnBook
-        input:
-          destination: bookStorage
-
-server:
-  port: 0
-
-debug: true
-
-
-
-
-
-

These examples lend themselves to three scenarios:

-
- -
-
Scenario 1 (No Input Message)
-
-

To trigger a message from the return_book_1 label, use the StubTrigger interface as -follows:

-
-
-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-
-

The following example shows how to listen to the output of the message sent to a channel whose destination is -returnBook:

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

The received message passes the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 2 (Output Triggered by Input)
-
-

Since the route is set for you, you can send a message to the bookStorage -destination, as follows:

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

The following example shows how to listen to the output of the message sent to returnBook:

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

The received message passes the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 3 (Input with No Output)
-
-

Since the route is set for you, you can send a message to the jms:output -destination, as follows:

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

4.8. Consumer Side Messaging With Spring AMQP

-
-

Spring Cloud Contract Stub Runner’s messaging module provides an easy way to -integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it -automatically downloads the stubs and registers the required routes.

-
-
-

The integration tries to work standalone (that is, without interaction with a running -RabbitMQ message broker). It expects a RabbitTemplate on the application context and -uses it as a spring boot test named @SpyBean. As a result, it can use the Mockito spy -functionality to verify and inspect messages sent by the application.

-
-
-

On the message consumer side, the stub runner considers all @RabbitListener annotated -endpoints and all SimpleMessageListenerContainer objects on the application context.

-
-
-

As messages are usually sent to exchanges in AMQP, the message contract contains the -exchange name as the destination. Message listeners on the other side are bound to -queues. Bindings connect an exchange to a queue. If message contracts are triggered, the -Spring AMQP stub runner integration looks for bindings on the application context that -matches this exchange. Then it collects the queues from the Spring exchanges and tries to -find message listeners bound to these queues. The message is triggered for all matching -message listeners.

-
-
-

If you need to work with routing keys, you can pass them by using the amqp_receivedRoutingKey -messaging header.

-
-
-

4.8.1. Adding the Runner to the Project

-
-

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and -set the property stubrunner.amqp.enabled=true. Remember to annotate your test class -with @AutoConfigureStubRunner.

-
-
- - - - - -
- - -If you already have Stream and Integration on the classpath, you need -to disable them explicitly by setting the stubrunner.stream.enabled=false and -stubrunner.integration.enabled=false properties. -
-
-
-
-

4.8.2. Examples

-
-

Assume that you have the following Maven repository with a deployed stubs for the -spring-cloud-contract-amqp-test application:

-
-
-
-
-
-
└── .m2
-    └── repository
-        └── com
-            └── example
-                └── spring-cloud-contract-amqp-test
-                    ├── 0.4.0-SNAPSHOT
-                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
-                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
-                    │   └── maven-metadata-local.xml
-                    └── maven-metadata-local.xml
-
-
-
-
-
-

Further assume that the stubs contain the following structure:

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

Then consider the following contract:

-
-
-
-
-
-
Contract.make {
-    // Human readable description
-    description 'Should produce valid person data'
-    // Label by means of which the output message can be triggered
-    label 'contract-test.person.created.event'
-    // input to the contract
-    input {
-        // the contract will be triggered by a method
-        triggeredBy('createPerson()')
-    }
-    // output message of the contract
-    outputMessage {
-        // destination to which the output message will be sent
-        sentTo 'contract-test.exchange'
-        headers {
-            header('contentType': 'application/json')
-            header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
-        }
-        // the body of the output message
-        body([
-                id  : $(consumer(9), producer(regex("[0-9]+"))),
-                name: "me"
-        ])
-    }
-}
-
-
-
-
-
-

Now consider the following Spring configuration:

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

To trigger a message using the contract in the preceding section, use the StubTrigger interface as -follows:

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

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner -integration looks for bindings related to this exchange, as the following example shows:

-
-
-
-
-
-
@Bean
-public Binding binding() {
-    return BindingBuilder.bind(new Queue("test.queue"))
-            .to(new DirectExchange("contract-test.exchange")).with("#");
-}
-
-
-
-
-
-

The binding definition binds the queue called test.queue. As a result, the following listener -definition is matched and invoked with the contract message:

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

Also, the following annotated listener matches and is invoked:

-
-
-
-
-
-
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
-        exchange = @Exchange(value = "contract-test.exchange",
-                ignoreDeclarationExceptions = "true")))
-public void handlePerson(Person person) {
-    this.person = person;
-}
-
-
-
-
-
- - - - - -
- - -The message is directly handed over to the onMessage method of the -MessageListener associated with the matching SimpleMessageListenerContainer. -
-
-
-
-
Spring AMQP Test Configuration
-
-

In order to avoid Spring AMQP trying to connect to a running broker during our tests, we -configure a mock ConnectionFactory.

-
-
-

To disable the mocked ConnectionFactory, set the following property: -stubrunner.amqp.mockConnection=false, as follows:

-
-
-
-
-
-
stubrunner:
-  amqp:
-    mockConnection: false
-
-
-
-
-
-
-
-
-

4.9. Consumer Side Messaging With Spring JMS

-
-

Spring Cloud Contract Stub Runner’s messaging module provides an easy way to -integrate with Spring JMS.

-
-
-

The integration assumes that you have a running instance of a JMS broker (e.g. activemq embedded broker).

-
-
-

4.9.1. Adding the Runner to the Project

-
-

You need to have both Spring JMS and Spring Cloud Contract Stub Runner on the classpath. Remember to annotate your test class -with @AutoConfigureStubRunner.

-
-
-
-

4.9.2. Examples

-
-

Assume that the stub structure looks as follows:

-
-
-
-
-
-
├── stubs
-    ├── bookDeleted.groovy
-    ├── bookReturned1.groovy
-    └── bookReturned2.groovy
-
-
-
-
-
-

Further assume the following test configuration:

-
-
-
-
-
-
stubrunner:
-  repository-root: stubs:classpath:/stubs/
-  ids: my:stubs
-  stubs-mode: remote
-spring:
-  activemq:
-    send-timeout: 1000
-  jms:
-    template:
-      receive-timeout: 1000
-
-
-
-
-
-

Now consider the following contracts (we number them 1 and 2):

-
-
-
-
-
-
Contract.make {
-    label 'return_book_1'
-    input {
-        triggeredBy('bookReturnedTriggered()')
-    }
-    outputMessage {
-        sentTo('output')
-        body('''{ "bookName" : "foo" }''')
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
Contract.make {
-    label 'return_book_2'
-    input {
-        messageFrom('input')
-        messageBody([
-                bookName: 'foo'
-        ])
-        messageHeaders {
-            header('sample', 'header')
-        }
-    }
-    outputMessage {
-        sentTo('output')
-        body([
-                bookName: 'foo'
-        ])
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
-
Scenario 1 (No Input Message)
-
-

To trigger a message from the return_book_1 label, we use the StubTrigger interface, as follows:

-
-
-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-
-

Next, we want to listen to the output of the message sent to output:

-
-
-
-
-
-
TextMessage receivedMessage = (TextMessage) jmsTemplate.receive('output')
-
-
-
-
-
-

The received message would then pass the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.getText())
-receivedMessage.getStringProperty('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 2 (Output Triggered by Input)
-
-

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

-
-
-
-
-
-
jmsTemplate.
-        convertAndSend('input', new BookReturned('foo'), new MessagePostProcessor() {
-            @Override
-            Message postProcessMessage(Message message) throws JMSException {
-                message.setStringProperty("sample", "header")
-                return message
-            }
-        })
-
-
-
-
-
-

Next, we want to listen to the output of the message sent to output, as follows:

-
-
-
-
-
-
TextMessage receivedMessage = (TextMessage) jmsTemplate.receive('output')
-
-
-
-
-
-

The received message would pass the following assertions:

-
-
-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.getText())
-receivedMessage.getStringProperty('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 3 (Input with No Output)
-
-

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

-
-
-
-
-
-
jmsTemplate.
-        convertAndSend('delete', new BookReturned('foo'), new MessagePostProcessor() {
-            @Override
-            Message postProcessMessage(Message message) throws JMSException {
-                message.setStringProperty("sample", "header")
-                return message
-            }
-        })
-
-
-
-
-
-
-
-
-

4.10. Consumer Side Messaging With Spring Kafka

-
-

Spring Cloud Contract Stub Runner’s messaging module provides an easy way to -integrate with Spring Kafka.

-
-
-

The integration assumes that you have a running instance of a embedded Kafka broker (via the spring-kafka-test dependency).

-
-
-

4.10.1. Adding the Runner to the Project

-
-

You need to have both Spring Kafka, Spring Kafka Test (to run the @EmbeddedBroker) and Spring Cloud Contract Stub Runner on the classpath. Remember to annotate your test class -with @AutoConfigureStubRunner.

-
-
-

With Kafka integration, in order to poll for a single message we need to register a consumer upon Spring context startup. That may lead to a situation that, when you’re on the consumer side, Stub Runner can register an additional consumer for the same group id and topic. That could lead to a situation that only one of the components would actually poll for the message. Since on the consumer side you have both the Spring Cloud Contract Stub Runner and Spring Cloud Contract Verifier classpath, we need to be able to switch off such behaviour. That’s done automatically via the stubrunner.kafka.initializer.enabled flag, that will disable the Contact Verifier consumer registration. If your application is both the consumer and the producer of a kafka message, you might need to manually toggle that property to false in the base class of your generated tests.

-
-
-
-

4.10.2. Examples

-
-

Assume that the stub structure looks as follows:

-
-
-
-
-
-
├── stubs
-    ├── bookDeleted.groovy
-    ├── bookReturned1.groovy
-    └── bookReturned2.groovy
-
-
-
-
-
-

Further assume the following test configuration (notice the spring.kafka.bootstrap-servers pointing to the embedded broker’s IP via ${spring.embedded.kafka.brokers}):

-
-
-
-
-
-
stubrunner:
-  repository-root: stubs:classpath:/stubs/
-  ids: my:stubs
-  stubs-mode: remote
-spring:
-  kafka:
-    bootstrap-servers: ${spring.embedded.kafka.brokers}
-    producer:
-      properties:
-        "value.serializer": "org.springframework.kafka.support.serializer.JsonSerializer"
-        "spring.json.trusted.packages": "*"
-    consumer:
-      properties:
-        "value.deserializer": "org.springframework.kafka.support.serializer.JsonDeserializer"
-        "value.serializer": "org.springframework.kafka.support.serializer.JsonSerializer"
-        "spring.json.trusted.packages": "*"
-      group-id: groupId
-
-
-
-
-
-

Now consider the following contracts (we number them 1 and 2):

-
-
-
-
-
-
Contract.make {
-    label 'return_book_1'
-    input {
-        triggeredBy('bookReturnedTriggered()')
-    }
-    outputMessage {
-        sentTo('output')
-        body('''{ "bookName" : "foo" }''')
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
Contract.make {
-    label 'return_book_2'
-    input {
-        messageFrom('input')
-        messageBody([
-                bookName: 'foo'
-        ])
-        messageHeaders {
-            header('sample', 'header')
-        }
-    }
-    outputMessage {
-        sentTo('output')
-        body([
-                bookName: 'foo'
-        ])
-        headers {
-            header('BOOK-NAME', 'foo')
-        }
-    }
-}
-
-
-
-
-
-
Scenario 1 (No Input Message)
-
-

To trigger a message from the return_book_1 label, we use the StubTrigger interface, as follows:

-
-
-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-
-

Next, we want to listen to the output of the message sent to output:

-
-
-
-
-
-
Message receivedMessage = receiveFromOutput()
-
-
-
-
-
-

The received message would then pass the following assertions:

-
-
-
-
-
-
assert receivedMessage != null
-assert assertThatBodyContainsBookNameFoo(receivedMessage.getPayload())
-assert receivedMessage.getHeaders().get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 2 (Output Triggered by Input)
-
-

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

-
-
-
-
-
-
Message message = MessageBuilder.createMessage(new BookReturned('foo'), new MessageHeaders([sample: "header",]))
-kafkaTemplate.setDefaultTopic('input')
-kafkaTemplate.send(message)
-
-
-
-
-
-

Next, we want to listen to the output of the message sent to output, as follows:

-
-
-
-
-
-
Message receivedMessage = receiveFromOutput()
-
-
-
-
-
-

The received message would pass the following assertions:

-
-
-
-
-
-
assert receivedMessage != null
-assert assertThatBodyContainsBookNameFoo(receivedMessage.getPayload())
-assert receivedMessage.getHeaders().get('BOOK-NAME') == 'foo'
-
-
-
-
-
-
-
Scenario 3 (Input with No Output)
-
-

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

-
-
-
-
-
-
Message message = MessageBuilder.createMessage(new BookReturned('foo'), new MessageHeaders([sample: "header",]))
-kafkaTemplate.setDefaultTopic('delete')
-kafkaTemplate.send(message)
-
-
-
-
-
-
-
-
-
-
-

5. Spring Cloud Contract Stub Runner

-
-
-

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

-
-
-

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

-
-
-

5.1. Snapshot Versions

-
-

You can add the additional snapshot repository to your build.gradle file to use snapshot -versions, which are automatically uploaded after every successful build, as follows:

-
-
-
-
-
Maven
-
-
<repositories>
-    <repository>
-        <id>spring-snapshots</id>
-        <name>Spring Snapshots</name>
-        <url>https://repo.spring.io/snapshot</url>
-        <snapshots>
-            <enabled>true</enabled>
-        </snapshots>
-    </repository>
-    <repository>
-        <id>spring-milestones</id>
-        <name>Spring Milestones</name>
-        <url>https://repo.spring.io/milestone</url>
-        <snapshots>
-            <enabled>false</enabled>
-        </snapshots>
-    </repository>
-    <repository>
-        <id>spring-releases</id>
-        <name>Spring Releases</name>
-        <url>https://repo.spring.io/release</url>
-        <snapshots>
-            <enabled>false</enabled>
-        </snapshots>
-    </repository>
-</repositories>
-<pluginRepositories>
-    <pluginRepository>
-        <id>spring-snapshots</id>
-        <name>Spring Snapshots</name>
-        <url>https://repo.spring.io/snapshot</url>
-        <snapshots>
-            <enabled>true</enabled>
-        </snapshots>
-    </pluginRepository>
-    <pluginRepository>
-        <id>spring-milestones</id>
-        <name>Spring Milestones</name>
-        <url>https://repo.spring.io/milestone</url>
-        <snapshots>
-            <enabled>false</enabled>
-        </snapshots>
-    </pluginRepository>
-    <pluginRepository>
-        <id>spring-releases</id>
-        <name>Spring Releases</name>
-        <url>https://repo.spring.io/release</url>
-        <snapshots>
-            <enabled>false</enabled>
-        </snapshots>
-    </pluginRepository>
-</pluginRepositories>
-
-
-
-
Gradle
-
-
/*
- We need to use the [buildscript {}] section when we have to modify
- the classpath for the plugins. If that's not the case this section
- can be skipped.
-
- If you don't need to modify the classpath (e.g. add a Pact dependency),
- then you can just set the [pluginManagement {}] section in [settings.gradle] file.
-
- // settings.gradle
- pluginManagement {
-    repositories {
-        // for snapshots
-        maven {url "https://repo.spring.io/snapshot"}
-        // for milestones
-        maven {url "https://repo.spring.io/milestone"}
-        // for GA versions
-        gradlePluginPortal()
-    }
- }
-
- */
-buildscript {
-    repositories {
-        mavenCentral()
-        mavenLocal()
-        maven { url "https://repo.spring.io/snapshot" }
-        maven { url "https://repo.spring.io/milestone" }
-        maven { url "https://repo.spring.io/release" }
-    }
-
-
-
-
-
-
-

5.2. Publishing Stubs as JARs

-
-

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

-
-
- - - - - -
- - -For both Maven and Gradle, the setup comes ready to work. However, you can customize -it if you want to. -
-
-
-

The following example shows how to publish stubs as jars:

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

5.3. Stub Runner Core

-
-

The stub runner core runs stubs for service collaborators. Treating stubs as contracts of -services lets you use stub-runner as an implementation of -Consumer-driven Contracts.

-
-
-

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

-
-
-

5.3.1. Retrieving stubs

-
-

You can pick from the following options of acquiring stubs:

-
-
-
    -
  • -

    Aether-based solution that downloads JARs with stubs from Artifactory or Nexus

    -
  • -
  • -

    Classpath-scanning solution that searches the classpath with a pattern to retrieve stubs

    -
  • -
  • -

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

    -
  • -
-
-
-

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

-
-
-
Downloading Stubs
-
-

You can control the downloading of stubs with the stubsMode switch. It picks value from the -StubRunnerProperties.StubsMode enumeration. You can use the following options:

-
-
-
    -
  • -

    StubRunnerProperties.StubsMode.CLASSPATH (default value): Picks stubs from the classpath

    -
  • -
  • -

    StubRunnerProperties.StubsMode.LOCAL: Picks stubs from a local storage (for example, .m2)

    -
  • -
  • -

    StubRunnerProperties.StubsMode.REMOTE: Picks stubs from a remote location

    -
  • -
-
-
-

The following example picks stubs from a local location:

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

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH -(or set nothing since CLASSPATH is the default value), the classpath is scanned. -Consider the following example:

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

You can add the dependencies to your classpath, as follows:

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

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

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

For com.example.thing1:thing2, the following locations are scanned:

-
-
-
    -
  • -

    /META-INF/com.example.thing1/thing2/*/.*

    -
  • -
  • -

    /contracts/com.example.thing1/thing2/*/.*

    -
  • -
  • -

    /mappings/com.example.thing1/thing2/*/.*

    -
  • -
-
-
- - - - - -
- - -You have to explicitly provide the group and artifact IDs when you package the -producer stubs. -
-
-
-

To achieve proper stub packaging, the producer would set up the contracts as follows:

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

By using the Maven assembly plugin or -Gradle Jar task, you have to create the following -structure in your stubs jar:

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

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

-
-
-
-
Configuring HTTP Server Stubs
-
-

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

-
-
-

Spring Cloud Contract Stub Runner comes with an implementation that you -can extend for WireMock: -org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. -In the configure method, -you can provide your own custom configuration for the given stub. The use -case might be starting WireMock for the given artifact ID, on an HTTPS port. The following -example shows how to do so:

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

You can then reuse it with the @AutoConfigureStubRunner annotation, as follows:

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

Whenever an HTTPS port is found, it takes precedence over the HTTP port.

-
-
-
-
-

5.3.2. Running stubs

-
-

This section describes how to run stubs. It contains the following topics:

-
- -
-
HTTP Stubs
-
-

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

-
-
-

The following example defines a stub in JSON:

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

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

-
-
-

You can also use the mappingsOutputFolder property to dump the mappings to files. -For the annotation-based approach, it would resembling the following example:

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

For the JUnit approach, it resembles the following example:

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

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

-
-
-
-
-
-
.
-├── fraudDetectionServer_13705
-└── loanIssuance_12255
-
-
-
-
-
-

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

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

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

-
-
-
-
-
-

5.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

-
-

Stub Runner comes with a JUnit rule that lets you can download and run stubs for a given -group and artifact ID, as the following example shows:

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

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

-
-
-
    -
  • -

    Download them

    -
  • -
  • -

    Cache them locally

    -
  • -
  • -

    Unzip them to a temporary folder

    -
  • -
  • -

    Start a WireMock server for each Maven dependency on a random port from the provided -range of ports or the provided port

    -
  • -
  • -

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

    -
  • -
  • -

    Send messages (remember to pass an implementation of MessageVerifier interface)

    -
  • -
-
-
-

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

-
-
-

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they let -you find the started stubs, as the following example shows:

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

The following examples provide more detail about using Stub Runner:

-
-
-
-
-
spock
-
-
@ClassRule
-@Shared
-StubRunnerRule rule = new StubRunnerRule()
-        .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-        .repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
-        .downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
-        .downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
-        .withMappingsOutputFolder("target/outputmappingsforrule")
-
-
-def 'should start WireMock servers'() {
-    expect: 'WireMocks are running'
-        rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
-        rule.findStubUrl('loanIssuance') != null
-        rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
-        rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
-    and:
-        rule.findAllRunningStubs().isPresent('loanIssuance')
-        rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
-        rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
-    and: 'Stubs were registered'
-        "${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
-        "${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
-}
-
-def 'should output mappings to output folder'() {
-    when:
-        def url = rule.findStubUrl('fraudDetectionServer')
-    then:
-        new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
-}
-
-
-
-
junit 4
-
-
@Test
-public void should_start_wiremock_servers() throws Exception {
-    // expect: 'WireMocks are running'
-    then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
-            "loanIssuance")).isNotNull();
-    then(rule.findStubUrl("loanIssuance")).isNotNull();
-    then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
-            "org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
-    then(rule.findStubUrl(
-            "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
-                    .isNotNull();
-    // and:
-    then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
-    then(rule.findAllRunningStubs().isPresent(
-            "org.springframework.cloud.contract.verifier.stubs",
-            "fraudDetectionServer")).isTrue();
-    then(rule.findAllRunningStubs().isPresent(
-            "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
-                    .isTrue();
-    // and: 'Stubs were registered'
-    then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
-            .isEqualTo("loanIssuance");
-    then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
-            .isEqualTo("fraudDetectionServer");
-}
-
-
-
-
junit 5
-
-
// Visible for Junit
-@RegisterExtension
-static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-        .repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-        .downloadStub("org.springframework.cloud.contract.verifier.stubs",
-                "loanIssuance")
-        .downloadStub(
-                "org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
-        .withMappingsOutputFolder("target/outputmappingsforrule");
-
-@BeforeAll
-@AfterAll
-static void setupProps() {
-    System.clearProperty("stubrunner.repository.root");
-    System.clearProperty("stubrunner.classifier");
-}
-
-private static String repoRoot() {
-    try {
-        return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
-                .toURI().toString();
-    }
-    catch (Exception e) {
-        return "";
-    }
-}
-
-
-
-
-
-

See the Common Properties for JUnit and Spring for more information on -how to apply global configuration of Stub Runner.

-
-
- - - - - -
- - -To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the -MessageVerifier interface to the rule builder (for example, rule.messageVerifier(new MyMessageVerifier())). -If you do not do this, then, whenever you try to send a message, an exception is thrown. -
-
-
-

5.4.1. Maven Settings

-
-

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

-
-
-
-

5.4.2. Providing Fixed Ports

-
-

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

-
-
-
-

5.4.3. Fluent API

-
-

When using the StubRunnerRule or StubRunnerExtension, you can add a stub to download -and then pass the port for the last downloaded stub. The following example shows how to do so:

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

For the preceding 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());
-
-
-
-
-
-
-

5.4.4. Stub Runner with Spring

-
-

Stub Runner with Spring sets up Spring configuration of the Stub Runner project.

-
-
-

By providing a list of stubs inside your configuration file, 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 follows:

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

Doing so depends on the following configuration file:

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

Instead of using the properties, you can also use the properties inside the @AutoConfigureStubRunner. -The following example achieves the same result by setting values on the annotation:

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

Stub Runner Spring registers environment variables in the following manner -for every registered WireMock server. The following example shows Stub Runner IDs for -com.example:thing1 and com.example:thing2:

-
-
-
    -
  • -

    stubrunner.runningstubs.thing1.port

    -
  • -
  • -

    stubrunner.runningstubs.com.example.thing1.port

    -
  • -
  • -

    stubrunner.runningstubs.thing2.port

    -
  • -
  • -

    stubrunner.runningstubs.com.example.thing2.port

    -
  • -
-
-
-

You can reference these values in your code.

-
-
-

You can also use the @StubRunnerPort annotation to inject the port of a running stub. -The value of the annotation can be the groupid:artifactid or just the artifactid. -The following example works shows Stub Runner IDs for -com.example:thing1 and com.example:thing2.

-
-
-
-
-
-
@StubRunnerPort("thing1")
-int thing1Port;
-@StubRunnerPort("com.example:thing2")
-int thing2Port;
-
-
-
-
-
-
-
-

5.5. Stub Runner Spring Cloud

-
-

Stub Runner can integrate with Spring Cloud.

-
-
-

For real life examples, see:

-
- -
-

5.5.1. Stubbing Service Discovery

-
-

The most important feature of Stub Runner Spring Cloud is the fact that it stubs:

-
-
-
    -
  • -

    DiscoveryClient

    -
  • -
  • -

    Ribbon ServerList

    -
  • -
-
-
-

That means that, regardless of whether you use Zookeeper, Consul, Eureka, or anything -else, you do not need that in your tests. We are starting WireMock instances of your -dependencies and we are telling your application, whenever you use Feign, to load a -balanced RestTemplate or DiscoveryClient directly, to call those stubbed servers -instead of calling the real Service Discovery tool.

-
-
-

For example, the following test passes:

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

Note that the preceding example requires the following configuration file:

-
-
-
-
-
-
stubrunner:
-  idsToServiceIds:
-    ivyNotation: someValueInsideYourCode
-    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer
-
-
-
-
-
-
Test Profiles and Service Discovery
-
-

In your integration tests, you typically do not want to call either a discovery service (such as Eureka) -or Config Server. That is why you create an additional test configuration in which you want to disable -these features.

-
-
-

Due to certain limitations of spring-cloud-commons, -to achieve this, you have to disable these properties -in a static block such as the following example (for Eureka):

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

5.5.2. Additional Configuration

-
-

You can match the artifactId of the stub with the name of your application by using the stubrunner.idsToServiceIds: map. -You can disable Stub Runner Ribbon support by setting stubrunner.cloud.ribbon.enabled to false -You can disable Stub Runner support by setting stubrunner.cloud.enabled to false

-
-
- - - - - -
- - -By default, all service discovery is stubbed. This means that, regardless of whether you have -an existing DiscoveryClient, its results are ignored. However, if you want to reuse it, you can set - stubrunner.cloud.delegate.enabled to true, and then your existing DiscoveryClient results are - merged with the stubbed ones. -
-
-
-

The default Maven configuration used by Stub Runner can be tweaked either -by setting the following system properties or by setting the corresponding environment variables:

-
-
-
    -
  • -

    maven.repo.local: Path to the custom maven local repository location

    -
  • -
  • -

    org.apache.maven.user-settings: Path to custom maven user settings location

    -
  • -
  • -

    org.apache.maven.global-settings: Path to maven global settings location

    -
  • -
-
-
-
-
-

5.6. Using the Stub Runner Boot Application

-
-

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

-
-
-

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

-
-
-

5.6.1. Stub Runner Server

-
-

To use the Stub Runner Server, add the following dependency:

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

Then annotate a class with @EnableStubRunnerServer, build a fat jar, and it is ready to work.

-
-
-

For the properties, see the Stub Runner Spring section.

-
-
-
-

5.6.2. Stub Runner Server Fat Jar

-
-

You can download a standalone JAR from Maven (for example, for version 2.0.1.RELEASE) -by running the following commands:

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

5.6.3. Spring Cloud CLI

-
-

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

-
-
-

In order to pass the configuration, you can create a stubrunner.yml file in the current working directory, -in a subdirectory called config, or in ~/.spring-cloud. The file could resemble the following -example for running stubs installed locally:

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

Then you can call spring cloud stubrunner from your terminal window to start -the Stub Runner server. It is available at port 8750.

-
-
-
-

5.6.4. Endpoints

-
-

Stub Runner Boot offers two endpoints:

-
-
- -
-
-
HTTP
-
-

For HTTP, Stub Runner Boot makes the following endpoints available:

-
-
-
    -
  • -

    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, Stub Runner Boot makes the following endpoints available:

-
-
-
    -
  • -

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

    -
  • -
  • -

    POST /triggers/{label}: Runs a trigger with label

    -
  • -
  • -

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

    -
  • -
-
-
-
-
-

5.6.5. Example

-
-

The following example shows typical usage of Stub Runner Boot:

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

5.6.6. Stub Runner Boot with Service Discovery

-
-

One way to use Stub Runner Boot is to use it as a feed of stubs for “smoke tests”. What does that mean? -Assume that you do not want to deploy 50 microservices to a test environment in order -to see whether your application works. You have already executed a suite of tests during the build process, -but you would also like to ensure that the packaging of your application works. You can -deploy your application to an environment, start it, and run a couple of tests on it to see whether -it works. We can call those tests “smoke tests”, because their purpose is to check only a handful -of testing scenarios.

-
-
-

The problem with this approach is thatm if you use microservices, you most likely also -use a service discovery tool. Stub Runner Boot lets you solve this issue by starting the -required stubs and registering them in a service discovery tool. Consider the following example of -such a setup with Eureka (assume that Eureka is already running):

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

We want to start a Stub Runner Boot server (@EnableStubRunnerServer), enable the Eureka client (@EnableEurekaClient), -and have the stub runner feature turned on (@AutoConfigureStubRunner).

-
-
-

Now assume that we want to start this application so that the stubs get automatically registered. -We can do so by running the application with java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar, where -${SYSTEM_PROPS} contains the following list of properties:

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

That way, your deployed application can send requests to started WireMock servers through service -discovery. Most likely, points 1 through 3 could be set by default in application.yml, because 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.

-
-
-
-
-

5.7. Consumer-Driven Contracts: Stubs Per Consumer

-
-

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

-
-
- - - - - -
- - -This approach also lets you immediately know which consumer uses which part of your API. -You can remove part of a response that your API produces and see which of your autogenerated tests -fails. If none fails, you can safely delete that part of the response, because nobody uses it. -
-
-
-

Consider the following example of a contract defined for the producer called producer, -which has two consumers (foo-consumer and bar-consumer):

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

You cannot produce two different responses for the same request. That is why you can properly package the -contracts and then profit from the stubsPerConsumer feature.

-
-
-

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

-
-
-

On the foo producer side the contracts would look like this

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

The bar-consumer consumer can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer -Alternatively, you can set the test as follows:

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

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

-
-
-

You can also set the consumer name explicitly, as follows:

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

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

-
-
-

See issue 224 for more -information about the reasons behind this change.

-
-
-
-

5.8. Fetching Stubs or Contract Definitions From A Location

-
-

Instead of picking the stubs or contract definitions from -Artifactory / Nexus or Git, one can just want to point to -a location on drive or classpath. This can be especially useful in a multimodule project, where one module wants -to reuse stubs or contracts from another module without -the need to actually install those in a local maven -repository ot commit those changes to Git.

-
-
-

In order to achieve this it’s enough to use the stubs:// -protocol when the repository root parameter is set either -in Stub Runner or in a Spring Cloud Contract plugin.

-
-
-

In this example the producer project has been successfully -built and stubs were generated under the target/stubs folder. As a consumer one can setup the Stub Runner to pick the stubs from that location using the stubs:// protocol.

-
-
-
-
-
Annotation
-
-
@AutoConfigureStubRunner(
-stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-        repositoryRoot = "stubs://file://location/to/the/producer/target/stubs/",
-        ids = "com.example:some-producer")
-
-
-
-
JUnit 4 Rule
-
-
@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/producer/target/stubs/")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
JUnit 5 Extension
-
-
@RegisterExtension
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/producer/target/stubs/")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
-
-

Contracts and stubs may be stored in a location, where each producer has its own, dedicated folder for contracts and stub mappings. Under that folder each consumer can have its own setup. To make Stub Runner find the dedicated folder from the provided ids one can pass a property stubs.find-producer=true or a system property stubrunner.stubs.find-producer=true .

-
-
-
-
└── com.example (1)
-    ├── some-artifact-id (2)
-    │   └── 0.0.1
-    │       ├── contracts (3)
-    │       │   └── shouldReturnStuffForArtifactId.groovy
-    │       └── mappings (4)
-    │           └── shouldReturnStuffForArtifactId.json
-    └── some-other-artifact-id (5)
-        ├── contracts
-        │   └── shouldReturnStuffForOtherArtifactId.groovy
-        └── mappings
-            └── shouldReturnStuffForOtherArtifactId.json
-
-
-
- - - - - - - - - - - - - - - - - - - - - -
1group id of the consumers
2consumer with artifact id [some-artifact-id]
3contracts for the consumer with artifact id [some-artifact-id]
4mappings for the consumer with artifact id [some-artifact-id]
5consumer with artifact id [some-other-artifact-id]
-
-
-
-
-
Annotation
-
-
@AutoConfigureStubRunner(
-stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-        repositoryRoot = "stubs://file://location/to/the/contracts/directory",
-        ids = "com.example:some-producer",
-        properties="stubs.find-producer=true")
-
-
-
-
JUnit 4 Rule
-
-
    static Map<String, String> contractProperties() {
-        Map<String, String> map = new HashMap<>();
-        map.put("stubs.find-producer", "true");
-        return map;
-    }
-
-@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts/directory")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .properties(contractProperties());
-
-
-
-
JUnit 5 Extension
-
-
    static Map<String, String> contractProperties() {
-        Map<String, String> map = new HashMap<>();
-        map.put("stubs.find-producer", "true");
-        return map;
-    }
-
-@RegisterExtension
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts/directory")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .properties(contractProperties());
-
-
-
-
-
-
-

5.9. Generating Stubs at Runtime

-
-

As a consumer, you might not want to wait for the producer to finish its implementation and then publish their stubs. A solution to this problem can be generation of stubs at runtime.

-
-
-

As a producer, when a contract is defined, you are required to make the generated tests pass in order for the stubs to be published. There are cases where you would like to unblock the consumers so that they can fetch the stubs before your tests are actually passing. In this case you should set such contracts as in progress. You can read more about this under the Contracts in Progress section. That way your tests will not be generated, but the stubs will.

-
-
-

As a consumer, you can toggle a switch to generate stubs at runtime. Stub Runner will ignore all the existing stub mappings and will generate new ones for all the contract definitions. Another option is to pass the stubrunner.generate-stubs system property. Below you can find an example of such setup.

-
-
-
-
-
Annotation
-
-
@AutoConfigureStubRunner(
-stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-        repositoryRoot = "stubs://file://location/to/the/contracts",
-        ids = "com.example:some-producer",
-        generateStubs = true)
-
-
-
-
JUnit 4 Rule
-
-
@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .withGenerateStubs(true);
-
-
-
-
JUnit 5 Extension
-
-
@RegisterExtension
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .withGenerateStubs(true);
-
-
-
-
-
-
-

5.10. Fail On No Stubs

-
-

By default Stub Runner will fail if no stubs were found. In order to change that behaviour, just set to false the failOnNoStubs property in the annotation or call the withFailOnNoStubs(false) method on a JUnit Rule or Extension.

-
-
-
-
-
Annotation
-
-
@AutoConfigureStubRunner(
-stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-        repositoryRoot = "stubs://file://location/to/the/contracts",
-        ids = "com.example:some-producer",
-        failOnNoStubs = false)
-
-
-
-
JUnit 4 Rule
-
-
@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .withFailOnNoStubs(false);
-
-
-
-
JUnit 5 Extension
-
-
@RegisterExtension
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example:some-producer")
-            .repoRoot("stubs://file://location/to/the/contracts")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-            .withFailOnNoStubs(false);
-
-
-
-
-
-
-

5.11. Common Properties

-
-

This section briefly describes common properties, including:

-
- -
-

5.11.1. Common Properties for JUnit and Spring

-
-

You can set repetitive properties by using system properties or Spring configuration -properties. The following table shows their names with their default values:

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

stubrunner.minPort

10000

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

stubrunner.maxPort

15000

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

stubrunner.repositoryRoot

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

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

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

stubrunner.password

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

stubrunner.stubsPerConsumer

false

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

stubrunner.consumerName

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

-
-
-

5.11.2. Stub Runner Stubs IDs

-
-

You can set the stubs to download in the stubrunner.ids system property. They -use the following pattern:

-
-
-
-
-
-
groupId:artifactId:version:classifier:port
-
-
-
-
-
-

Note that version, classifier, and port are optional.

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

port means the port of the WireMock server.

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

6. Spring Cloud Contract WireMock

-
-
-

The Spring Cloud Contract WireMock modules let you use WireMock in a -Spring Boot application. Check out the -samples -for more details.

-
-
-

If you have a Spring Boot application that uses Tomcat as an embedded server (which is -the default with spring-boot-starter-web), you can add -spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock -to use Wiremock in your tests. Wiremock runs as a stub server, and you -can register stub behavior by using a Java API or by using static JSON declarations as part of -your test. The following code shows an example:

-
-
-
-
-
-
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-@AutoConfigureWireMock(port = 0)
-public class WiremockForDocsTests {
-
-    // A service that calls out over HTTP
-    @Autowired
-    private Service service;
-
-    @BeforeEach
-    public void setup() {
-        this.service.setBase("http://localhost:"
-                + this.environment.getProperty("wiremock.server.port"));
-    }
-
-    // Using the WireMock APIs in the normal way:
-    @Test
-    public void contextLoads() throws Exception {
-        // Stubbing WireMock
-        stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain").withBody("Hello World!")));
-        // We're asserting if WireMock responded properly
-        assertThat(this.service.go()).isEqualTo("Hello World!");
-    }
-
-}
-
-
-
-
-
-

To start the stub server on a different port, use (for example), -@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub -server port can be bound in the test application context with the "wiremock.server.port" -property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to -your test application context, where it is cached between methods and classes -having the same context. The same is true for Spring integration tests. Also, you can -inject a bean of type WireMockServer into your test. -The registered WireMock server is reset after each test class, however, if you need to reset it after each test method, just set the wiremock.reset-mappings-after-each-test property to true.

-
-
-

6.1. Registering Stubs Automatically

-
-

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file -system or classpath (by default, from file:src/test/resources/mappings). You can -customize the locations by using the stubs attribute in the annotation, which can be an -Ant-style resource pattern or a directory. In the case of a directory, */.json is -appended. The following code shows an example:

-
-
-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureWireMock(stubs="classpath:/stubs")
-public class WiremockImportApplicationTests {
-
-    @Autowired
-    private Service service;
-
-    @Test
-    public void contextLoads() throws Exception {
-        assertThat(this.service.go()).isEqualTo("Hello World!");
-    }
-
-}
-
-
-
-
-
- - - - - -
- - -Actually, WireMock always loads mappings from src/test/resources/mappings as -well as the custom locations in the stubs attribute. To change this behavior, you can -also specify a files root, as described in the next section of this document. -
-
-
-

If you use Spring Cloud Contract’s default stub jars, your -stubs are stored in the /META-INF/group-id/artifact-id/versions/mappings/ folder. -If you want to register all stubs from that location, from all embedded JARs, you can use -the following syntax:

-
-
-
-
-
-
@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")
-
-
-
-
-
-
-

6.2. Using Files to Specify the Stub Bodies

-
-

WireMock can read response bodies from files on the classpath or the file system. In the -case of the file system, you can see in the JSON DSL that the response has a bodyFileName instead of a -(literal) body. The files are resolved relative to a root directory (by default, -src/test/resources/__files). To customize this location, you can set the files -attribute in the @AutoConfigureWireMock annotation to the location of the parent -directory (in other words, __files is a subdirectory). You can use Spring resource -notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not -supported. A list of values can be given — in which case, WireMock resolves the first file -that exists when it needs to find a response body.

-
-
- - - - - -
- - -When you configure the files root, it also affects the -automatic loading of stubs, because they come from the root location -in a subdirectory called mappings. The value of files has no -effect on the stubs loaded explicitly from the stubs attribute. -
-
-
-
-

6.3. Alternative: Using JUnit Rules

-
-

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop -the server. To do so, use the WireMockSpring convenience class to obtain an Options -instance, as the following example shows:

-
-
-
-
-
-
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-public class WiremockForDocsClassRuleTests {
-
-    // Start WireMock on some dynamic port
-    // for some reason `dynamicPort()` is not working properly
-    public static WireMockServer wiremock = new WireMockServer(WireMockSpring.options().dynamicPort());
-
-    @BeforeAll
-    static void setupClass() {
-        wiremock.start();
-    }
-
-    @AfterEach
-    void after() {
-        wiremock.resetAll();
-    }
-
-    @AfterAll
-    static void clean() {
-        wiremock.shutdown();
-    }
-
-    // A service that calls out over HTTP to wiremock's port
-    @Autowired
-    private Service service;
-
-    @BeforeEach
-    public void setup() {
-        this.service.setBase("http://localhost:" + wiremock.port());
-    }
-
-    // Using the WireMock APIs in the normal way:
-    @Test
-    public void contextLoads() throws Exception {
-        // Stubbing WireMock
-        wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
-                .withHeader("Content-Type", "text/plain").withBody("Hello World!")));
-        // We're asserting if WireMock responded properly
-        assertThat(this.service.go()).isEqualTo("Hello World!");
-    }
-
-}
-
-
-
-
-
-

The @ClassRule means that the server shuts down after all the methods in this class -have been run.

-
-
-
-

6.4. Relaxed SSL Validation for Rest Template

-
-

WireMock lets you stub a “secure” server with an https URL protocol. If your -application wants to contact that stub server in an integration test, it will find that -the SSL certificates are not valid (the usual problem with self-installed certificates). -The best option is often to re-configure the client to use http. If that is not an -option, you can ask Spring to configure an HTTP client that ignores SSL validation errors -(do so only for tests, of course).

-
-
-

To make this work with minimum fuss, you need to use the Spring Boot -RestTemplateBuilder in your application, as the following example shows:

-
-
-
-
-
-
@Bean
-public RestTemplate restTemplate(RestTemplateBuilder builder) {
-    return builder.build();
-}
-
-
-
-
-
-

You need RestTemplateBuilder because the builder is passed through callbacks to -initialize it, so the SSL validation can be set up in the client at that point. This -happens automatically in your test if you use the @AutoConfigureWireMock -annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the -@AutoConfigureHttpClient annotation as well, as the following example shows:

-
-
-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest("app.baseUrl=https://localhost:6443")
-@AutoConfigureHttpClient
-public class WiremockHttpsServerApplicationTests {
-
-    @ClassRule
-    public static WireMockClassRule wiremock = new WireMockClassRule(
-            WireMockSpring.options().httpsPort(6443));
-...
-}
-
-
-
-
-
-

If you use spring-boot-starter-test, you have the Apache HTTP client on the -classpath, and it is selected by the RestTemplateBuilder and configured to ignore SSL -errors. If you use the default java.net client, you do not need the annotation (but it -does no harm). There is currently no support for other clients, but it may be added -in future releases.

-
-
-

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled -property to false.

-
-
-
-

6.5. WireMock and Spring MVC Mocks

-
-

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into -a Spring MockRestServiceServer. The following code shows an example:

-
-
-
-
-
-
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
-public class WiremockForDocsMockServerApplicationTests {
-
-    @Autowired
-    private RestTemplate restTemplate;
-
-    @Autowired
-    private Service service;
-
-    @Test
-    public void contextLoads() throws Exception {
-        // will read stubs classpath
-        MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
-                .baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
-                .build();
-        // We're asserting if WireMock responded properly
-        assertThat(this.service.go()).isEqualTo("Hello World");
-        server.verify();
-    }
-
-}
-
-
-
-
-
-

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub -path resource pattern as an argument. In the preceding example, the stub defined at -/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to -visit example.org/, it gets the responses as being declared at that URL. More -than one stub pattern can be specified, and each one can be a directory (for a recursive -list of all .json), a fixed filename (as in the preceding example), or an Ant-style -pattern. The JSON format is the normal WireMock format, which you can read about at the -WireMock website.

-
-
-

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as -Spring Boot embedded servers, and Wiremock itself has “native” support for a particular -version of Jetty (currently 9.2). To use the native Jetty, you need to add the native -Wiremock dependencies and exclude the Spring Boot container (if there is one).

-
-
-
-
-
-

7. Build Tools Integration

-
-
-

You can run test generation and stub execution in various ways. The most common ones are -as follows:

-
-
- -
-
-
-
-

8. What to Read Next

-
-
-

If you want to learn more about any of the classes discussed in this section, you can browse the -source code directly. If you have specific questions, see the -how-to section.

-
-
-

If you are comfortable with Spring Cloud Contract’s core features, you can continue on and read -about -Spring Cloud Contract’s advanced features.

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/sagan-boot.html b/reference/html/sagan-boot.html index 61e6af7eb5..9990b6e5bb 100644 --- a/reference/html/sagan-boot.html +++ b/reference/html/sagan-boot.html @@ -1,265 +1,12 @@ - - - + + - - - -On the Producer Side - - - - - - - - - -
-
-

On the Producer Side

-
-
-

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

-
-
-

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

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

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

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

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

-
-
-

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

-
-
-

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

-
-
-

The following example, from pom.xml, shows how to specify the base test class:

-
-
-
-
<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>
-                <baseClassForTests>com.example.contractTest.BaseTestClass</baseClassForTests>
-            </configuration>
-        </plugin>
-        <plugin>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-maven-plugin</artifactId>
-        </plugin>
-    </plugins>
-</build>
-
-
-
-

INFO: The baseClassForTests element lets you specify your base test class. It must be a child of a configuration element within spring-cloud-contract-maven-plugin.

-
-
-

Once the implementation and the test base class are in place, the tests pass, and both the application and the stub artifacts are built and installed in the local Maven repository. You can now merge the changes, and you can publish both the application and the stub artifacts in an online repository.

-
-
-
-
-

On the Consumer Side

-
-
-

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

-
-
-

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

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

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

-
-
-

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

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

The tests are being skipped because the producer-side contract implementation is not in place yet, so the automatically-generated contract tests fail.

-
-
-

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

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

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

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

Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

-
-
-

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

-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/sagan-index.html b/reference/html/sagan-index.html index 958e14538f..9990b6e5bb 100644 --- a/reference/html/sagan-index.html +++ b/reference/html/sagan-index.html @@ -1,266 +1,12 @@ - - - + + - - - -Features - - - - - - - - - -
-
-
-
-

Spring Cloud Contract is an umbrella project holding solutions that help users in successfully implementing the Consumer Driven Contracts approach. Currently Spring Cloud Contract consists of the Spring Cloud Contract Verifier project.

-
-
-

Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped with Contract Definition Language (DSL) written in Groovy or YAML. Contract definitions are used to produce following resources:

-
-
-
    -
  • -

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

    -
  • -
  • -

    Messaging routes if you’re using one. We’re integrating with Spring Integration, Spring Cloud Stream and Apache Camel. You can however set your own integrations if you want to.

    -
  • -
  • -

    Acceptance tests (by default in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (server tests). Full test is generated by Spring Cloud Contract Verifier.

    -
  • -
-
-
-

Spring Cloud Contract Verifier moves TDD to the level of software architecture.

-
-
-

To see how Spring Cloud Contract supports other languages just check out this blog post.

-
-
-
-
-

Features

-
-
-

When trying to test an application that communicates with other services then we could do one of two things:

-
-
-
    -
  • -

    deploy all microservices and perform end to end tests

    -
  • -
  • -

    mock other microservices in unit / integration tests

    -
  • -
-
-
-

Both have their advantages but also a lot of disadvantages. Let’s focus on the latter. -Deploy all microservices and perform end to end tests

-
-
-

Advantages:

-
-
-
    -
  • -

    simulates production

    -
  • -
  • -

    tests real communication between services

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

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

    -
  • -
  • -

    the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime).

    -
  • -
  • -

    long to run

    -
  • -
  • -

    very late feedback

    -
  • -
  • -

    extremely hard to debug

    -
  • -
-
-
-

Mock other microservices in unit / integration tests

-
-
-

Advantages:

-
-
-
    -
  • -

    very fast feedback

    -
  • -
  • -

    no infrastructure requirements

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

    the implementor of the service creates stubs thus they might have nothing to do with the reality

    -
  • -
  • -

    you can go to production with passing tests and failing production

    -
  • -
-
-
-

To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need to set up the whole world of microservices.

-
-
-

Spring Cloud Contract Verifier features:

-
-
-
    -
  • -

    ensure that HTTP / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do

    -
  • -
  • -

    promote acceptance test driven development method and Microservices architectural style

    -
  • -
  • -

    to provide a way to publish changes in contracts that are immediately visible on both sides of the communication

    -
  • -
  • -

    to generate boilerplate test code used on the server side

    -
  • -
-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/spring-cloud-contract-verifier.html b/reference/html/spring-cloud-contract-verifier.html index fb0b4aaff7..9990b6e5bb 100644 --- a/reference/html/spring-cloud-contract-verifier.html +++ b/reference/html/spring-cloud-contract-verifier.html @@ -1,13993 +1,12 @@ - - - + + - - - -Spring Cloud Contract Verifier Introduction - - + - - - - - - -
-
-

Spring Cloud Contract Verifier Introduction

-
-
-

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

-
-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

History

-
-

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

-
-
-

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

-
-
-
-

Why a Contract Verifier?

-
-

Assume that we have a system consisting of multiple microservices:

-
-
-

Testing issues

-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

    Mock other microservices in unit/integration tests.

    -
  • -
-
-
-

Both have their advantages but also a lot of disadvantages.

-
-
-

Deploy all microservices and perform end to end tests

-
-
-

Advantages:

-
-
-
    -
  • -

    Simulates production.

    -
  • -
  • -

    Tests real communication between services.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    They take a long time to run.

    -
  • -
  • -

    The feedback comes very late in the process.

    -
  • -
  • -

    They are extremely hard to debug.

    -
  • -
-
-
-

Mock other microservices in unit/integration tests

-
-
-

Advantages:

-
-
-
    -
  • -

    They provide very fast feedback.

    -
  • -
  • -

    They have no infrastructure requirements.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

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

-
-
-

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

-
-
-
-
-

Purposes

-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

    To promote ATDD method and Microservices architectural style.

    -
  • -
  • -

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

    -
  • -
  • -

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

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

How It Works

-
-

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

-
-
-

A Three-second Tour

-
-

This very brief tour walks through using Spring Cloud Contract:

-
- -
-

You can find a somewhat longer tour -here.

-
-
-
On the Producer Side
-
-

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

-
-
-

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

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

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

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

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

-
-
-

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

-
-
-

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

-
-
-

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

-
-
-
-
On the Consumer Side
-
-

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

-
-
-

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

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

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

-
-
-
    -
  • -

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

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

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

    -
    -
    -
    -
    -
    -
  • -
-
-
-

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

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

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

-
-
-
-
-

A Three-minute Tour

-
-

This brief tour walks through using Spring Cloud Contract:

-
- -
-

You can find an even more brief tour -here.

-
-
-
On the Producer Side
-
-

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

-
-
-

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

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

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

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

In the case of messaging, you can define:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-

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

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

The following example shows the same contract expressed in YAML:

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

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

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

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

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

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

-
-
-

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

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

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

-
-
-

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

-
-
-

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

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

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

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

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

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

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

-
-
-

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

-
-
-

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

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

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

-
-
-

Docker Project

-
-
-

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

-
-
-
-
On the Consumer Side
-
-

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

-
-
-

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

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

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

-
-
-
    -
  • -

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

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

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

    -
    -
    -
    -
    -
    -
  • -
-
-
-

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

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

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

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

Defining the Contract

-
-

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

-
-
-

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

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

Client Side

-
-

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

-
-
-

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

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

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

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

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

-
-
-
-

Server Side

-
-

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

-
-
-

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

-
-
-

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

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

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

-
-

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

-
-
-

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

-
-
-

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

-
-
-

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

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

Technical note

-
-

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

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

Consumer side (Loan Issuance)

-
-

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

-
-
-
    -
  1. -

    Start doing TDD by writing a test for your feature.

    -
  2. -
  3. -

    Write the missing implementation.

    -
  4. -
  5. -

    Clone the Fraud Detection service repository locally.

    -
  6. -
  7. -

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

    -
  8. -
  9. -

    Add the Spring Cloud Contract Verifier plugin.

    -
  10. -
  11. -

    Run the integration tests.

    -
  12. -
  13. -

    File a pull request.

    -
  14. -
  15. -

    Create an initial implementation.

    -
  16. -
  17. -

    Take over the pull request.

    -
  18. -
  19. -

    Write the missing implementation.

    -
  20. -
  21. -

    Deploy your app.

    -
  22. -
  23. -

    Work online.

    -
  24. -
-
-
-

Start doing TDD by writing a test for your feature.

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

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

-
-
-

Write the missing implementation.

-
-
-

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

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

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

-
-
-

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

-
-
-

Clone the Fraud Detection service repository locally.

-
-
-

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

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

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

-
-
-

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

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

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

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

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

-
-
-
    -
  • -

    if an HTTP request is sent with all of

    -
    -
      -
    • -

      a PUT method on the /fraudcheck endpoint,

      -
    • -
    • -

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

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
  • -

    then an HTTP response is sent to the consumer that

    -
    -
      -
    • -

      has status 200,

      -
    • -
    • -

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

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
-
-
-

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

-
-
-

Add the Spring Cloud Contract Verifier plugin.

-
-
-

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

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

Next, add the Spring Cloud Contract Verifier Maven plugin

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

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

-
-
-
    -
  • -

    generate and run tests

    -
  • -
  • -

    produce and install stubs

    -
  • -
-
-
-

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

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

In the logs, you see something like this:

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

The following line is extremely important:

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

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

-
-
-

Run the integration tests.

-
-
-

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

-
-
-

Add the Spring Cloud Contract BOM:

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

Add the dependency to Spring Cloud Contract Stub Runner:

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

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

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

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

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

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

-
-
-

File a pull request.

-
-
-

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

-
-
-

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

-
-
-
-

Producer side (Fraud Detection server)

-
-

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

-
-
-

Create an initial implementation.

-
-
-

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

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

Take over the pull request.

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

You must add the dependencies needed by the autogenerated tests:

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

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

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

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

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

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

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

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

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

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

-
-
-

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

-
-
-

Write the missing implementation.

-
-
-

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

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

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

-
-
-

Deploy your app.

-
-
-

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

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

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

-
-
-
-

Consumer Side (Loan Issuance) Final Step

-
-

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

-
-
-

Merge branch to master.

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

Work online.

-
-
-

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

-
-
-
-
-
-
-
-

That’s it!

-
-
-
-
-

Dependencies

-
-

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

-
-
-

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

-
-
-
- -
-

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

-
-
-

Spring Cloud Contract video

-
-

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

-
-
-
- -
-
-
- -
-
-

Samples

-
-

You can find some samples at -samples.

-
-
-
-
-
-

Spring Cloud Contract FAQ

-
-
-

Why use Spring Cloud Contract Verifier and not X ?

-
-

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

-
-
-
    -
  • -

    Possibility to do CDC with messaging

    -
  • -
  • -

    Clear and easy to use, statically typed DSL

    -
  • -
  • -

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

    -
  • -
  • -

    Automatic generation of tests from the defined Contract

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

    Via Docker adds support for any language & framework used

    -
  • -
-
-
-
-

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

-
-

No problem. You can write a contract in YAML!

-
-
-
-

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

-
-

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

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

and JSON response

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

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

-
-
-

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

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

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

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

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

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

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

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

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

-
-
-

Either via the value method

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

or using the $() method

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

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

-
-
-

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

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

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

-
-
-

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

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

How to do Stubs versioning?

-
-

API Versioning

-
-

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

-
-
-
    -
  • -

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

    -
  • -
  • -

    pass versions through headers / urls

    -
  • -
-
-
-

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

-
-
-

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

-
-
-
-

JAR versioning

-
-

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

-
-
-

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

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

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

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

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

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

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

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

Dev or prod stubs

-
-

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

-
-
-

Example of tests using development version of stubs

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

Example of tests using production version of stubs

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

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

-
-
-
-
-

Common repo with contracts

-
-

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

-
-
-

Repo structure

-
-

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

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

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

-
-
-

Example of a pom.xml inside the server folder.

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

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

-
-
-

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

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

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

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

Workflow

-
-

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

-
-
-
-

Consumer

-
-

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

-
-
- - - - - -
- - -You need to have Maven installed locally -
-
-
-
-

Producer

-
-

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

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

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

-
-
-

The rest of the flow looks the same.

-
-
-
-

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

-
-

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

-
-
-
For Maven Project
-
-

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

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

    Add a custom configuration for the common-repo dependency:

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

    Add the common-repo dependency to your classpath:

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

    Download the dependency to an appropriate folder:

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

    Unzip JAR:

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

    Cleanup unused contracts:

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

    Create task dependencies:

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

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

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

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

-
-

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

-
-
-

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

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

Under META-INF folder:

-
-
-
    -
  • -

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

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
    -
      -
    • -

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

      -
      -
        -
      • -

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

        -
      • -
      • -

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

        -
      • -
      • -

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

        -
      • -
      -
      -
    • -
    • -

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

      -
      -
        -
      • -

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

        -
      • -
      • -

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

        -
      • -
      -
      -
    • -
    -
    -
  • -
  • -

    finally, there are two folders:

    -
    -
      -
    • -

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

      -
    • -
    • -

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

      -
    • -
    -
    -
  • -
-
-
-

Protocol convention

-
-

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

-
-
-

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

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

Producer

-
-

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

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

With such a setup:

-
-
-
    -
  • -

    Git project will be cloned to a temporary directory

    -
  • -
  • -

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

    -
  • -
  • -

    Tests will be generated from the contracts

    -
  • -
  • -

    Stubs will be created from the contracts

    -
  • -
  • -

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

    -
  • -
  • -

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

    -
  • -
-
-
-
-

Producer with contracts stored locally

-
-

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

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

With such a setup:

-
-
-
    -
  • -

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

    -
  • -
  • -

    Tests will be generated from the contracts

    -
  • -
  • -

    Stubs will be created from the contracts

    -
  • -
  • -

    Once the tests pass

    -
    -
      -
    • -

      Git project will be cloned to a temporary directory

      -
    • -
    • -

      The stubs and contracts will be committed in the cloned repository

      -
    • -
    -
    -
  • -
  • -

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

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

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

-
-
-

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

-
-
-
-
-

Consumer

-
-

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

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

With such a setup:

-
-
-
    -
  • -

    Git project will be cloned to a temporary directory

    -
  • -
  • -

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

    -
  • -
  • -

    Stub servers will be started and fed with mappings

    -
  • -
  • -

    Messaging definitions will be read and used in the messaging tests

    -
  • -
-
-
-
-
-

Can I use the Pact Broker?

-
-

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

-
-
-

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

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

Pact Consumer

-
-

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

-
-
-
-

Producer

-
-

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

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

With such a setup:

-
-
-
    -
  • -

    Pact files will be downloaded from the Pact Broker

    -
  • -
  • -

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

    -
  • -
  • -

    The JAR with the stubs gets automatically created as usual

    -
  • -
-
-
-
-

Pact Consumer (Producer Contract approach)

-
-

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

-
-
-

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

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

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

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

With such a setup:

-
-
-
    -
  • -

    Pact files will be downloaded from the Pact Broker

    -
  • -
  • -

    Spring Cloud Contract will convert the Pact files into stub definitions

    -
  • -
  • -

    The stub servers will be started and fed with stubs

    -
  • -
-
-
-

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

-
-
-
-
-

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

-
-

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

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

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

-
-

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

-
-
-

To turn off this feature just bump WireMock logging to ERROR

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

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

-
-

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

-
-
-
-

Can I reference text from file?

-
-

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

-
-
-
-
-
-
-

Spring Cloud Contract Verifier Setup

-
-
-

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

-
- -
-

Gradle Project

-
-

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

-
- -
-

Prerequisites

-
-

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

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

Add Gradle Plugin with Dependencies

-
-

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

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

Gradle and Rest Assured 2.0

-
-

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

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

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

-
-
-
-

Snapshot Versions for Gradle

-
-

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

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

Add stubs

-
-

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

-
-
-

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

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

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods:

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-

Run the Plugin

-
-

The plugin registers itself to be invoked before a check task. If you want it to be -part of your build process, you need to do nothing more. If you just want to generate -tests, invoke the generateContractTests task.

-
-
-
-

Default Setup

-
-

The default Gradle Plugin setup creates the following Gradle part of the build (in -pseudocode):

-
-
-
-
contracts {
-    testFramework ='JUNIT'
-    testMode = 'MockMvc'
-    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
-    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
-    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
-    basePackageForTests = 'org.springframework.cloud.verifier.tests'
-    stubsOutputDir = project.file("${project.buildDir}/stubs")
-
-    // the following properties are used when you want to provide where the JAR with contract lays
-    contractDependency {
-        stringNotation = ''
-    }
-    contractsPath = ''
-    contractsWorkOffline = false
-    contractRepository {
-        cacheDownloadedContracts(true)
-    }
-}
-
-tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
-    baseName = project.name
-    classifier = contracts.stubsSuffix
-    from contractVerifier.stubsOutputDir
-}
-
-project.artifacts {
-    archives task
-}
-
-tasks.create(type: Copy, name: 'copyContracts') {
-    from contracts.contractsDslDir
-    into contracts.stubsOutputDir
-}
-
-verifierStubsJar.dependsOn 'copyContracts'
-
-publishing {
-    publications {
-        stubs(MavenPublication) {
-            artifactId project.name
-            artifact verifierStubsJar
-        }
-    }
-}
-
-
-
-
-

Configure Plugin

-
-

To change the default configuration, add a contracts snippet to your Gradle config, as -shown here:

-
-
-
-
contracts {
-	testMode = 'MockMvc'
-	baseClassForTests = 'org.mycompany.tests'
-	generatedTestSourcesDir = project.file('src/generatedContract')
-}
-
-
-
-
-

Configuration Options

-
-
    -
  • -

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.

    -
  • -
  • -

    imports: Creates an array with imports that should be included in generated tests -(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    -
  • -
  • -

    staticImports: Creates an array with static imports that should be included in -generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty -array.

    -
  • -
  • -

    basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.

    -
  • -
  • -

    baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.

    -
  • -
  • -

    packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests.

    -
  • -
  • -

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This -setting takes precedence over packageWithBaseClasses and baseClassForTests.

    -
  • -
  • -

    ruleClassForTests: Specifies a rule that should be added to the generated test -classes.

    -
  • -
  • -

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing -should be skipped. By default, it is an empty array.

    -
  • -
  • -

    contractsDslDir: Specifies the directory containing contracts written using the -GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    -
  • -
  • -

    generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.

    -
  • -
  • -

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-resources/contracts.

    -
  • -
  • -

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from -the Groovy DSL should be placed.

    -
  • -
  • -

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and -JUnit 5 are supported with JUnit 4 being the default framework.

    -
  • -
  • -

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    -
  • -
-
-
-

The following properties are used when you want to specify the location of the JAR -containing the contracts:

-
-
-
    -
  • -

    contractDependency: Specifies the Dependency that provides -groupid:artifactid:version:classifier coordinates. You can use the contractDependency -closure to set it up.

    -
  • -
  • -

    contractsPath: Specifies the path to the jar. If contract dependencies are -downloaded, the path defaults to groupid/artifactid where groupid is slash -separated. Otherwise, it scans contracts under the provided directory.

    -
  • -
  • -

    contractsMode: Specifies the mode of downloading contracts (whether the -JAR is available offline, remotely etc.)

    -
  • -
  • -

    deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

    -
  • -
-
-
-

Below you can find a list of experimental features you can turn on via the plugin:

-
-
-
    -
  • -

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    -
  • -
  • -

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    -
  • -
-
-
-
-

Single Base Class for All Tests

-
-

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified.

-
-
-
-
abstract class BaseMockMvcSpec extends Specification {
-
-	def setup() {
-		RestAssuredMockMvc.standaloneSetup(new PairIdController())
-	}
-
-	void isProperCorrelationId(Integer correlationId) {
-		assert correlationId == 123456
-	}
-
-	void isEmpty(String value) {
-		assert value == null
-	}
-
-}
-
-
-
-

If you use Explicit mode, you can use a base class to initialize the whole tested app -as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this -base class should also contain a protected WebTarget webTarget field. Right now, the -only option to test the JAX-RS API is to start a web server.

-
-
-
-

Different Base Classes for Contracts

-
-

If your base classes differ between contracts, you can tell the Spring Cloud Contract -plugin which class should get extended by the autogenerated tests. You have two options:

-
-
-
    -
  • -

    Follow a convention by providing the packageWithBaseClasses

    -
  • -
  • -

    Provide explicit mapping via baseClassMappings

    -
  • -
-
-
-

By Convention

-
-
-

The convention is such that if you have a contract under (for example) -src/test/resources/contract/foo/bar/baz/ and set the value of the -packageWithBaseClasses property to com.example.base, then Spring Cloud Contract -Verifier assumes that there is a BarBazBase class under the com.example.base package. -In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a Base suffix. This rule takes precedence over baseClassForTests. -Here is an example of how it works in the contracts closure:

-
-
-
-
packageWithBaseClasses = 'com.example.base'
-
-
-
-

By Mapping

-
-
-

You can manually map a regular expression of the contract’s package to fully qualified -name of the base class for the matched contract. You have to provide a list called -baseClassMappings that consists baseClassMapping objects that takes a -contractPackageRegex to baseClassFQN mapping. Consider the following example:

-
-
-
-
baseClassForTests = "com.example.FooBase"
-baseClassMappings {
-	baseClassMapping('.*/com/.*', 'com.example.ComBase')
-	baseClassMapping('.*/bar/.*': 'com.example.BarBase')
-}
-
-
-
-

Let’s assume that you have contracts under - - src/test/resources/contract/com/ - - src/test/resources/contract/foo/

-
-
-

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. -(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests -generated from src/test/resources/contract/com/ contracts extend the -com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

-
-
-
-

Invoking Generated Tests

-
-

To ensure that the provider side is compliant with defined contracts, you need to invoke:

-
-
-
-
./gradlew generateContractTests test
-
-
-
-
-

Pushing stubs to SCM

-
-

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to call the pushStubsToScm -task. Example:

-
-
-
-
$ ./gradlew pushStubsToScm
-
-
-
-

Under Using the SCM Stub Downloader you can find all possible -configuration options that you can pass either via -the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, -via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, -a system property or an environment variable.

-
-
-
-

Spring Cloud Contract Verifier on the Consumer Side

-
-

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin -in exactly the same way as in case of provider. If you do not want to use Stub Runner -then you need to copy contracts stored in src/test/resources/contracts and generate -WireMock JSON stubs using:

-
-
-
-
./gradlew generateClientStubs
-
-
-
- - - - - -
- - -The stubsOutputDir option has to be set for stub generation to work. -
-
-
-

When present, JSON stubs can be used in automated tests of consuming a service.

-
-
-
-
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
-class LoanApplicationServiceSpec extends Specification {
-
- @ClassRule
- @Shared
- WireMockClassRule wireMockRule == new WireMockClassRule()
-
- @Autowired
- LoanApplicationService sut
-
- def 'should successfully apply for loan'() {
-   given:
- 	LoanApplication application =
-			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
-   when:
-	LoanApplicationResult loanApplication == sut.loanApplication(application)
-   then:
-	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
-	loanApplication.rejectionReason == null
- }
-}
-
-
-
-

LoanApplication makes a call to FraudDetection service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

-
-
-
-
-

Maven Project

-
-

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the -following sections:

-
- -
-

Add maven plugin

-
-

Add the Spring Cloud Contract BOM in a fashion similar to this:

-
-
-
-
<dependencyManagement>
-	<dependencies>
-		<dependency>
-			<groupId>org.springframework.cloud</groupId>
-			<artifactId>spring-cloud-dependencies</artifactId>
-			<version>${spring-cloud-release.version}</version>
-			<type>pom</type>
-			<scope>import</scope>
-		</dependency>
-	</dependencies>
-</dependencyManagement>
-
-
-
-

Next, add the Spring Cloud Contract Verifier Maven plugin:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-	<configuration>
-		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
-		<convertToYaml>true</convertToYaml>
-	</configuration>
-</plugin>
-
-
- -
-
-

Maven and Rest Assured 2.0

-
-

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest -Assured 2.x by adding it to the plugins classpath, as shown here:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <packageWithBaseClasses>com.example</packageWithBaseClasses>
-    </configuration>
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-contract-verifier</artifactId>
-            <version>${spring-cloud-contract.version}</version>
-        </dependency>
-        <dependency>
-           <groupId>com.jayway.restassured</groupId>
-           <artifactId>rest-assured</artifactId>
-           <version>2.5.0</version>
-           <scope>compile</scope>
-        </dependency>
-        <dependency>
-           <groupId>com.jayway.restassured</groupId>
-           <artifactId>spring-mock-mvc</artifactId>
-           <version>2.5.0</version>
-           <scope>compile</scope>
-        </dependency>
-    </dependencies>
-</plugin>
-
-<dependencies>
-    <!-- all dependencies -->
-    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
-    <dependency>
-       <groupId>com.jayway.restassured</groupId>
-       <artifactId>rest-assured</artifactId>
-       <version>2.5.0</version>
-       <scope>test</scope>
-    </dependency>
-    <dependency>
-       <groupId>com.jayway.restassured</groupId>
-       <artifactId>spring-mock-mvc</artifactId>
-       <version>2.5.0</version>
-       <scope>test</scope>
-    </dependency>
-</dependencies>
-
-
-
-

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath -and modifies the imports accordingly.

-
-
-
-

Snapshot versions for Maven

-
-

For Snapshot and Milestone versions, you have to add the following section to your -pom.xml, as shown here:

-
-
-
-
<repositories>
-	<repository>
-		<id>spring-snapshots</id>
-		<name>Spring Snapshots</name>
-		<url>https://repo.spring.io/snapshot</url>
-		<snapshots>
-			<enabled>true</enabled>
-		</snapshots>
-	</repository>
-	<repository>
-		<id>spring-milestones</id>
-		<name>Spring Milestones</name>
-		<url>https://repo.spring.io/milestone</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</repository>
-	<repository>
-		<id>spring-releases</id>
-		<name>Spring Releases</name>
-		<url>https://repo.spring.io/release</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</repository>
-</repositories>
-<pluginRepositories>
-	<pluginRepository>
-		<id>spring-snapshots</id>
-		<name>Spring Snapshots</name>
-		<url>https://repo.spring.io/snapshot</url>
-		<snapshots>
-			<enabled>true</enabled>
-		</snapshots>
-	</pluginRepository>
-	<pluginRepository>
-		<id>spring-milestones</id>
-		<name>Spring Milestones</name>
-		<url>https://repo.spring.io/milestone</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</pluginRepository>
-	<pluginRepository>
-		<id>spring-releases</id>
-		<name>Spring Releases</name>
-		<url>https://repo.spring.io/release</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</pluginRepository>
-</pluginRepositories>
-
-
-
-
-

Add stubs

-
-

By default, Spring Cloud Contract Verifier is looking for stubs in the -src/test/resources/contracts directory. The directory containing stub definitions is -treated as a class name, and each stub definition is treated as a single test. We assume -that it contains at least one directory to be used as test class name. If there is more -than one level of nested directories, all except the last one is used as package name. -For example, with following structure:

-
-
-
-
src/test/resources/contracts/myservice/shouldCreateUser.groovy
-src/test/resources/contracts/myservice/shouldReturnUser.groovy
-
-
-
-

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-

Run plugin

-
-

The plugin goal generateTests is assigned to be invoked in the phase called -generate-test-sources. If you want it to be part of your build process, you need not do -anything. If you just want to generate tests, invoke the generateTests goal.

-
-
-
-

Configure plugin

-
-

To change the default configuration, just add a configuration section to the plugin -definition or the execution definition, as shown here:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <executions>
-        <execution>
-            <goals>
-                <goal>convert</goal>
-                <goal>generateStubs</goal>
-                <goal>generateTests</goal>
-            </goals>
-        </execution>
-    </executions>
-    <configuration>
-        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
-        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
-    </configuration>
-</plugin>
-
-
-
-
-

Configuration Options

-
-
    -
  • -

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.

    -
  • -
  • -

    basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.

    -
  • -
  • -

    ruleClassForTests: Specifies a rule that should be added to the generated test -classes.

    -
  • -
  • -

    baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.

    -
  • -
  • -

    contractsDirectory: Specifies a directory containing contracts written with the -GroovyDSL. The default directory is /src/test/resources/contracts.

    -
  • -
  • -

    generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.

    -
  • -
  • -

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    -
  • -
  • -

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and -JUnit 5 are supported with JUnit 4 being the default framework.

    -
  • -
  • -

    packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests. The convention is such that, if you -have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set -the value of the packageWithBaseClasses property to com.example.base, then Spring -Cloud Contract Verifier assumes that there is a BarBazBase class under the -com.example.base package. In other words, the system takes the last two parts of the -package, if they exist, and forms a class with a Base suffix.

    -
  • -
  • -

    baseClassMappings: Specifies a list of base class mappings that provide -contractPackageRegex, which is checked against the package where the contract is -located, and baseClassFQN, which maps to the fully qualified name of the base class for -the matched contract. For example, if you have a contract under -src/test/resources/contract/foo/bar/baz/ and map the property -.* → com.example.base.BaseClass, then the test class generated from these contracts -extends com.example.base.BaseClass. This setting takes precedence over -packageWithBaseClasses and baseClassForTests.

    -
  • -
  • -

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    -
  • -
-
-
-

If you want to download your contract definitions from a Maven repository, you can use -the following options:

-
-
-
    -
  • -

    contractDependency: The contract dependency that contains all the packaged contracts.

    -
  • -
  • -

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. -Defaults to groupid/artifactid where gropuid is slash separated.

    -
  • -
  • -

    contractsMode: Picks the mode in which stubs will be found and registered

    -
  • -
  • -

    deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

    -
  • -
  • -

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, -use the current Maven ones.

    -
  • -
  • -

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    -
  • -
-
-
-

We cache only non-snapshot, explicitly provided versions (for example -+ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

-
-
-

Below you can find a list of experimental features you can turn on via the plugin:

-
-
-
    -
  • -

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    -
  • -
  • -

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    -
  • -
-
-
-
-

Single Base Class for All Tests

-
-

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified.

-
-
-
-
package org.mycompany.tests
-
-import org.mycompany.ExampleSpringController
-import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
-import spock.lang.Specification
-
-class MvcSpec extends Specification {
-  def setup() {
-   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
-  }
-}
-
-
-
-

You can also setup the whole context if necessary.

-
-
-
-
import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.context.WebApplicationContext;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
-public abstract class BaseTestClass {
-
-	@Autowired
-	WebApplicationContext context;
-
-	@Before
-	public void setup() {
-		RestAssuredMockMvc.webAppContextSetup(this.context);
-	}
-}
-
-
-
-

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app -similarly, as you might find in regular integration tests.

-
-
-
-
import io.restassured.RestAssured;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.web.server.LocalServerPort
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.context.WebApplicationContext;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
-public abstract class BaseTestClass {
-
-	@LocalServerPort
-	int port;
-
-	@Before
-	public void setup() {
-		RestAssured.baseURI = "http://localhost:" + this.port;
-	}
-}
-
-
-
-

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right -now, the only option to test the JAX-RS API is to start a web server.

-
-
-
-

Different base classes for contracts

-
-

If your base classes differ between contracts, you can tell the Spring Cloud Contract -plugin which class should get extended by the autogenerated tests. You have two options:

-
-
-
    -
  • -

    Follow a convention by providing the packageWithBaseClasses

    -
  • -
  • -

    provide explicit mapping via baseClassMappings

    -
  • -
-
-
-

By Convention

-
-
-

The convention is such that if you have a contract under (for example) -src/test/resources/contract/foo/bar/baz/ and set the value of the -packageWithBaseClasses property to com.example.base, then Spring Cloud Contract -Verifier assumes that there is a BarBazBase class under the com.example.base package. -In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a Base suffix. This rule takes precedence over baseClassForTests. -Here is an example of how it works in the contracts closure:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<configuration>
-		<packageWithBaseClasses>hello</packageWithBaseClasses>
-	</configuration>
-</plugin>
-
-
-
-

By Mapping

-
-
-

You can manually map a regular expression of the contract’s package to fully qualified -name of the base class for the matched contract. You have to provide a list called -baseClassMappings that consists baseClassMapping objects that takes a -contractPackageRegex to baseClassFQN mapping. Consider the following example:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<configuration>
-		<baseClassForTests>com.example.FooBase</baseClassForTests>
-		<baseClassMappings>
-			<baseClassMapping>
-				<contractPackageRegex>.*com.*</contractPackageRegex>
-				<baseClassFQN>com.example.TestBase</baseClassFQN>
-			</baseClassMapping>
-		</baseClassMappings>
-	</configuration>
-</plugin>
-
-
-
-

Assume that you have contracts under these two locations: -* src/test/resources/contract/com/ -* src/test/resources/contract/foo/

-
-
-

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. -(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests -generated from src/test/resources/contract/com/ contracts extend the -com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

-
-
-
-

Invoking generated tests

-
-

The Spring Cloud Contract Maven Plugin generates verification code in a directory called -/generated-test-sources/contractVerifier and attaches this directory to testCompile -goal.

-
-
-

For Groovy Spock code, use the following:

-
-
-
-
<plugin>
-	<groupId>org.codehaus.gmavenplus</groupId>
-	<artifactId>gmavenplus-plugin</artifactId>
-	<version>1.5</version>
-	<executions>
-		<execution>
-			<goals>
-				<goal>testCompile</goal>
-			</goals>
-		</execution>
-	</executions>
-	<configuration>
-		<testSources>
-			<testSource>
-				<directory>${project.basedir}/src/test/groovy</directory>
-				<includes>
-					<include>**/*.groovy</include>
-				</includes>
-			</testSource>
-			<testSource>
-				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
-				<includes>
-					<include>**/*.groovy</include>
-				</includes>
-			</testSource>
-		</testSources>
-	</configuration>
-</plugin>
-
-
-
-

To ensure that provider side is compliant with defined contracts, you need to invoke -mvn generateTest test.

-
-
-
-

Pushing stubs to SCM

-
-

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to add the pushStubsToScm -goal. Example:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- Base class mappings etc. -->
-
-        <!-- We want to pick contracts from a Git repository -->
-        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
-
-        <!-- We reuse the contract dependency section to set up the path
-        to the folder that contains the contract definitions. In our case the
-        path will be /groupId/artifactId/version/contracts -->
-        <contractDependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>${project.artifactId}</artifactId>
-            <version>${project.version}</version>
-        </contractDependency>
-
-        <!-- The contracts mode can't be classpath -->
-        <contractsMode>REMOTE</contractsMode>
-    </configuration>
-    <executions>
-        <execution>
-            <phase>package</phase>
-            <goals>
-                <!-- By default we will not push the stubs back to SCM,
-                you have to explicitly add it as a goal -->
-                <goal>pushStubsToScm</goal>
-            </goals>
-        </execution>
-    </executions>
-</plugin>
-
-
-
-

Under Using the SCM Stub Downloader you can find all possible -configuration options that you can pass either via -the <configuration><contractProperties> map, a system property -or an environment variable.

-
-
-
-

Maven Plugin and STS

-
-

If you see the following exception while using STS:

-
-
-
-STS Exception -
-
-
-

When you click on the error marker you should see something like this:

-
-
-
-
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
- cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
- org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
-...
- org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
- org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
- org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
-
-
-
-

In order to fix this issue, provide the following section in your pom.xml:

-
-
-
-
<build>
-    <pluginManagement>
-        <plugins>
-            <!--This plugin's configuration is used to store Eclipse m2e settings
-                only. It has no influence on the Maven build itself. -->
-            <plugin>
-                <groupId>org.eclipse.m2e</groupId>
-                <artifactId>lifecycle-mapping</artifactId>
-                <version>1.0.0</version>
-                <configuration>
-                    <lifecycleMappingMetadata>
-                        <pluginExecutions>
-                             <pluginExecution>
-                                <pluginExecutionFilter>
-                                    <groupId>org.springframework.cloud</groupId>
-                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                    <versionRange>[1.0,)</versionRange>
-                                    <goals>
-                                        <goal>convert</goal>
-                                    </goals>
-                                </pluginExecutionFilter>
-                                <action>
-                                    <execute />
-                                </action>
-                             </pluginExecution>
-                        </pluginExecutions>
-                    </lifecycleMappingMetadata>
-                </configuration>
-            </plugin>
-        </plugins>
-    </pluginManagement>
-</build>
-
-
-
-
-

Maven Plugin with Spock Tests

-
-

You can select the Spock Framework for creating and executing the auto-generated contract -verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, -in Maven you will require some additional setup in order to make the tests compile and execute properly.

-
-
-

First of all, you will have to use a plugin, such as GMavenPlus plugin, -to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the -path where your base test classes are defined and the path were the generated contract tests are added. -Please refer to the example below:

-
-
-
-
-
-
-
-

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven -Surefire plugin setup, like in the following example:

-
-
-
-
-
-
-
-
-
-

Stubs and Transitive Dependencies

-
-

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One -problem that arises is that, when reusing the stubs, you can mistakenly import all of -that stub’s dependencies. When building a Maven artifact, even though you have a couple -of different jars, all of them share one pom:

-
-
-
-
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
-├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
-├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
-├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
-├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
-├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
-├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
-├── ...
-└── ...
-
-
-
-

There are three possibilities of working with those dependencies so as not to have any -issues with transitive dependencies:

-
-
-
    -
  • -

    Mark all application dependencies as optional

    -
  • -
  • -

    Create a separate artifactid for the stubs

    -
  • -
  • -

    Exclude dependencies on the consumer side

    -
  • -
-
-
-

Mark all application dependencies as optional

-
-
-

If, in the github-webhook application, you mark all of your dependencies as optional, -when you include the github-webhook stubs in another application (or when that -dependency gets downloaded by Stub Runner) then, since all of the dependencies are -optional, they will not get downloaded.

-
-
-

Create a separate artifactid for the stubs

-
-
-

If you create a separate artifactid, then you can set it up in whatever way you wish. -For example, you might decide to have no dependencies at all.

-
-
-

Exclude dependencies on the consumer side

-
-
-

As a consumer, if you add the stub dependency to your classpath, you can explicitly -exclude the unwanted dependencies.

-
-
-
-

Scenarios

-
-

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to -stick to the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This will work regardles - of whether you’re working with YAML or Groovy. Example:

-
-
-
-
my_contracts_dir\
-  scenario1\
-    1_login.groovy
-    2_showCart.groovy
-    3_logout.groovy
-
-
-
-

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a -name of scenario1 and the three following steps:

-
-
-
    -
  1. -

    login marked as Started pointing to…​

    -
  2. -
  3. -

    showCart marked as Step1 pointing to…​

    -
  4. -
  5. -

    logout marked as Step2 which will close the scenario.

    -
  6. -
-
-
-

More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/

-
-
-

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

-
-
-
-

Docker Project

-
-

We’re publishing a springcloud/spring-cloud-contract Docker image -that contains a project that will generate tests and execute them in EXPLICIT mode -against a running application.

-
-
- - - - - -
- - -The EXPLICIT mode means that the tests generated from contracts will send -real requests and not the mocked ones. -
-
-
-

Short intro to Maven, JARs and Binary storage

-
-

Since the Docker image can be used by non JVM projects, it’s good to -explain the basic terms behind Spring Cloud Contract packaging defaults.

-
-
-

Part of the following definitions were taken from the Maven Glossary

-
-
-
    -
  • -

    Project: Maven thinks in terms of projects. Everything that you -will build are projects. Those projects follow a well defined -“Project Object Model”. Projects can depend on other projects, -in which case the latter are called “dependencies”. A project may -consistent of several subprojects, however these subprojects are still -treated equally as projects.

    -
  • -
  • -

    Artifact: An artifact is something that is either produced or used -by a project. Examples of artifacts produced by Maven for a project -include: JARs, source and binary distributions. Each artifact -is uniquely identified by a group id and an artifact ID which is -unique within a group.

    -
  • -
  • -

    JAR: JAR stands for Java ARchive. It’s a format based on -the ZIP file format. Spring Cloud Contract packages the contracts and generated -stubs in a JAR file.

    -
  • -
  • -

    GroupId: A group ID is a universally unique identifier for a project. -While this is often just the project name (eg. commons-collections), -it is helpful to use a fully-qualified package name to distinguish it -from other projects with a similar name (eg. org.apache.maven). -Typically, when published to the Artifact Manager, the GroupId will get -slash separated and form part of the URL. E.g. for group id com.example -and artifact id application would be /com/example/application/.

    -
  • -
  • -

    Classifier: The Maven dependency notation looks as follows: -groupId:artifactId:version:classifier. The classifier is additional suffix -passed to the dependency. E.g. stubs, sources. The same dependency -e.g. com.example:application can produce multiple artifacts that -differ from each other with the classifier.

    -
  • -
  • -

    Artifact manager: When you generate binaries / sources / packages, you would -like them to be available for others to download / reference or reuse. In case -of the JVM world those artifacts would be JARs, for Ruby these are gems -and for Docker those would be Docker images. You can store those artifacts -in a manager. Examples of such managers can be Artifactory -or Nexus.

    -
  • -
-
-
-
-

How it works

-
-

The image searches for contracts under the /contracts folder. -The output from running the tests will be available under -/spring-cloud-contract/build folder (it’s useful for debugging -purposes).

-
-
-

It’s enough for you to mount your contracts, pass the environment variables - and the image will:

-
-
-
    -
  • -

    generate the contract tests

    -
  • -
  • -

    execute the tests against the provided URL

    -
  • -
  • -

    generate the WireMock stubs

    -
  • -
  • -

    (optional - turned on by default) publish the stubs to a Artifact Manager

    -
  • -
-
-
-
Environment Variables
-
-

The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance etc.

-
-
-
    -
  • -

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    -
  • -
  • -

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    -
  • -
  • -

    PROJECT_NAME - artifact id. Defaults to example

    -
  • -
  • -

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    -
  • -
  • -

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally

    -
  • -
  • -

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    -
  • -
  • -

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    -
  • -
  • -

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    -
  • -
-
-
-

These environment variables are used when contracts lay in an external repository. To enable -this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

-
-
-
    -
  • -

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    -
  • -
  • -

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    -
  • -
  • -

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. -If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. -Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. -for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts -from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. -You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    -
  • -
-
-
-

These environment variables are used when tests are executed:

-
-
-
    -
  • -

    APPLICATION_BASE_URL - url against which tests should be executed. -Remember that it has to be accessible from the Docker container (e.g. localhost -will not work)

    -
  • -
  • -

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    -
  • -
  • -

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    -
  • -
-
-
-
-
-

Example of usage

-
-

Let’s take a look at a simple MVC application

-
-
-
-
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
-$ cd bookstore
-
-
-
-

The contracts are available under /contracts folder.

-
-
-
-

Server side (nodejs)

-
-

Since we want to run tests, we could just execute:

-
-
-
-
$ npm test
-
-
-
-

however, for learning purposes, let’s split it into pieces:

-
-
-
-
# Stop docker infra (nodejs, artifactory)
-$ ./stop_infra.sh
-# Start docker infra (nodejs, artifactory)
-$ ./setup_infra.sh
-
-# Kill & Run app
-$ pkill -f "node app"
-$ nohup node app &
-
-# Prepare environment variables
-$ SC_CONTRACT_DOCKER_VERSION="..."
-$ APP_IP="192.168.0.100"
-$ APP_PORT="3000"
-$ ARTIFACTORY_PORT="8081"
-$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
-$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
-$ CURRENT_DIR="$( pwd )"
-$ CURRENT_FOLDER_NAME=${PWD##*/}
-$ PROJECT_VERSION="0.0.1.RELEASE"
-
-# Execute contract tests
-$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
-
-# Kill app
-$ pkill -f "node app"
-
-
-
-

What will happen is that via bash scripts:

-
-
-
    -
  • -

    infrastructure will be set up (MongoDb, Artifactory). -In real life scenario you would just run the NodeJS application -with mocked database. In this example we want to show how we can -benefit from Spring Cloud Contract in no time.

    -
  • -
  • -

    due to those constraints the contracts also represent the -stateful situation

    -
    -
      -
    • -

      first request is a POST that causes data to get inserted to the database

      -
    • -
    • -

      second request is a GET that returns a list of data with 1 previously inserted element

      -
    • -
    -
    -
  • -
  • -

    the NodeJS application will be started (on port 3000)

    -
  • -
  • -

    contract tests will be generated via Docker and tests -will be executed against the running application

    -
    -
      -
    • -

      the contracts will be taken from /contracts folder.

      -
    • -
    • -

      the output of the test execution is available under -node_modules/spring-cloud-contract/output.

      -
    • -
    -
    -
  • -
  • -

    the stubs will be uploaded to Artifactory. You can check them out -under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    -
  • -
-
-
-

To see how the client side looks like check out the Stub Runner Docker section.

-
-
-
-
-
-
-

Spring Cloud Contract Verifier Messaging

-
-
-

Spring Cloud Contract Verifier lets you verify applications that use messaging as a -means of communication. All of the integrations shown in this document work with Spring, -but you can also create one of your own and use that.

-
-
-

Integrations

-
-

You can use one of the following four integration configurations:

-
-
-
    -
  • -

    Apache Camel

    -
  • -
  • -

    Spring Integration

    -
  • -
  • -

    Spring Cloud Stream

    -
  • -
  • -

    Spring AMQP

    -
  • -
-
-
-

Since we use Spring Boot, if you have added one of these libraries to the classpath, all -the messaging configuration is automatically set up.

-
-
- - - - - -
- - -Remember to put @AutoConfigureMessageVerifier on the base class of your -generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not -work. -
-
-
- - - - - -
- - -If you want to use Spring Cloud Stream, remember to add a dependency on -org.springframework.cloud:spring-cloud-stream-test-support, as shown here: -
-
-
-
Maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-stream-test-support</artifactId>
-    <scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
-
-
-
-
-

Manual Integration Testing

-
-

The main interface used by the tests is -org.springframework.cloud.contract.verifier.messaging.MessageVerifier. -It defines how to send and receive messages. You can create your own implementation to -achieve the same goal.

-
-
-

In a test, you can inject a ContractVerifierMessageExchange to send and receive -messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. -Here’s an example:

-
-
-
-
@RunWith(SpringTestRunner.class)
-@SpringBootTest
-@AutoConfigureMessageVerifier
-public static class MessagingContractTests {
-
-  @Autowired
-  private MessageVerifier verifier;
-  ...
-}
-
-
-
- - - - - -
- - -If your tests require stubs as well, then @AutoConfigureStubRunner includes the -messaging configuration, so you only need the one annotation. -
-
-
-
-

Publisher-Side Test Generation

-
-

Having the input or outputMessage sections in your DSL results in creation of tests -on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a -possibility to create JUnit 5, TestNG or Spock tests.

-
-
-

There are 3 main scenarios that we should take into consideration:

-
-
-
    -
  • -

    Scenario 1: There is no input message that produces an output message. The output -message is triggered by a component inside the application (for example, scheduler).

    -
  • -
  • -

    Scenario 2: The input message triggers an output message.

    -
  • -
  • -

    Scenario 3: The input message is consumed and there is no output message.

    -
  • -
-
-
- - - - - -
- - -The destination passed to messageFrom or sentTo can have different -meanings for different messaging implementations. For Stream and Integration it is -first resolved as a destination of a channel. Then, if there is no such destination -it is resolved as a channel name. For Camel, that’s a certain component (for example, -jms). -
-
-
-

Scenario 1: No Input Message

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
			def contractDsl = Contract.make {
-				name "foo"
-				label 'some_label'
-				input {
-					triggeredBy('bookReturnedTriggered()')
-				}
-				outputMessage {
-					sentTo('activemq:output')
-					body('''{ "bookName" : "foo" }''')
-					headers {
-						header('BOOK-NAME', 'foo')
-						messagingContentType(applicationJson())
-					}
-				}
-			}
-
-
-
-
YAML
-
-
label: some_label
-input:
-  triggeredBy: bookReturnedTriggered
-outputMessage:
-  sentTo: activemq:output
-  body:
-    bookName: foo
-  headers:
-    BOOK-NAME: foo
-    contentType: application/json
-
-
-
-

The following JUnit test is created:

-
-
-
-
					'''\
-package com.example;
-
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import org.junit.Test;
-import org.junit.Rule;
-import javax.inject.Inject;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
-
-@SuppressWarnings("rawtypes")
-public class FooTest {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging;
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
-
-\t@Test
-\tpublic void validate_foo() throws Exception {
-\t\t// when:
-\t\t\tbookReturnedTriggered();
-
-\t\t// then:
-\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
-\t\t\tassertThat(response).isNotNull();
-
-\t\t// and:
-\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
-\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
-\t\t\tassertThat(response.getHeader("contentType")).isNotNull();
-\t\t\tassertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
-
-\t\t// and:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
-\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
-\t}
-
-}
-
-'''
-
-
-
-

And the following Spock test would be created:

-
-
-
-
					'''\
-package com.example
-
-import com.jayway.jsonpath.DocumentContext
-import com.jayway.jsonpath.JsonPath
-import spock.lang.Specification
-import javax.inject.Inject
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
-
-@SuppressWarnings("rawtypes")
-class FooSpec extends Specification {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
-
-\tdef validate_foo() throws Exception {
-\t\twhen:
-\t\t\tbookReturnedTriggered()
-
-\t\tthen:
-\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output")
-\t\t\tresponse != null
-
-\t\tand:
-\t\t\tresponse.getHeader("BOOK-NAME") != null
-\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
-\t\t\tresponse.getHeader("contentType") != null
-\t\t\tresponse.getHeader("contentType").toString() == 'application/json'
-
-\t\tand:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
-\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
-\t}
-
-}
-
-'''
-
-
-
-
-

Scenario 2: Output Triggered by Input

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
			def contractDsl = Contract.make {
-				name "foo"
-				label 'some_label'
-				input {
-					messageFrom('jms:input')
-					messageBody([
-							bookName: 'foo'
-					])
-					messageHeaders {
-						header('sample', 'header')
-					}
-				}
-				outputMessage {
-					sentTo('jms:output')
-					body([
-							bookName: 'foo'
-					])
-					headers {
-						header('BOOK-NAME', 'foo')
-					}
-				}
-			}
-
-
-
-
YAML
-
-
label: some_label
-input:
-  messageFrom: jms:input
-  messageBody:
-    bookName: 'foo'
-  messageHeaders:
-    sample: header
-outputMessage:
-  sentTo: jms:output
-  body:
-    bookName: foo
-  headers:
-    BOOK-NAME: foo
-
-
-
-

The following JUnit test is created:

-
-
-
-
					'''\
-package com.example;
-
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import org.junit.Test;
-import org.junit.Rule;
-import javax.inject.Inject;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
-
-@SuppressWarnings("rawtypes")
-public class FooTest {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging;
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
-
-\t@Test
-\tpublic void validate_foo() throws Exception {
-\t\t// given:
-\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
-\t\t\t\t\t\t, headers()
-\t\t\t\t\t\t\t.header("sample", "header")
-\t\t\t);
-
-\t\t// when:
-\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input");
-
-\t\t// then:
-\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
-\t\t\tassertThat(response).isNotNull();
-
-\t\t// and:
-\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
-\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
-
-\t\t// and:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
-\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
-\t}
-
-}
-
-'''
-
-
-
-

And the following Spock test would be created:

-
-
-
-
					"""\
-package com.example
-
-import com.jayway.jsonpath.DocumentContext
-import com.jayway.jsonpath.JsonPath
-import spock.lang.Specification
-import javax.inject.Inject
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
-
-@SuppressWarnings("rawtypes")
-class FooSpec extends Specification {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
-
-\tdef validate_foo() throws Exception {
-\t\tgiven:
-\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-\t\t\t\t\t'''{"bookName":"foo"}'''
-\t\t\t\t\t\t, headers()
-\t\t\t\t\t\t\t.header("sample", "header")
-\t\t\t)
-
-\t\twhen:
-\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input")
-
-\t\tthen:
-\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output")
-\t\t\tresponse != null
-
-\t\tand:
-\t\t\tresponse.getHeader("BOOK-NAME") != null
-\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
-
-\t\tand:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
-\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
-\t}
-
-}
-
-"""
-
-
-
-
-

Scenario 3: No Output Message

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
			def contractDsl = Contract.make {
-				name "foo"
-				label 'some_label'
-				input {
-					messageFrom('jms:delete')
-					messageBody([
-							bookName: 'foo'
-					])
-					messageHeaders {
-						header('sample', 'header')
-					}
-					assertThat('bookWasDeleted()')
-				}
-			}
-
-
-
-
YAML
-
-
label: some_label
-input:
-  messageFrom: jms:delete
-  messageBody:
-    bookName: 'foo'
-  messageHeaders:
-    sample: header
-  assertThat: bookWasDeleted()
-
-
-
-

The following JUnit test is created:

-
-
-
-
					"""\
-package com.example;
-
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import org.junit.Test;
-import org.junit.Rule;
-import javax.inject.Inject;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
-
-@SuppressWarnings("rawtypes")
-public class FooTest {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging;
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
-
-\t@Test
-\tpublic void validate_foo() throws Exception {
-\t\t// given:
-\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
-\t\t\t\t\t\t, headers()
-\t\t\t\t\t\t\t.header("sample", "header")
-\t\t\t);
-
-\t\t// when:
-\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete");
-\t\t\tbookWasDeleted();
-
-\t}
-
-}
-
-"""
-
-
-
-

And the following Spock test would be created:

-
-
-
-
					"""\
-package com.example
-
-import com.jayway.jsonpath.DocumentContext
-import com.jayway.jsonpath.JsonPath
-import spock.lang.Specification
-import javax.inject.Inject
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
-import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
-import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
-
-@SuppressWarnings("rawtypes")
-class FooSpec extends Specification {
-\t@Inject ContractVerifierMessaging contractVerifierMessaging
-\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
-
-\tdef validate_foo() throws Exception {
-\t\tgiven:
-\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-\t\t\t\t\t'''{"bookName":"foo"}'''
-\t\t\t\t\t\t, headers()
-\t\t\t\t\t\t\t.header("sample", "header")
-\t\t\t)
-
-\t\twhen:
-\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete")
-\t\t\tbookWasDeleted()
-
-\t\tthen:
-\t\t\tnoExceptionThrown()
-\t}
-
-}
-"""
-
-
-
-
-
-

Consumer Stub Generation

-
-

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with -a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

-
-
-

For more information, see Stub Runner for Messaging section.

-
-
-
Maven
-
-
<dependencies>
-	<dependency>
-		<groupId>org.springframework.cloud</groupId>
-		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
-	</dependency>
-
-	<dependency>
-		<groupId>org.springframework.cloud</groupId>
-		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
-		<scope>test</scope>
-	</dependency>
-	<dependency>
-		<groupId>org.springframework.cloud</groupId>
-		<artifactId>spring-cloud-stream-test-support</artifactId>
-		<scope>test</scope>
-	</dependency>
-</dependencies>
-
-<dependencyManagement>
-	<dependencies>
-		<dependency>
-			<groupId>org.springframework.cloud</groupId>
-			<artifactId>spring-cloud-dependencies</artifactId>
-			<version>Hoxton.BUILD-SNAPSHOT</version>
-			<type>pom</type>
-			<scope>import</scope>
-		</dependency>
-	</dependencies>
-</dependencyManagement>
-
-
-
-
Gradle
-
-
ext {
-	contractsDir = file("mappings")
-	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
-}
-
-// Automatically added by plugin:
-// copyContracts - copies contracts to the output folder from which JAR will be created
-// verifierStubsJar - JAR with a provided stub suffix
-// the presented publication is also added by the plugin but you can modify it as you wish
-
-publishing {
-	publications {
-		stubs(MavenPublication) {
-			artifactId "${project.name}-stubs"
-			artifact verifierStubsJar
-		}
-	}
-}
-
-
-
-
-
-
-

Spring Cloud Contract Stub Runner

-
-
-

One of the issues that you might encounter while using Spring Cloud Contract Verifier is -passing the generated WireMock JSON stubs from the server side to the client side (or to -various clients). The same takes place in terms of client-side generation for messaging.

-
-
-

Copying the JSON files and setting the client side for messaging manually is out of the -question. That is why we introduced Spring Cloud Contract Stub Runner. It can -automatically download and run the stubs for you.

-
-
-

Snapshot versions

-
-

Add the additional snapshot repository to your build.gradle file to use snapshot -versions, which are automatically uploaded after every successful build:

-
-
-
Maven
-
-
<repositories>
-	<repository>
-		<id>spring-snapshots</id>
-		<name>Spring Snapshots</name>
-		<url>https://repo.spring.io/snapshot</url>
-		<snapshots>
-			<enabled>true</enabled>
-		</snapshots>
-	</repository>
-	<repository>
-		<id>spring-milestones</id>
-		<name>Spring Milestones</name>
-		<url>https://repo.spring.io/milestone</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</repository>
-	<repository>
-		<id>spring-releases</id>
-		<name>Spring Releases</name>
-		<url>https://repo.spring.io/release</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</repository>
-</repositories>
-<pluginRepositories>
-	<pluginRepository>
-		<id>spring-snapshots</id>
-		<name>Spring Snapshots</name>
-		<url>https://repo.spring.io/snapshot</url>
-		<snapshots>
-			<enabled>true</enabled>
-		</snapshots>
-	</pluginRepository>
-	<pluginRepository>
-		<id>spring-milestones</id>
-		<name>Spring Milestones</name>
-		<url>https://repo.spring.io/milestone</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</pluginRepository>
-	<pluginRepository>
-		<id>spring-releases</id>
-		<name>Spring Releases</name>
-		<url>https://repo.spring.io/release</url>
-		<snapshots>
-			<enabled>false</enabled>
-		</snapshots>
-	</pluginRepository>
-</pluginRepositories>
-
-
-
-
Gradle
-
-
buildscript {
-	repositories {
-		mavenCentral()
-		mavenLocal()
-		maven { url "https://repo.spring.io/snapshot" }
-		maven { url "https://repo.spring.io/milestone" }
-		maven { url "https://repo.spring.io/release" }
-	}
-
-
-
-
-

Publishing Stubs as JARs

-
-

The easiest approach would be to centralize the way stubs are kept. For example, you can -keep them as jars in a Maven repository.

-
-
- - - - - -
- - -For both Maven and Gradle, the setup comes ready to work. However, you can customize -it if you want to. -
-
-
-
Maven
-
-
<!-- First disable the default jar setup in the properties section -->
-<!-- we don't want the verifier to do a jar for us -->
-<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
-
-<!-- Next add the assembly plugin to your build -->
-<!-- we want the assembly plugin to generate the JAR -->
-<plugin>
-	<groupId>org.apache.maven.plugins</groupId>
-	<artifactId>maven-assembly-plugin</artifactId>
-	<executions>
-		<execution>
-			<id>stub</id>
-			<phase>prepare-package</phase>
-			<goals>
-				<goal>single</goal>
-			</goals>
-			<inherited>false</inherited>
-			<configuration>
-				<attach>true</attach>
-				<descriptors>
-					${basedir}/src/assembly/stub.xml
-				</descriptors>
-			</configuration>
-		</execution>
-	</executions>
-</plugin>
-
-<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
-<assembly
-	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
-	<id>stubs</id>
-	<formats>
-		<format>jar</format>
-	</formats>
-	<includeBaseDirectory>false</includeBaseDirectory>
-	<fileSets>
-		<fileSet>
-			<directory>src/main/java</directory>
-			<outputDirectory>/</outputDirectory>
-			<includes>
-				<include>**com/example/model/*.*</include>
-			</includes>
-		</fileSet>
-		<fileSet>
-			<directory>${project.build.directory}/classes</directory>
-			<outputDirectory>/</outputDirectory>
-			<includes>
-				<include>**com/example/model/*.*</include>
-			</includes>
-		</fileSet>
-		<fileSet>
-			<directory>${project.build.directory}/snippets/stubs</directory>
-			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
-			<includes>
-				<include>**/*</include>
-			</includes>
-		</fileSet>
-		<fileSet>
-			<directory>${basedir}/src/test/resources/contracts</directory>
-			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
-			<includes>
-				<include>**/*.groovy</include>
-			</includes>
-		</fileSet>
-	</fileSets>
-</assembly>
-
-
-
-
Gradle
-
-
ext {
-	contractsDir = file("mappings")
-	stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
-}
-
-// Automatically added by plugin:
-// copyContracts - copies contracts to the output folder from which JAR will be created
-// verifierStubsJar - JAR with a provided stub suffix
-// the presented publication is also added by the plugin but you can modify it as you wish
-
-publishing {
-	publications {
-		stubs(MavenPublication) {
-			artifactId "${project.name}-stubs"
-			artifact verifierStubsJar
-		}
-	}
-}
-
-
-
-
-

Stub Runner Core

-
-

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of -Consumer Driven Contracts.

-
-
-

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. -For messaging, special stub routes are defined.

-
-
-

Retrieving stubs

-
-

You can pick the following options of acquiring stubs

-
-
-
    -
  • -

    Aether based solution that downloads JARs with stubs from Artifactory / Nexus

    -
  • -
  • -

    Classpath scanning solution that searches classpath via pattern to retrieve stubs

    -
  • -
  • -

    Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    -
  • -
-
-
-

The latter example is described in the Custom Stub Runner section.

-
-
-
Stub downloading
-
-

You can control the stub downloading via the stubsMode switch. It picks value from the -StubRunnerProperties.StubsMode enum. You can use the following options

-
-
-
    -
  • -

    StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath

    -
  • -
  • -

    StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)

    -
  • -
  • -

    StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

    -
  • -
-
-
-

Example:

-
-
-
-
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
-
-
-
-
-
Classpath scanning
-
-

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH -(or set nothing since CLASSPATH is the default value) then classpath will get scanned. -Let’s look at the following example:

-
-
-
-
@AutoConfigureStubRunner(ids = {
-    "com.example:beer-api-producer:+:stubs:8095",
-    "com.example.foo:bar:1.0.0:superstubs:8096"
-})
-
-
-
-

If you’ve added the dependencies to your classpath

-
-
-
Maven
-
-
<dependency>
-    <groupId>com.example</groupId>
-    <artifactId>beer-api-producer-restdocs</artifactId>
-    <classifier>stubs</classifier>
-    <version>0.0.1-SNAPSHOT</version>
-    <scope>test</scope>
-    <exclusions>
-        <exclusion>
-            <groupId>*</groupId>
-            <artifactId>*</artifactId>
-        </exclusion>
-    </exclusions>
-</dependency>
-<dependency>
-    <groupId>com.example.foo</groupId>
-    <artifactId>bar</artifactId>
-    <classifier>superstubs</classifier>
-    <version>1.0.0</version>
-    <scope>test</scope>
-    <exclusions>
-        <exclusion>
-            <groupId>*</groupId>
-            <artifactId>*</artifactId>
-        </exclusion>
-    </exclusions>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
-    transitive = false
-}
-testCompile("com.example.foo:bar:1.0.0:superstubs") {
-    transitive = false
-}
-
-
-
-

Then the following locations on your classpath will get scanned. For com.example:beer-api-producer-restdocs

-
-
-
    -
  • -

    /META-INF/com.example/beer-api-producer-restdocs/*/.*

    -
  • -
  • -

    /contracts/com.example/beer-api-producer-restdocs/*/.*

    -
  • -
  • -

    /mappings/com.example/beer-api-producer-restdocs/*/.*

    -
  • -
-
-
-

and com.example.foo:bar

-
-
-
    -
  • -

    /META-INF/com.example.foo/bar/*/.*

    -
  • -
  • -

    /contracts/com.example.foo/bar/*/.*

    -
  • -
  • -

    /mappings/com.example.foo/bar/*/.*

    -
  • -
-
-
- - - - - -
- - -As you can see you have to explicitly provide the group and artifact ids when packaging the -producer stubs. -
-
-
-

The producer would setup the contracts like this:

-
-
-
-
└── src
-    └── test
-        └── resources
-            └── contracts
-                └── com.example
-                    └── beer-api-producer-restdocs
-                        └── nested
-                            └── contract3.groovy
-
-
-
-

To achieve proper stub packaging.

-
-
-

Or using the Maven assembly plugin or -Gradle Jar task you have to create the following -structure in your stubs jar.

-
-
-
-
└── META-INF
-    └── com.example
-        └── beer-api-producer-restdocs
-            └── 2.0.0
-                ├── contracts
-                │   └── nested
-                │       └── contract2.groovy
-                └── mappings
-                    └── mapping.json
-
-
-
-

By maintaining this structure classpath gets scanned and you can profit from the messaging / -HTTP stubs without the need to download artifacts.

-
-
-
-
Configuring HTTP Server Stubs
-
-

Stub Runner has a notion of a HttpServerStub that abstracts the underlaying -concrete implementation of the HTTP server (e.g. WireMock is one of the implementations). -Sometimes, you need to perform some additional tuning of the stub servers, -that is concrete for the given implementation. To do that, Stub Runner gives you -the httpServerStubConfigurer property that is available in the annotation, -JUnit rule, and is accessible via system properties, where you can provide -your implementation of the org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer interface. The implementations can alter -the configuration files for the given HTTP server stub.

-
-
-

Spring Cloud Contract Stub Runner comes with an implementation that you -can extend, for WireMock - org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer. In the configure method -you can provide your own, custom configuration for the given stub. The use -case might be starting WireMock for the given artifact id, on an HTTPs port. Example:

-
-
-
WireMockHttpServerStubConfigurer implementation
-
-
@CompileStatic
-static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
-
-	private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
-
-	@Override
-	WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
-		if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
-			int httpsPort = SocketUtils.findAvailableTcpPort()
-			log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
-			return httpStubConfiguration
-					.httpsPort(httpsPort)
-		}
-		return httpStubConfiguration
-	}
-}
-
-
-
-

You can then reuse it via the annotation

-
-
-
-
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
-		httpServerStubConfigurer = HttpsForFraudDetection)
-
-
-
-

Whenever an https port is found, it will take precedence over the http one.

-
-
-
-
-

Running stubs

-
-
Running using main app
-
-

You can set the following options to the main class:

-
-
-
-
-c, --classifier                Suffix for the jar containing stubs (e.
-                                  g. 'stubs' if the stub jar would
-                                  have a 'stubs' classifier for stubs:
-                                  foobar-stubs ). Defaults to 'stubs'
-                                  (default: stubs)
---maxPort, --maxp <Integer>     Maximum port value to be assigned to
-                                  the WireMock instance. Defaults to
-                                  15000 (default: 15000)
---minPort, --minp <Integer>     Minimum port value to be assigned to
-                                  the WireMock instance. Defaults to
-                                  10000 (default: 10000)
--p, --password                  Password to user when connecting to
-                                  repository
---phost, --proxyHost            Proxy host to use for repository
-                                  requests
---pport, --proxyPort [Integer]  Proxy port to use for repository
-                                  requests
--r, --root                      Location of a Jar containing server
-                                  where you keep your stubs (e.g. http:
-                                  //nexus.
-                                  net/content/repositories/repository)
--s, --stubs                     Comma separated list of Ivy
-                                  representation of jars with stubs.
-                                  Eg. groupid:artifactid1,groupid2:
-                                  artifactid2:classifier
---sm, --stubsMode               Stubs mode to be used. Acceptable values
-                                  [CLASSPATH, LOCAL, REMOTE]
--u, --username                  Username to user when connecting to
-                                  repository
-
-
-
-
-
HTTP Stubs
-
-

Stubs are defined in JSON documents, whose syntax is defined in WireMock documentation

-
-
-

Example:

-
-
-
-
{
-    "request": {
-        "method": "GET",
-        "url": "/ping"
-    },
-    "response": {
-        "status": 200,
-        "body": "pong",
-        "headers": {
-            "Content-Type": "text/plain"
-        }
-    }
-}
-
-
-
-
-
Viewing registered mappings
-
-

Every stubbed collaborator exposes list of defined mappings under __/admin/ endpoint.

-
-
-

You can also use the mappingsOutputFolder property to dump the mappings to files. - For annotation based approach it would look like this

-
-
-
-
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
-mappingsOutputFolder = "target/outputmappings/")
-
-
-
-

and for the JUnit approach like this:

-
-
-
-
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
-			.repoRoot("https://some_url")
-			.downloadStub("a.b.c", "loanIssuance")
-			.downloadStub("a.b.c:fraudDetectionServer")
-			.withMappingsOutputFolder("target/outputmappings")
-
-
-
-

Then if you check out the folder target/outputmappings you would see the following structure

-
-
-
-
.
-├── fraudDetectionServer_13705
-└── loanIssuance_12255
-
-
-
-

That means that there were two stubs registered. fraudDetectionServer was registered at port 13705 -and loanIssuance at port 12255. If we take a look at one of the files we would see (for WireMock) -mappings available for the given server:

-
-
-
-
[{
-  "id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
-  "request" : {
-    "url" : "/name",
-    "method" : "GET"
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "fraudDetectionServer"
-  },
-  "uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
-},
-...
-]
-
-
-
-
-
Messaging Stubs
-
-

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

-
-
-
-
-
-

Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

-
-

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

-
-
-
-
@ClassRule
-public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
-		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
-				"loanIssuance")
-		.downloadStub(
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
-
-@BeforeClass
-@AfterClass
-public static void setupProps() {
-	System.clearProperty("stubrunner.repository.root");
-	System.clearProperty("stubrunner.classifier");
-}
-
-
-
-

There’s also a StubRunnerExtension available for JUnit 5. StubRunnerRule and StubRunnerExtension work in a very -similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

-
-
-
    -
  • -

    download them

    -
  • -
  • -

    cache them locally

    -
  • -
  • -

    unzip them to a temporary folder

    -
  • -
  • -

    start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port

    -
  • -
  • -

    feed the WireMock server with all JSON files that are valid WireMock definitions

    -
  • -
  • -

    can also send messages (remember to pass an implementation of MessageVerifier interface)

    -
  • -
-
-
-

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. -Check their docs for more information.

-
-
-

Since the StubRunnerRule and StubRunnerExtension implement the StubFinder they allow you to find the started stubs:

-
-
-
-
package org.springframework.cloud.contract.stubrunner;
-
-import java.net.URL;
-import java.util.Collection;
-import java.util.Map;
-
-import org.springframework.cloud.contract.spec.Contract;
-
-/**
- * Contract for finding registered stubs.
- *
- * @author Marcin Grzejszczak
- */
-public interface StubFinder extends StubTrigger {
-
-	/**
-	 * For the given groupId and artifactId tries to find the matching URL of the running
-	 * stub.
-	 * @param groupId - might be null. In that case a search only via artifactId takes
-	 * place
-	 * @param artifactId - artifact id of the stub
-	 * @return URL of a running stub or throws exception if not found
-	 * @throws StubNotFoundException in case of not finding a stub
-	 */
-	URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
-
-	/**
-	 * For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
-	 * tries to find the matching URL of the running stub. You can also pass only
-	 * {@code artifactId}.
-	 * @param ivyNotation - Ivy representation of the Maven artifact
-	 * @return URL of a running stub or throws exception if not found
-	 * @throws StubNotFoundException in case of not finding a stub
-	 */
-	URL findStubUrl(String ivyNotation) throws StubNotFoundException;
-
-	/**
-	 * @return all running stubs
-	 */
-	RunningStubs findAllRunningStubs();
-
-	/**
-	 * @return the list of Contracts
-	 */
-	Map<StubConfiguration, Collection<Contract>> getContracts();
-
-}
-
-
-
-

Example of usage in Spock tests:

-
-
-
-
@ClassRule
-@Shared
-StubRunnerRule rule = new StubRunnerRule()
-		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-		.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
-		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
-		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
-		.withMappingsOutputFolder("target/outputmappingsforrule")
-
-
-def 'should start WireMock servers'() {
-	expect: 'WireMocks are running'
-		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
-		rule.findStubUrl('loanIssuance') != null
-		rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
-		rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
-	and:
-		rule.findAllRunningStubs().isPresent('loanIssuance')
-		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
-		rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
-	and: 'Stubs were registered'
-		"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
-		"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
-}
-
-def 'should output mappings to output folder'() {
-	when:
-		def url = rule.findStubUrl('fraudDetectionServer')
-	then:
-		new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
-}
-
-
-
-

Example of usage in JUnit tests:

-
-
-
-
	@Test
-	public void should_start_wiremock_servers() throws Exception {
-		// expect: 'WireMocks are running'
-		then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
-				"loanIssuance")).isNotNull();
-		then(rule.findStubUrl("loanIssuance")).isNotNull();
-		then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
-				"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
-		then(rule.findStubUrl(
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
-						.isNotNull();
-		// and:
-		then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
-		then(rule.findAllRunningStubs().isPresent(
-				"org.springframework.cloud.contract.verifier.stubs",
-				"fraudDetectionServer")).isTrue();
-		then(rule.findAllRunningStubs().isPresent(
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
-						.isTrue();
-		// and: 'Stubs were registered'
-		then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
-				.isEqualTo("loanIssuance");
-		then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
-				.isEqualTo("fraudDetectionServer");
-	}
-
-	private String httpGet(String url) throws Exception {
-		try (InputStream stream = URI.create(url).toURL().openStream()) {
-			return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
-		}
-	}
-
-}
-
-
-
-

JUnit 5 Extension example:

-
-
-
-
// Visible for Junit
-@RegisterExtension
-static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-		.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
-				"loanIssuance")
-		.downloadStub(
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
-		.withMappingsOutputFolder("target/outputmappingsforrule");
-
-@BeforeAll
-@AfterAll
-static void setupProps() {
-	System.clearProperty("stubrunner.repository.root");
-	System.clearProperty("stubrunner.classifier");
-}
-
-private static String repoRoot() {
-	try {
-		return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
-				.toURI().toString();
-	}
-	catch (Exception e) {
-		return "";
-	}
-}
-
-
-
-

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

-
-
- - - - - -
- - -To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the -MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). -If you don’t do this, then whenever you try to send a message an exception will be thrown. -
-
-
-

Maven settings

-
-

The stub downloader honors Maven settings for a different local repository folder. -Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

-
-
-
-

Providing fixed ports

-
-

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of -JUnit rule.

-
-
-
-

Fluent API

-
-

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

-
-
-
-
@ClassRule
-public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
-		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
-		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
-				"loanIssuance")
-		.withPort(12345).downloadStub(
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
-
-@BeforeClass
-@AfterClass
-public static void setupProps() {
-	System.clearProperty("stubrunner.repository.root");
-	System.clearProperty("stubrunner.classifier");
-}
-
-
-
-

You can see that for this example the following test is valid:

-
-
-
-
then(rule.findStubUrl("loanIssuance"))
-		.isEqualTo(URI.create("http://localhost:12345").toURL());
-then(rule.findStubUrl("fraudDetectionServer"))
-		.isEqualTo(URI.create("http://localhost:12346").toURL());
-
-
-
-
-

Stub Runner with Spring

-
-

Sets up Spring configuration of the Stub Runner project.

-
-
-

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads -and registers in WireMock the selected stubs.

-
-
-

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use -its methods as presented below:

-
-
-
-
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
-@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
-		'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
-		'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
-@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
-		httpServerStubConfigurer = HttpsForFraudDetection)
-@ActiveProfiles("test")
-class StubRunnerConfigurationSpec extends Specification {
-
-	@Autowired
-	StubFinder stubFinder
-	@Autowired
-	Environment environment
-	@StubRunnerPort("fraudDetectionServer")
-	int fraudDetectionServerPort
-	@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
-	int fraudDetectionServerPortWithGroupId
-	@Value('${foo}')
-	Integer foo
-
-	@BeforeClass
-	@AfterClass
-	void setupProps() {
-		System.clearProperty("stubrunner.repository.root")
-		System.clearProperty("stubrunner.classifier")
-	}
-
-	def 'should start WireMock servers'() {
-		expect: 'WireMocks are running'
-			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
-			stubFinder.findStubUrl('loanIssuance') != null
-			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
-			stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
-			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
-			stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
-		and:
-			stubFinder.findAllRunningStubs().isPresent('loanIssuance')
-			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
-			stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
-		and: 'Stubs were registered'
-			"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
-			"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
-		and: 'Fraud Detection is an HTTPS endpoint'
-			stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
-	}
-
-	def 'should throw an exception when stub is not found'() {
-		when:
-			stubFinder.findStubUrl('nonExistingService')
-		then:
-			thrown(StubNotFoundException)
-		when:
-			stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
-		then:
-			thrown(StubNotFoundException)
-	}
-
-	def 'should register started servers as environment variables'() {
-		expect:
-			environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
-			stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
-		and:
-			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
-			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
-		and:
-			environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
-			stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
-	}
-
-	def 'should be able to interpolate a running stub in the passed test property'() {
-		given:
-			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
-		expect:
-			fraudPort > 0
-			environment.getProperty("foo", Integer) == fraudPort
-			environment.getProperty("fooWithGroup", Integer) == fraudPort
-			foo == fraudPort
-	}
-
-	@Issue("#573")
-	def 'should be able to retrieve the port of a running stub via an annotation'() {
-		given:
-			int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
-		expect:
-			fraudPort > 0
-			fraudDetectionServerPort == fraudPort
-			fraudDetectionServerPortWithGroupId == fraudPort
-	}
-
-	def 'should dump all mappings to a file'() {
-		when:
-			def url = stubFinder.findStubUrl("fraudDetectionServer")
-		then:
-			new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
-	}
-
-	@Configuration
-	@EnableAutoConfiguration
-	static class Config {}
-
-	@CompileStatic
-	static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
-
-		private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
-
-		@Override
-		WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
-			if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
-				int httpsPort = SocketUtils.findAvailableTcpPort()
-				log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
-				return httpStubConfiguration
-						.httpsPort(httpsPort)
-			}
-			return httpStubConfiguration
-		}
-	}
-}
-
-
-
-

for the following configuration file:

-
-
-
-
stubrunner:
-  repositoryRoot: classpath:m2repo/repository/
-  ids:
-    - org.springframework.cloud.contract.verifier.stubs:loanIssuance
-    - org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
-    - org.springframework.cloud.contract.verifier.stubs:bootService
-  stubs-mode: remote
-
-
-
-

Instead of using the properties you can also use the properties inside the @AutoConfigureStubRunner. -Below you can find an example of achieving the same result by setting values on the annotation.

-
-
-
-
@AutoConfigureStubRunner(
-		ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
-				"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
-				"org.springframework.cloud.contract.verifier.stubs:bootService"],
-		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-		repositoryRoot = "classpath:m2repo/repository/")
-
-
-
-

Stub Runner Spring registers environment variables in the following manner -for every registered WireMock server. Example for Stub Runner ids - com.example:foo, com.example:bar.

-
-
-
    -
  • -

    stubrunner.runningstubs.foo.port

    -
  • -
  • -

    stubrunner.runningstubs.com.example.foo.port

    -
  • -
  • -

    stubrunner.runningstubs.bar.port

    -
  • -
  • -

    stubrunner.runningstubs.com.example.bar.port

    -
  • -
-
-
-

Which you can reference in your code.

-
-
-

You can also use the @StubRunnerPort annotation to inject the port of a running stub. -Value of the annotation can be the groupid:artifactid or just the artifactid. Example for Stub Runner ids -com.example:foo, com.example:bar.

-
-
-
-
@StubRunnerPort("foo")
-int fooPort;
-@StubRunnerPort("com.example:bar")
-int barPort;
-
-
-
-
-
-

Stub Runner Spring Cloud

-
-

Stub Runner can integrate with Spring Cloud.

-
-
-

For real life examples you can check the

-
- -
-

Stubbing Service Discovery

-
-

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

-
-
-
    -
  • -

    DiscoveryClient

    -
  • -
  • -

    Ribbon ServerList

    -
  • -
-
-
-

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. -We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate -or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

-
-
-

For example this test will pass

-
-
-
-
def 'should make service discovery work'() {
-	expect: 'WireMocks are running'
-		"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
-		"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
-	and: 'Stubs can be reached via load service discovery'
-		restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
-		restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
-}
-
-
-
-

for the following configuration file

-
-
-
-
stubrunner:
-  idsToServiceIds:
-    ivyNotation: someValueInsideYourCode
-    fraudDetectionServer: someNameThatShouldMapFraudDetectionServer
-
-
-
-
Test profiles and service discovery
-
-

In your integration tests you typically don’t want to call neither a discovery service (e.g. Eureka) -or Config Server. That’s why you create an additional test configuration in which you want to disable -these features.

-
-
-

Due to certain limitations of spring-cloud-commons to achieve this you have disable these properties -via a static block like presented below (example for Eureka)

-
-
-
-
    //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
-    static {
-        System.setProperty("eureka.client.enabled", "false");
-        System.setProperty("spring.cloud.config.failFast", "false");
-    }
-
-
-
-
-
-

Additional Configuration

-
-

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. -You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false -You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

-
-
- - - - - -
- - -By default all service discovery will be stubbed. That means that regardless of the fact if you have -an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set - stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be - merged with the stubbed ones. -
-
-
-

The default Maven configuration used by Stub Runner can be tweaked either -via the following system properties or environment variables

-
-
-
    -
  • -

    maven.repo.local - path to the custom maven local repository location

    -
  • -
  • -

    org.apache.maven.user-settings - path to custom maven user settings location

    -
  • -
  • -

    org.apache.maven.global-settings - path to maven global settings location

    -
  • -
-
-
-
-
-

Stub Runner Boot Application

-
-

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to -trigger the messaging labels and to access started WireMock servers.

-
-
-

One of the use-cases is to run some smoke (end to end) tests on a deployed application. -You can check out the Spring Cloud Pipelines -project for more information.

-
-
-

How to use it?

-
-
Stub Runner Server
-
-

Just add the

-
-
-
-
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
-
-
-
-

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

-
-
-

For the properties check the Stub Runner Spring section.

-
-
-
-
Stub Runner Server Fat Jar
-
-

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

-
-
-
-
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
-$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
-
-
-
-
-
Spring Cloud CLI
-
-

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI -project you can start Stub Runner Boot by executing spring cloud stubrunner.

-
-
-

In order to pass the configuration just create a stubrunner.yml file in the current working directory -or a subdirectory called config or in ~/.spring-cloud. The file could look like this -(example for running stubs installed locally)

-
-
-
stubrunner.yml
-
-
stubrunner:
-  stubsMode: LOCAL
-  ids:
-    - com.example:beer-api-producer:+:9876
-
-
-
-

and then just call spring cloud stubrunner from your terminal window to start -the Stub Runner server. It will be available at port 8750.

-
-
-
-
-

Endpoints

-
-
HTTP
-
-
    -
  • -

    GET /stubs - returns a list of all running stubs in ivy:integer notation

    -
  • -
  • -

    GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    -
  • -
-
-
-
-
Messaging
-
-

For Messaging

-
-
-
    -
  • -

    GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation

    -
  • -
  • -

    POST /triggers/{label} - executes a trigger with label

    -
  • -
  • -

    POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    -
  • -
-
-
-
-
-

Example

-
-
-
@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
-@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
-@ActiveProfiles("test")
-class StubRunnerBootSpec extends Specification {
-
-	@Autowired
-	StubRunning stubRunning
-
-	def setup() {
-		RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
-				new TriggerController(stubRunning))
-	}
-
-	def 'should return a list of running stub servers in "full ivy:port" notation'() {
-		when:
-			String response = RestAssuredMockMvc.get('/stubs').body.asString()
-		then:
-			def root = new JsonSlurper().parseText(response)
-			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
-	}
-
-	def 'should return a port on which a [#stubId] stub is running'() {
-		when:
-			def response = RestAssuredMockMvc.get("/stubs/${stubId}")
-		then:
-			response.statusCode == 200
-			Integer.valueOf(response.body.asString()) > 0
-		where:
-			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
-					   'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
-					   'org.springframework.cloud.contract.verifier.stubs:bootService:+',
-					   'org.springframework.cloud.contract.verifier.stubs:bootService',
-					   'bootService']
-	}
-
-	def 'should return 404 when missing stub was called'() {
-		when:
-			def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
-		then:
-			response.statusCode == 404
-	}
-
-	def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
-		when:
-			String response = RestAssuredMockMvc.get('/triggers').body.asString()
-		then:
-			def root = new JsonSlurper().parseText(response)
-			root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
-	}
-
-	def 'should trigger a messaging label'() {
-		given:
-			StubRunning stubRunning = Mock()
-			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
-		when:
-			def response = RestAssuredMockMvc.post("/triggers/delete_book")
-		then:
-			response.statusCode == 200
-		and:
-			1 * stubRunning.trigger('delete_book')
-	}
-
-	def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
-		given:
-			StubRunning stubRunning = Mock()
-			RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
-		when:
-			def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
-		then:
-			response.statusCode == 200
-		and:
-			1 * stubRunning.trigger(stubId, 'delete_book')
-		where:
-			stubId << ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
-	}
-
-	def 'should throw exception when trigger is missing'() {
-		when:
-			RestAssuredMockMvc.post("/triggers/missing_label")
-		then:
-			Exception e = thrown(Exception)
-			e.message.contains("Exception occurred while trying to return [missing_label] label.")
-			e.message.contains("Available labels are")
-			e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
-			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
-	}
-
-}
-
-
-
-
-

Stub Runner Boot with Service Discovery

-
-

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? - Let’s assume that you don’t want to deploy 50 microservice to a test environment in order - to check if your application is working fine. You’ve already executed a suite of tests during the build process - but you would also like to ensure that the packaging of your application is fine. What you can do - is to deploy your application to an environment, start it and run a couple of tests on it to see if - it’s working fine. We can call those tests smoke-tests since their idea is to check only a handful - of testing scenarios.

-
-
-

The problem with this approach is such that if you’re doing microservices most likely you’re - using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the - required stubs and register them in a service discovery tool. Let’s take a look at an example of - such a setup with Eureka. Let’s assume that Eureka was already running.

-
-
-
-
@SpringBootApplication
-@EnableStubRunnerServer
-@EnableEurekaClient
-@AutoConfigureStubRunner
-public class StubRunnerBootEurekaExample {
-
-	public static void main(String[] args) {
-		SpringApplication.run(StubRunnerBootEurekaExample.class, args);
-	}
-
-}
-
-
-
-

As you can see we want to start a Stub Runner Boot server @EnableStubRunnerServer, enable Eureka client @EnableEurekaClient -and we want to have the stub runner feature turned on @AutoConfigureStubRunner.

-
-
-

Now let’s assume that we want to start this application so that the stubs get automatically registered. - We can do it by running the app java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar where - ${SYSTEM_PROPS} would contain the following list of properties

-
-
-
-
* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
-* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
-* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
-* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
-* cloud.contract.verifier.stubs:bootService (3)
-* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
-* someNameThatShouldMapFraudDetectionServer (4)
-*
-* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
-* behaviour where the discovery service is stubbed. That's why the stub registration will
-* be picked (3) - we provide a list of stubs to download (4) - we provide a list of
-
-
-
-

That way your deployed application can send requests to started WireMock servers via the service -discovery. Most likely points 1-3 could be set by default in application.yml cause they are not -likely to change. That way you can provide only the list of stubs to download whenever you start -the Stub Runner Boot.

-
-
-
-
-

Stubs Per Consumer

-
-

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

-
-
- - - - - -
- - -This approach also allows you to immediately know which consumer is using which part of your API. -You can remove part of a response that your API produces and you can see which of your autogenerated tests -fails. If none fails then you can safely delete that part of the response cause nobody is using it. -
-
-
-

Let’s look at the following example for contract defined for the producer called producer. -There are 2 consumers: foo-consumer and bar-consumer.

-
-
-

Consumer foo-service

-
-
-
-
request {
-   url '/foo'
-   method GET()
-}
-response {
-    status OK()
-    body(
-       foo: "foo"
-    }
-}
-
-
-
-

Consumer bar-service

-
-
-
-
request {
-   url '/foo'
-   method GET()
-}
-response {
-    status OK()
-    body(
-       bar: "bar"
-    }
-}
-
-
-
-

You can’t produce for the same request 2 different responses. That’s why you can properly package the -contracts and then profit from the stubsPerConsumer feature.

-
-
-

On the producer side the consumers can have a folder that contains contracts related only to them. -By setting the stubrunner.stubs-per-consumer flag to true we no longer register all stubs but only those that -correspond to the consumer application’s name. In other words we’ll scan the path of every stub and -if it contains the subfolder with name of the consumer in the path only then will it get registered.

-
-
-

On the foo producer side the contracts would look like this

-
-
-
-
.
-└── contracts
-    ├── bar-consumer
-    │   ├── bookReturnedForBar.groovy
-    │   └── shouldCallBar.groovy
-    └── foo-consumer
-        ├── bookReturnedForFoo.groovy
-        └── shouldCallFoo.groovy
-
-
-
-

Being the bar-consumer consumer you can either set the spring.application.name or the stubrunner.consumer-name to bar-consumer -Or set the test as follows:

-
-
-
-
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
-@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
-@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
-		repositoryRoot = "classpath:m2repo/repository/",
-		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-		stubsPerConsumer = true)
-class StubRunnerStubsPerConsumerSpec extends Specification {
-...
-}
-
-
-
-

Then only the stubs registered under a path that contains the bar-consumer in its name (i.e. those from the -src/test/resources/contracts/bar-consumer/some/contracts/…​ folder) will be allowed to be referenced.

-
-
-

Or set the consumer name explicitly

-
-
-
-
@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
-@SpringBootTest
-@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
-		repositoryRoot = "classpath:m2repo/repository/",
-		consumerName = "foo-consumer",
-		stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-		stubsPerConsumer = true)
-class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
-...
-}
-
-
-
-

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the -src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

-
-
-

You can check out issue 224 for more -information about the reasons behind this change.

-
-
-
-

Common

-
-

This section briefly describes common properties, including:

-
- -
-

Common Properties for JUnit and Spring

-
-

You can set repetitive properties by using system properties or Spring configuration -properties. Here are their names with their default values:

-
- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with -stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with -stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for -each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to -override the consumer name just change this value.

-
-
-

Stub Runner Stubs IDs

-
-

You can provide the stubs to download via the stubrunner.ids system property. They -follow this pattern:

-
-
-
-
groupId:artifactId:version:classifier:port
-
-
-
-

Note that version, classifier and port are optional.

-
-
-
    -
  • -

    If you do not provide the port, a random one will be picked.

    -
  • -
  • -

    If you do not provide the classifier, the default is used. (Note that you can -pass an empty classifier this way: groupId:artifactId:version:).

    -
  • -
  • -

    If you do not provide the version, then the + will be passed and the latest one is -downloaded.

    -
  • -
-
-
-

port means the port of the WireMock server.

-
-
- - - - - -
- - -Starting with version 1.0.4, you can provide a range of versions that you -would like the Stub Runner to take into consideration. You can read more about the -Aether versioning -ranges here. -
-
-
-
-
-

Stub Runner Docker

-
-

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image -that will start the standalone version of Stub Runner.

-
-
-

If you want to learn more about the basics of Maven, artifact ids, -group ids, classifiers and Artifact Managers, just click here Docker Project.

-
-
-

How to use it

-
-

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring -as environment variables. The convention is that all the -letters should be upper case. The camel case notation should -and the dot (.) should be separated via underscore (_). E.g. - the stubrunner.repositoryRoot property should be represented - as a STUBRUNNER_REPOSITORY_ROOT environment variable.

-
-
-
-

Example of client side usage in a non JVM project

-
-

We’d like to use the stubs created in this Server side (nodejs) step. -Let’s assume that we want to run the stubs on port 9876. The NodeJS code -is available here:

-
-
-
-
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
-$ cd bookstore
-
-
-
-

Let’s run the Stub Runner Boot application with the stubs.

-
-
-
-
# Provide the Spring Cloud Contract Docker version
-$ SC_CONTRACT_DOCKER_VERSION="..."
-# The IP at which the app is running and Docker container can reach it
-$ APP_IP="192.168.0.100"
-# Spring Cloud Contract Stub Runner properties
-$ STUBRUNNER_PORT="8083"
-# Stub coordinates 'groupId:artifactId:version:classifier:port'
-$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
-$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
-# Run the docker with Stub Runner Boot
-$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
-
-
-
-

What’s happening is that

-
-
-
    -
  • -

    a standalone Stub Runner application got started

    -
  • -
  • -

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    -
  • -
  • -

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    -
  • -
  • -

    after a while Stub Runner will be running on port 8083

    -
  • -
  • -

    and the stubs will be running at port 9876

    -
  • -
-
-
-

On the server side we built a stateful stub. Let’s use curl to assert -that the stubs are setup properly.

-
-
-
-
# let's execute the first request (no response is returned)
-$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
-# Now time for the second request
-$ curl -X GET http://localhost:9876/api/books
-# You will receive contents of the JSON
-
-
-
- - - - - -
- - -If you want use the stubs that you have built locally, on your host, -then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount -the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" -
-
-
-
-
-
-
-

Stub Runner for Messaging

-
-
-

Stub Runner can run the published stubs in memory. It can integrate with the following -frameworks:

-
-
-
    -
  • -

    Spring Integration

    -
  • -
  • -

    Spring Cloud Stream

    -
  • -
  • -

    Apache Camel

    -
  • -
  • -

    Spring AMQP

    -
  • -
-
-
-

It also provides entry points to integrate with any other solution on the market.

-
-
- - - - - -
- - -If you have multiple frameworks on the classpath Stub Runner will need to -define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration -on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. -That way the only remaining framework is Spring AMQP. -
-
-
-

Stub triggering

-
-

To trigger a message, use the StubTrigger interface:

-
-
-
-
package org.springframework.cloud.contract.stubrunner;
-
-import java.util.Collection;
-import java.util.Map;
-
-/**
- * Contract for triggering stub messages.
- *
- * @author Marcin Grzejszczak
- */
-public interface StubTrigger {
-
-	/**
-	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
-	 * You can use only {@code artifactId} too.
-	 *
-	 * Feature related to messaging.
-	 * @param ivyNotation ivy notation of a stub
-	 * @param labelName name of the label to trigger
-	 * @return true - if managed to run a trigger
-	 */
-	boolean trigger(String ivyNotation, String labelName);
-
-	/**
-	 * Triggers an event by a given label.
-	 *
-	 * Feature related to messaging.
-	 * @param labelName name of the label to trigger
-	 * @return true - if managed to run a trigger
-	 */
-	boolean trigger(String labelName);
-
-	/**
-	 * Triggers all possible events.
-	 *
-	 * Feature related to messaging.
-	 * @return true - if managed to run a trigger
-	 */
-	boolean trigger();
-
-	/**
-	 * Feature related to messaging.
-	 * @return a mapping of ivy notation of a dependency to all the labels it has.
-	 */
-	Map<String, Collection<String>> labels();
-
-}
-
-
-
-

For convenience, the StubFinder interface extends StubTrigger, so you only need one -or the other in your tests.

-
-
-

StubTrigger gives you the following options to trigger a message:

-
- -
-

Trigger by Label

-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-
-

Trigger by Group and Artifact Ids

-
-
-
stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')
-
-
-
-
-

Trigger by Artifact Ids

-
-
-
stubFinder.trigger('streamService', 'return_book_1')
-
-
-
-
-

Trigger All Messages

-
-
-
stubFinder.trigger()
-
-
-
-
-
-

Stub Runner Camel

-
-

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. -For the provided artifacts it will automatically download the stubs and register the required -routes.

-
-
-

Adding it to the project

-
-

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with @AutoConfigureStubRunner.

-
-
-
-

Disabling the functionality

-
-

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

-
-
-
-

Examples

-
-
Stubs structure
-
-

Let us assume that we have the following Maven repository with a deployed stubs for the -camelService application.

-
-
-
-
└── .m2
-    └── repository
-        └── io
-            └── codearte
-                └── accurest
-                    └── stubs
-                        └── camelService
-                            ├── 0.0.1-SNAPSHOT
-                            │   ├── camelService-0.0.1-SNAPSHOT.pom
-                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
-                            │   └── maven-metadata-local.xml
-                            └── maven-metadata-local.xml
-
-
-
-

And the stubs contain the following structure:

-
-
-
-
├── META-INF
-│   └── MANIFEST.MF
-└── repository
-    ├── accurest
-    │   ├── bookDeleted.groovy
-    │   ├── bookReturned1.groovy
-    │   └── bookReturned2.groovy
-    └── mappings
-
-
-
-

Let’s consider the following contracts (let' number it with 1):

-
-
-
-
Contract.make {
-	label 'return_book_1'
-	input {
-		triggeredBy('bookReturnedTriggered()')
-	}
-	outputMessage {
-		sentTo('jms:output')
-		body('''{ "bookName" : "foo" }''')
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-

and number 2

-
-
-
-
Contract.make {
-	label 'return_book_2'
-	input {
-		messageFrom('jms:input')
-		messageBody([
-				bookName: 'foo'
-		])
-		messageHeaders {
-			header('sample', 'header')
-		}
-	}
-	outputMessage {
-		sentTo('jms:output')
-		body([
-				bookName: 'foo'
-		])
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-
-
Scenario 1 (no input message)
-
-

So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-

Next we’ll want to listen to the output of the message sent to jms:output

-
-
-
-
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
-
-
-
-

And the received message would pass the following assertions

-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
-receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 2 (output triggered by input)
-
-

Since the route is set for you it’s enough to just send a message to the jms:output destination.

-
-
-
-
producerTemplate.
-		sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])
-
-
-
-

Next we’ll want to listen to the output of the message sent to jms:output

-
-
-
-
Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)
-
-
-
-

And the received message would pass the following assertions

-
-
-
-
receivedMessage != null
-assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
-receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 3 (input with no output)
-
-

Since the route is set for you it’s enough to just send a message to the jms:output destination.

-
-
-
-
producerTemplate.
-		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])
-
-
-
-
-
-
-

Stub Runner Integration

-
-

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to -integrate with Spring Integration. For the provided artifacts, it automatically downloads -the stubs and registers the required routes.

-
-
-

Adding the Runner to the Project

-
-

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

-
-
-
-

Disabling the functionality

-
-

If you need to disable this functionality, set the -stubrunner.integration.enabled=false property.

-
-
-

Assume that you have the following Maven repository with deployed stubs for the -integrationService application:

-
-
-
-
└── .m2
-    └── repository
-        └── io
-            └── codearte
-                └── accurest
-                    └── stubs
-                        └── integrationService
-                            ├── 0.0.1-SNAPSHOT
-                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
-                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
-                            │   └── maven-metadata-local.xml
-                            └── maven-metadata-local.xml
-
-
-
-

Further assume the stubs contain the following structure:

-
-
-
-
├── META-INF
-│   └── MANIFEST.MF
-└── repository
-    ├── accurest
-    │   ├── bookDeleted.groovy
-    │   ├── bookReturned1.groovy
-    │   └── bookReturned2.groovy
-    └── mappings
-
-
-
-

Consider the following contracts (numbered 1):

-
-
-
-
Contract.make {
-	label 'return_book_1'
-	input {
-		triggeredBy('bookReturnedTriggered()')
-	}
-	outputMessage {
-		sentTo('output')
-		body('''{ "bookName" : "foo" }''')
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-

Now consider 2:

-
-
-
-
Contract.make {
-	label 'return_book_2'
-	input {
-		messageFrom('input')
-		messageBody([
-				bookName: 'foo'
-		])
-		messageHeaders {
-			header('sample', 'header')
-		}
-	}
-	outputMessage {
-		sentTo('output')
-		body([
-				bookName: 'foo'
-		])
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-

and the following Spring Integration Route:

-
-
-
-
<?xml version="1.0" encoding="UTF-8"?>
-<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-			 xmlns:beans="http://www.springframework.org/schema/beans"
-			 xmlns="http://www.springframework.org/schema/integration"
-			 xsi:schemaLocation="http://www.springframework.org/schema/beans
-			https://www.springframework.org/schema/beans/spring-beans.xsd
-			http://www.springframework.org/schema/integration
-			http://www.springframework.org/schema/integration/spring-integration.xsd">
-
-
-	<!-- REQUIRED FOR TESTING -->
-	<bridge input-channel="output"
-			output-channel="outputTest"/>
-
-	<channel id="outputTest">
-		<queue/>
-	</channel>
-
-</beans:beans>
-
-
-
-

These examples lend themselves to three scenarios:

-
- -
-
Scenario 1 (no input message)
-
-

To trigger a message via the return_book_1 label, use the StubTigger interface, as -follows:

-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-

To listen to the output of the message sent to output:

-
-
-
-
Message<?> receivedMessage = messaging.receive('outputTest')
-
-
-
-

The received message would pass the following assertions:

-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 2 (output triggered by input)
-
-

Since the route is set for you, you can send a message to the output -destination:

-
-
-
-
messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')
-
-
-
-

To listen to the output of the message sent to output:

-
-
-
-
Message<?> receivedMessage = messaging.receive('outputTest')
-
-
-
-

The received message passes the following assertions:

-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 3 (input with no output)
-
-

Since the route is set for you, you can send a message to the input destination:

-
-
-
-
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
-
-
-
-
-
-
-

Stub Runner Stream

-
-

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to -integrate with Spring Stream. For the provided artifacts, it automatically downloads the -stubs and registers the required routes.

-
-
- - - - - -
- - -If Stub Runner’s integration with Stream the messageFrom or sentTo Strings -are resolved first as a destination of a channel and no such destination exists, the -destination is resolved as a channel name. -
-
-
- - - - - -
- - -If you want to use Spring Cloud Stream remember, to add a dependency on -org.springframework.cloud:spring-cloud-stream-test-support. -
-
-
-
Maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-stream-test-support</artifactId>
-    <scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
-
-
-
-

Adding the Runner to the Project

-
-

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

-
-
-
-

Disabling the functionality

-
-

If you need to disable this functionality, set the stubrunner.stream.enabled=false -property.

-
-
-

Assume that you have the following Maven repository with a deployed stubs for the -streamService application:

-
-
-
-
└── .m2
-    └── repository
-        └── io
-            └── codearte
-                └── accurest
-                    └── stubs
-                        └── streamService
-                            ├── 0.0.1-SNAPSHOT
-                            │   ├── streamService-0.0.1-SNAPSHOT.pom
-                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
-                            │   └── maven-metadata-local.xml
-                            └── maven-metadata-local.xml
-
-
-
-

Further assume the stubs contain the following structure:

-
-
-
-
├── META-INF
-│   └── MANIFEST.MF
-└── repository
-    ├── accurest
-    │   ├── bookDeleted.groovy
-    │   ├── bookReturned1.groovy
-    │   └── bookReturned2.groovy
-    └── mappings
-
-
-
-

Consider the following contracts (numbered 1):

-
-
-
-
Contract.make {
-	label 'return_book_1'
-	input { triggeredBy('bookReturnedTriggered()') }
-	outputMessage {
-		sentTo('returnBook')
-		body('''{ "bookName" : "foo" }''')
-		headers { header('BOOK-NAME', 'foo') }
-	}
-}
-
-
-
-

Now consider 2:

-
-
-
-
Contract.make {
-	label 'return_book_2'
-	input {
-		messageFrom('bookStorage')
-		messageBody([
-				bookName: 'foo'
-		])
-		messageHeaders { header('sample', 'header') }
-	}
-	outputMessage {
-		sentTo('returnBook')
-		body([
-				bookName: 'foo'
-		])
-		headers { header('BOOK-NAME', 'foo') }
-	}
-}
-
-
-
-

Now consider the following Spring configuration:

-
-
-
-
stubrunner.repositoryRoot: classpath:m2repo/repository/
-stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
-stubrunner.stubs-mode: remote
-spring:
-  cloud:
-    stream:
-      bindings:
-        output:
-          destination: returnBook
-        input:
-          destination: bookStorage
-
-server:
-  port: 0
-
-debug: true
-
-
-
-

These examples lend themselves to three scenarios:

-
- -
-
Scenario 1 (no input message)
-
-

To trigger a message via the return_book_1 label, use the StubTrigger interface as -follows:

-
-
-
-
stubFinder.trigger('return_book_1')
-
-
-
-

To listen to the output of the message sent to a channel whose destination is -returnBook:

-
-
-
-
Message<?> receivedMessage = messaging.receive('returnBook')
-
-
-
-

The received message passes the following assertions:

-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 2 (output triggered by input)
-
-

Since the route is set for you, you can send a message to the bookStorage -destination:

-
-
-
-
messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')
-
-
-
-

To listen to the output of the message sent to returnBook:

-
-
-
-
Message<?> receivedMessage = messaging.receive('returnBook')
-
-
-
-

The received message passes the following assertions:

-
-
-
-
receivedMessage != null
-assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'
-
-
-
-
-
Scenario 3 (input with no output)
-
-

Since the route is set for you, you can send a message to the output -destination:

-
-
-
-
messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')
-
-
-
-
-
-
-

Stub Runner Spring AMQP

-
-

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to -integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it -automatically downloads the stubs and registers the required routes.

-
-
-

The integration tries to work standalone (that is, without interaction with a running -RabbitMQ message broker). It expects a RabbitTemplate on the application context and -uses it as a spring boot test named @SpyBean. As a result, it can use the mockito spy -functionality to verify and inspect messages sent by the application.

-
-
-

On the message consumer side, the stub runner considers all @RabbitListener annotated -endpoints and all SimpleMessageListenerContainer objects on the application context.

-
-
-

As messages are usually sent to exchanges in AMQP, the message contract contains the -exchange name as the destination. Message listeners on the other side are bound to -queues. Bindings connect an exchange to a queue. If message contracts are triggered, the -Spring AMQP stub runner integration looks for bindings on the application context that -match this exchange. Then it collects the queues from the Spring exchanges and tries to -find message listeners bound to these queues. The message is triggered for all matching -message listeners.

-
-
-

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey -messaging header.

-
-
-

Adding the Runner to the Project

-
-

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and -set the property stubrunner.amqp.enabled=true. Remember to annotate your test class -with @AutoConfigureStubRunner.

-
-
- - - - - -
- - -If you already have Stream and Integration on the classpath, you need -to disable them explicitly by setting the stubrunner.stream.enabled=false and -stubrunner.integration.enabled=false properties. -
-
-
-

Assume that you have the following Maven repository with a deployed stubs for the -spring-cloud-contract-amqp-test application.

-
-
-
-
└── .m2
-    └── repository
-        └── com
-            └── example
-                └── spring-cloud-contract-amqp-test
-                    ├── 0.4.0-SNAPSHOT
-                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
-                    │   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
-                    │   └── maven-metadata-local.xml
-                    └── maven-metadata-local.xml
-
-
-
-

Further assume that the stubs contain the following structure:

-
-
-
-
├── META-INF
-│   └── MANIFEST.MF
-└── contracts
-    └── shouldProduceValidPersonData.groovy
-
-
-
-

Consider the following contract:

-
-
-
-
Contract.make {
-	// Human readable description
-	description 'Should produce valid person data'
-	// Label by means of which the output message can be triggered
-	label 'contract-test.person.created.event'
-	// input to the contract
-	input {
-		// the contract will be triggered by a method
-		triggeredBy('createPerson()')
-	}
-	// output message of the contract
-	outputMessage {
-		// destination to which the output message will be sent
-		sentTo 'contract-test.exchange'
-		headers {
-			header('contentType': 'application/json')
-			header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
-		}
-		// the body of the output message
-		body([
-				id  : $(consumer(9), producer(regex("[0-9]+"))),
-				name: "me"
-		])
-	}
-}
-
-
-
-

Now consider the following Spring configuration:

-
-
-
-
stubrunner:
-  repositoryRoot: classpath:m2repo/repository/
-  ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
-  stubs-mode: remote
-  amqp:
-    enabled: true
-server:
-  port: 0
-
-
-
-
Triggering the message
-
-

To trigger a message using the contract above, use the StubTrigger interface as -follows:

-
-
-
-
stubTrigger.trigger("contract-test.person.created.event")
-
-
-
-

The message has a destination of contract-test.exchange, so the Spring AMQP stub runner -integration looks for bindings related to this exchange.

-
-
-
-
@Bean
-public Binding binding() {
-	return BindingBuilder.bind(new Queue("test.queue"))
-			.to(new DirectExchange("contract-test.exchange")).with("#");
-}
-
-
-
-

The binding definition binds the queue test.queue. As a result, the following listener -definition is matched and invoked with the contract message.

-
-
-
-
@Bean
-public SimpleMessageListenerContainer simpleMessageListenerContainer(
-		ConnectionFactory connectionFactory,
-		MessageListenerAdapter listenerAdapter) {
-	SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
-	container.setConnectionFactory(connectionFactory);
-	container.setQueueNames("test.queue");
-	container.setMessageListener(listenerAdapter);
-
-	return container;
-}
-
-
-
-

Also, the following annotated listener matches and is invoked:

-
-
-
-
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
-		exchange = @Exchange(value = "contract-test.exchange",
-				ignoreDeclarationExceptions = "true")))
-public void handlePerson(Person person) {
-	this.person = person;
-}
-
-
-
- - - - - -
- - -The message is directly handed over to the onMessage method of the -MessageListener associated with the matching SimpleMessageListenerContainer. -
-
-
-
-
Spring AMQP Test Configuration
-
-

In order to avoid Spring AMQP trying to connect to a running broker during our tests -configure a mock ConnectionFactory.

-
-
-

To disable the mocked ConnectionFactory, set the following property: -stubrunner.amqp.mockConnection=false

-
-
-
-
stubrunner:
-  amqp:
-    mockConnection: false
-
-
-
-
-
-
-
-
-

Contract DSL

-
-
-

Spring Cloud Contract supports out of the box 2 types of DSL. One written in -Groovy and one written in YAML.

-
-
-

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy -before. Knowledge of the language is not really needed, as the Contract DSL uses only a -tiny subset of it (only literals, method calls and closures). Also, the DSL is statically -typed, to make it programmer-readable without any knowledge of the DSL itself.

-
-
- - - - - -
- - -Remember that, inside the Groovy contract file, you have to provide the fully -qualified name to the Contract class and make static imports, such as -org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to -the Contract class: import org.springframework.cloud.spec.Contract and then call -Contract.make { …​ }. -
-
-
- - - - - -
- - -Spring Cloud Contract supports defining multiple contracts in a single file. -
-
-
-

The following is a complete example of a Groovy contract definition:

-
-
-
-
-
-
-
-

The following is a complete example of a YAML contract definition:

-
-
-
-
description: Some description
-name: some name
-priority: 8
-ignored: true
-request:
-  url: /foo
-  queryParameters:
-    a: b
-    b: c
-  method: PUT
-  headers:
-    foo: bar
-    fooReq: baz
-  body:
-    foo: bar
-  matchers:
-    body:
-      - path: $.foo
-        type: by_regex
-        value: bar
-    headers:
-      - key: foo
-        regex: bar
-response:
-  status: 200
-  headers:
-    foo2: bar
-    foo3: foo33
-    fooRes: baz
-  body:
-    foo2: bar
-    foo3: baz
-    nullValue: null
-  matchers:
-    body:
-      - path: $.foo2
-        type: by_regex
-        value: bar
-      - path: $.foo3
-        type: by_command
-        value: executeMe($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-    headers:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        command: andMeToo($it)
-
-
-
- - - - - -
- - -You can compile contracts to stubs mapping using standalone maven command: -mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert -
-
-
-

Limitations

-
- - - - - -
- - -Spring Cloud Contract Verifier does not properly support XML. Please use JSON or -help us implement this feature. -
-
-
- - - - - -
- - -The support for verifying the size of JSON arrays is experimental. If you want -to turn it on, please set the value of the following system property to true: -spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. -You can also provide the assertJsonSize property in the plugin configuration. -
-
-
- - - - - -
- - -Because JSON structure can have any form, it can be impossible to parse it -properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That -is why you should use the Groovy Map notation. -
-
-
-
-

Common Top-Level elements

-
-

The following sections describe the most common top-level elements:

-
- -
-

Description

-
-

You can add a description to your contract. The description is arbitrary text. The -following code shows an example:

-
-
-
Groovy DSL
-
-
			org.springframework.cloud.contract.spec.Contract.make {
-				description('''
-given:
-	An input
-when:
-	Sth happens
-then:
-	Output
-''')
-			}
-
-
-
-
YAML
-
-
description: Some description
-name: some name
-priority: 8
-ignored: true
-request:
-  url: /foo
-  queryParameters:
-    a: b
-    b: c
-  method: PUT
-  headers:
-    foo: bar
-    fooReq: baz
-  body:
-    foo: bar
-  matchers:
-    body:
-      - path: $.foo
-        type: by_regex
-        value: bar
-    headers:
-      - key: foo
-        regex: bar
-response:
-  status: 200
-  headers:
-    foo2: bar
-    foo3: foo33
-    fooRes: baz
-  body:
-    foo2: bar
-    foo3: baz
-    nullValue: null
-  matchers:
-    body:
-      - path: $.foo2
-        type: by_regex
-        value: bar
-      - path: $.foo3
-        type: by_command
-        value: executeMe($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-    headers:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        command: andMeToo($it)
-
-
-
-
-

Name

-
-

You can provide a name for your contract. Assume that you provided the following name: -should register a user. If you do so, the name of the autogenerated test is -validate_should_register_a_user. Also, the name of the stub in a WireMock stub is -should_register_a_user.json.

-
-
- - - - - -
- - -You must ensure that the name does not contain any characters that make the -generated test not compile. Also, remember that, if you provide the same name for -multiple contracts, your autogenerated tests fail to compile and your generated stubs -override each other. -
-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	name("some_special_name")
-}
-
-
-
-
YAML
-
-
name: some name
-
-
-
-
-

Ignoring Contracts

-
-

If you want to ignore a contract, you can either set a value of ignored contracts in the -plugin configuration or set the ignored property on the contract itself:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	ignored()
-}
-
-
-
-
YAML
-
-
ignored: true
-
-
-
-
-

Passing Values from Files

-
-

Starting with version 1.2.0, you can pass values from files. Assume that you have the -following resources in our project.

-
-
-
-
└── src
-    └── test
-        └── resources
-            └── contracts
-                ├── readFromFile.groovy
-                ├── request.json
-                └── response.json
-
-
-
-

Further assume that your contract is as follows:

-
-
-
Groovy DSL
-
-
/*
- * Copyright 2013-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-	request {
-		method('PUT')
-		headers {
-			contentType(applicationJson())
-		}
-		body(file("request.json"))
-		url("/1")
-	}
-	response {
-		status OK()
-		body(file("response.json"))
-		headers {
-			contentType(applicationJson())
-		}
-	}
-}
-
-
-
-
YAML
-
-
request:
-  method: GET
-  url: /foo
-  bodyFromFile: request.json
-response:
-  status: 200
-  bodyFromFile: response.json
-
-
-
-

Further assume that the JSON files is as follows:

-
-
-

request.json

-
-
-
-
{
-  "status": "REQUEST"
-}
-
-
-
-

response.json

-
-
-
-
{
-  "status": "RESPONSE"
-}
-
-
-
-

When test or stub generation takes place, the contents of the file is passed to the body -of a request or a response. The name of the file needs to be a file with location -relative to the folder in which the contract lays.

-
-
-

If you need to pass the contents of a file in a binary form -it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

-
-
-
Groovy DSL
-
-
import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-	request {
-		url("/1")
-		method(PUT())
-		headers {
-			contentType(applicationOctetStream())
-		}
-		body(fileAsBytes("request.pdf"))
-	}
-	response {
-		status 200
-		body(fileAsBytes("response.pdf"))
-		headers {
-			contentType(applicationOctetStream())
-		}
-	}
-}
-
-
-
-
YAML
-
-
request:
-  url: /1
-  method: PUT
-  headers:
-    Content-Type: application/octet-stream
-  bodyFromFileAsBytes: request.pdf
-response:
-  status: 200
-  bodyFromFileAsBytes: response.pdf
-  headers:
-    Content-Type: application/octet-stream
-
-
-
- - - - - -
- - -You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. -
-
-
-
-

HTTP Top-Level Elements

-
-

The following methods can be called in the top-level closure of a contract definition. -request and response are mandatory. priority is optional.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	// Definition of HTTP request part of the contract
-	// (this can be a valid request or invalid depending
-	// on type of contract being specified).
-	request {
-		method GET()
-		url "/foo"
-		//...
-	}
-
-	// Definition of HTTP response part of the contract
-	// (a service implementing this contract should respond
-	// with following response after receiving request
-	// specified in "request" part above).
-	response {
-		status 200
-		//...
-	}
-
-	// Contract priority, which can be used for overriding
-	// contracts (1 is highest). Priority is optional.
-	priority 1
-}
-
-
-
-
YAML
-
-
priority: 8
-request:
-...
-response:
-...
-
-
-
- - - - - -
- - -If you want to make your contract have a higher value of priority -you need to pass a lower number to the priority tag / method. E.g. priority with -value 5 has higher priority than priority with value 10. -
-
-
-
-
-

Request

-
-

The HTTP protocol requires only method and url to be specified in a request. The -same information is mandatory in request definition of the Contract.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		// HTTP request method (GET/POST/PUT/DELETE).
-		method 'GET'
-
-		// Path component of request URL is specified as follows.
-		urlPath('/users')
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
method: PUT
-url: /foo
-
-
-
-

It is possible to specify an absolute rather than relative url, but using urlPath is -the recommended way, as doing so makes the tests host-independent.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		method 'GET'
-
-		// Specifying `url` and `urlPath` in one contract is illegal.
-		url('http://localhost:8888/users')
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
request:
-  method: PUT
-  urlPath: /foo
-
-
-
-

request may contain query parameters.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		//...
-		method GET()
-
-		urlPath('/users') {
-
-			// Each parameter is specified in form
-			// `'paramName' : paramValue` where parameter value
-			// may be a simple literal or one of matcher functions,
-			// all of which are used in this example.
-			queryParameters {
-
-				// If a simple literal is used as value
-				// default matcher function is used (equalTo)
-				parameter 'limit': 100
-
-				// `equalTo` function simply compares passed value
-				// using identity operator (==).
-				parameter 'filter': equalTo("email")
-
-				// `containing` function matches strings
-				// that contains passed substring.
-				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
-
-				// `matching` function tests parameter
-				// against passed regular expression.
-				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
-
-				// `notMatching` functions tests if parameter
-				// does not match passed regular expression.
-				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
-			}
-		}
-
-		//...
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
request:
-...
-  queryParameters:
-    a: b
-    b: c
-  headers:
-    foo: bar
-    fooReq: baz
-  cookies:
-    foo: bar
-    fooReq: baz
-  body:
-    foo: bar
-  matchers:
-    body:
-      - path: $.foo
-        type: by_regex
-        value: bar
-    headers:
-      - key: foo
-        regex: bar
-response:
-  status: 200
-  fixedDelayMilliseconds: 1000
-  headers:
-    foo2: bar
-    foo3: foo33
-    fooRes: baz
-  body:
-    foo2: bar
-    foo3: baz
-    nullValue: null
-  matchers:
-    body:
-      - path: $.foo2
-        type: by_regex
-        value: bar
-      - path: $.foo3
-        type: by_command
-        value: executeMe($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-    headers:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        command: andMeToo($it)
-    cookies:
-      - key: foo2
-        regex: bar
-      - key: foo3
-        predefined:
-
-
-
-

request may contain additional request headers, as shown in the following example:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		//...
-		method GET()
-		url "/foo"
-
-		// Each header is added in form `'Header-Name' : 'Header-Value'`.
-		// there are also some helper methods
-		headers {
-			header 'key': 'value'
-			contentType(applicationJson())
-		}
-
-		//...
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
request:
-...
-headers:
-  foo: bar
-  fooReq: baz
-
-
-
-

request may contain additional request cookies, as shown in the following example:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		//...
-		method GET()
-		url "/foo"
-
-		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
-		// there are also some helper methods
-		cookies {
-			cookie 'key': 'value'
-			cookie('another_key', 'another_value')
-		}
-
-		//...
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
request:
-...
-cookies:
-  foo: bar
-  fooReq: baz
-
-
-
-

request may contain a request body:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		//...
-		method GET()
-		url "/foo"
-
-		// Currently only JSON format of request body is supported.
-		// Format will be determined from a header or body's content.
-		body '''{ "login" : "john", "name": "John The Contract" }'''
-	}
-
-	response {
-		//...
-		status 200
-	}
-}
-
-
-
-
YAML
-
-
request:
-...
-body:
-  foo: bar
-
-
-
-

request may contain multipart elements. To include multipart elements, use the -multipart method/section, as shown in the following examples

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
request:
-  method: PUT
-  url: /multipart
-  headers:
-    Content-Type: multipart/form-data;boundary=AaB03x
-  multipart:
-    params:
-      # key (parameter name), value (parameter value) pair
-      formParameter: '"formParameterValue"'
-      someBooleanParameter: true
-    named:
-      - paramName: file
-        fileName: filename.csv
-        fileContent: file content
-  matchers:
-    multipart:
-      params:
-        - key: formParameter
-          regex: ".+"
-        - key: someBooleanParameter
-          predefined: any_boolean
-      named:
-        - paramName: file
-          fileName:
-            predefined: non_empty
-          fileContent:
-            predefined: non_empty
-response:
-  status: 200
-
-
-
-

In the preceding example, we define parameters in either of two ways:

-
-
-
Groovy DSL
-
    -
  • -

    Directly, by using the map notation, where the value can be a dynamic property (such as -formParameter: $(consumer(…​), producer(…​))).

    -
  • -
  • -

    By using the named(…​) method that lets you set a named parameter. A named parameter -can set a name and content. You can call it either via a method with two arguments, -such as named("fileName", "fileContent"), or via a map notation, such as -named(name: "fileName", content: "fileContent").

    -
  • -
-
-
-
YAML
-
    -
  • -

    The multipart parameters are set via multipart.params section

    -
  • -
  • -

    The named parameters (the fileName and fileContent for a given parameter name) -can be set via the multipart.named section. That section contains -the paramName (name of the parameter), fileName (name of the file), -fileContent (content of the file) fields

    -
  • -
  • -

    The dynamic bits can be set via the matchers.multipart section

    -
    -
      -
    • -

      for parameters use the params section that can accept -regex or a predefined regular expression

      -
    • -
    • -

      for named params use the named section where first you -define the parameter name via paramName and then you can pass the -parametrization of either fileName or fileContent via -regex or a predefined regular expression

      -
    • -
    -
    -
  • -
-
-
-

From this contract, the generated test is as follows:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
-   .param("formParameter", "\"formParameterValue\"")
-   .param("someBooleanParameter", "true")
-   .multiPart("file", "filename.csv", "file content".getBytes());
-
-// when:
- ResponseOptions response = given().spec(request)
-   .put("/multipart");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-

The WireMock stub is as follows:

-
-
-
-
			'''
-{
-  "request" : {
-	"url" : "/multipart",
-	"method" : "PUT",
-	"headers" : {
-	  "Content-Type" : {
-		"matches" : "multipart/form-data;boundary=AaB03x.*"
-	  }
-	},
-	"bodyPatterns" : [ {
-		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
-  		}, {
-    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
-  		}, {
-	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
-	} ]
-  },
-  "response" : {
-	"status" : 200,
-	"transformers" : [ "response-template", "foo-transformer" ]
-  }
-}
-	'''
-
-
-
-
-

Response

-
-

The response must contain an HTTP status code and may contain other information. The -following code shows an example:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		//...
-		method GET()
-		url "/foo"
-	}
-	response {
-		// Status code sent by the server
-		// in response to request specified above.
-		status OK()
-	}
-}
-
-
-
-
YAML
-
-
response:
-...
-status: 200
-
-
-
-

Besides status, the response may contain headers, cookies and a body, both of which are -specified the same way as in the request (see the previous paragraph).

-
-
- - - - - -
- - -Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus -methods to provide a meaningful status instead of a digit. E.g. you can call -OK() for a status 200 or BAD_REQUEST() for 400. -
-
-
-
-

Dynamic properties

-
-

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not -want to force the consumers to stub their clocks to always return the same value of time -so that it gets matched by the stub.

-
-
-

For Groovy DSL you can provide the dynamic parts in your contracts -in two ways: pass them directly in the body or set them in a separate section called -bodyMatchers.

-
-
- - - - - -
- - -Before 2.0.0 these were set using testMatchers and stubMatchers, -check out the migration guide for more information. -
-
-
-

For YAML you can only use the matchers section.

-
-
-

Dynamic properties inside the body

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can set the properties inside the body either with the value method or, if you use -the Groovy map notation, with $(). The following example shows how to set dynamic -properties with the value method:

-
-
-
-
value(consumer(...), producer(...))
-value(c(...), p(...))
-value(stub(...), test(...))
-value(client(...), server(...))
-
-
-
-

The following example shows how to set dynamic properties with $():

-
-
-
-
$(consumer(...), producer(...))
-$(c(...), p(...))
-$(stub(...), test(...))
-$(client(...), server(...))
-
-
-
-

Both approaches work equally well. stub and client methods are aliases over the consumer -method. Subsequent sections take a closer look at what you can do with those values.

-
-
-
-

Regular expressions

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can use regular expressions to write your requests in Contract DSL. Doing so is -particularly useful when you want to indicate that a given response should be provided -for requests that follow a given pattern. Also, you can use regular expressions when you -need to use patterns and not exact values both for your test and your server side tests.

-
-
-

Make sure that regex matches a whole region of a sequence as internally a call to -Pattern.matches() -is called. For instance, abc pattern doesn’t match aabc string but .abc does. -There are several additional known limitations as well.

-
-
-

The following example shows how to use regular expressions to write a request:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		method('GET')
-		url $(consumer(~/\/[0-9]{2}/), producer('/12'))
-	}
-	response {
-		status OK()
-		body(
-				id: $(anyNumber()),
-				surname: $(
-						consumer('Kowalsky'),
-						producer(regex('[a-zA-Z]+'))
-				),
-				name: 'Jan',
-				created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
-				correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
-						producer(regex('[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}'))
-				)
-		)
-		headers {
-			header 'Content-Type': 'text/plain'
-		}
-	}
-}
-
-
-
-

You can also provide only one side of the communication with a regular expression. If you -do so, then the contract engine automatically provides the generated string that matches -the provided regular expression. The following code shows an example:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		method 'PUT'
-		url value(consumer(regex('/foo/[0-9]{5}')))
-		body([
-				requestElement: $(consumer(regex('[0-9]{5}')))
-		])
-		headers {
-			header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
-		}
-	}
-	response {
-		status OK()
-		body([
-				responseElement: $(producer(regex('[0-9]{7}')))
-		])
-		headers {
-			contentType("application/vnd.fraud.v1+json")
-		}
-	}
-}
-
-
-
-

In the preceding example, the opposite side of the communication has the respective data -generated for request and response.

-
-
-

Spring Cloud Contract comes with a series of predefined regular expressions that you can -use in your contracts, as shown in the following example:

-
-
-
-
protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
-
-protected static final Pattern ALPHA_NUMERIC = Pattern.compile("[a-zA-Z0-9]+");
-
-protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile("[\\p{L}]*");
-
-protected static final Pattern NUMBER = Pattern.compile("-?(\\d*\\.\\d+|\\d+)");
-
-protected static final Pattern INTEGER = Pattern.compile("-?(\\d+)");
-
-protected static final Pattern POSITIVE_INT = Pattern.compile("([1-9]\\d*)");
-
-protected static final Pattern DOUBLE = Pattern.compile("-?(\\d*\\.\\d+)");
-
-protected static final Pattern HEX = Pattern.compile("[a-fA-F0-9]+");
-
-protected static final Pattern IP_ADDRESS = Pattern.compile(
-		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
-
-protected static final Pattern HOSTNAME_PATTERN = Pattern
-		.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
-
-protected static final Pattern EMAIL = Pattern
-		.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
-
-protected static final Pattern URL = UrlHelper.URL;
-
-protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
-
-protected static final Pattern UUID = Pattern
-		.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
-
-protected static final Pattern ANY_DATE = Pattern
-		.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
-
-protected static final Pattern ANY_DATE_TIME = Pattern.compile(
-		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
-
-protected static final Pattern ANY_TIME = Pattern
-		.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
-
-protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
-
-protected static final Pattern NON_BLANK = Pattern.compile("^\\s*\\S[\\S\\s]*");
-
-protected static final Pattern ISO8601_WITH_OFFSET = Pattern.compile(
-		"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d{3})?(Z|[+-][01]\\d:[0-5]\\d)");
-
-protected static Pattern anyOf(String... values) {
-	return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$')
-			.collect(Collectors.joining("|")));
-}
-
-public static String multipartParam(Object name, Object value) {
-	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
-			+ "\"\r\n(Content-Type: .*\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
-			+ value + "\r\n--\\1.*";
-}
-
-public static String multipartFile(Object name, Object filename, Object content,
-		Object contentType) {
-	return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
-			+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
-			+ toContentType(contentType)
-			+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
-			+ content + "\r\n--\\1.*";
-}
-
-private static String toContentType(Object contentType) {
-	if (contentType == null) {
-		return ".*";
-	}
-	if (contentType instanceof RegexProperty) {
-		return ((RegexProperty) contentType).pattern();
-	}
-	return contentType.toString();
-}
-
-public RegexProperty onlyAlphaUnicode() {
-	return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
-}
-
-public RegexProperty alphaNumeric() {
-	return new RegexProperty(ALPHA_NUMERIC).asString();
-}
-
-public RegexProperty number() {
-	return new RegexProperty(NUMBER).asDouble();
-}
-
-public RegexProperty positiveInt() {
-	return new RegexProperty(POSITIVE_INT).asInteger();
-}
-
-public RegexProperty anyBoolean() {
-	return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
-}
-
-public RegexProperty anInteger() {
-	return new RegexProperty(INTEGER).asInteger();
-}
-
-public RegexProperty aDouble() {
-	return new RegexProperty(DOUBLE).asDouble();
-}
-
-public RegexProperty ipAddress() {
-	return new RegexProperty(IP_ADDRESS).asString();
-}
-
-public RegexProperty hostname() {
-	return new RegexProperty(HOSTNAME_PATTERN).asString();
-}
-
-public RegexProperty email() {
-	return new RegexProperty(EMAIL).asString();
-}
-
-public RegexProperty url() {
-	return new RegexProperty(URL).asString();
-}
-
-public RegexProperty httpsUrl() {
-	return new RegexProperty(HTTPS_URL).asString();
-}
-
-public RegexProperty uuid() {
-	return new RegexProperty(UUID).asString();
-}
-
-public RegexProperty isoDate() {
-	return new RegexProperty(ANY_DATE).asString();
-}
-
-public RegexProperty isoDateTime() {
-	return new RegexProperty(ANY_DATE_TIME).asString();
-}
-
-public RegexProperty isoTime() {
-	return new RegexProperty(ANY_TIME).asString();
-}
-
-
-
-

In your contract, you can use it as shown in the following example:

-
-
-
-
Contract dslWithOptionalsInString = Contract.make {
-	priority 1
-	request {
-		method POST()
-		url '/users/password'
-		headers {
-			contentType(applicationJson())
-		}
-		body(
-				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
-				callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
-		)
-	}
-	response {
-		status 404
-		headers {
-			contentType(applicationJson())
-		}
-		body(
-				code: value(consumer("123123"), producer(optional("123123"))),
-				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
-		)
-	}
-}
-
-
-
-

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. -All of those methods start with any prefix:

-
-
-
-
-
-
-
-

and this is an example of how you can reference those methods:

-
-
-
-
Contract contractDsl = Contract.make {
-	name "foo"
-	label 'trigger_event'
-	input {
-		triggeredBy('toString()')
-	}
-	outputMessage {
-		sentTo 'topic.rateablequote'
-		body([
-				alpha            : $(anyAlphaUnicode()),
-				number           : $(anyNumber()),
-				anInteger        : $(anyInteger()),
-				positiveInt      : $(anyPositiveInt()),
-				aDouble          : $(anyDouble()),
-				aBoolean         : $(aBoolean()),
-				ip               : $(anyIpAddress()),
-				hostname         : $(anyHostname()),
-				email            : $(anyEmail()),
-				url              : $(anyUrl()),
-				httpsUrl         : $(anyHttpsUrl()),
-				uuid             : $(anyUuid()),
-				date             : $(anyDate()),
-				dateTime         : $(anyDateTime()),
-				time             : $(anyTime()),
-				iso8601WithOffset: $(anyIso8601WithOffset()),
-				nonBlankString   : $(anyNonBlankString()),
-				nonEmptyString   : $(anyNonEmptyString()),
-				anyOf            : $(anyOf('foo', 'bar'))
-		])
-	}
-}
-
-
-
-
Limitations
-
- - - - - -
- - -Due to certain limitations of Xeger library that generates string out of -regex, do not use $ and ^ signs in your regex if you rely on automatic -generation. Issue 899 -
-
-
- - - - - -
- - -Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). -It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. -Issue 900 -
-
-
-
-
-

Passing Optional Parameters

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

It is possible to provide optional parameters in your contract. However, you can provide -optional parameters only for the following:

-
-
-
    -
  • -

    STUB side of the Request

    -
  • -
  • -

    TEST side of the Response

    -
  • -
-
-
-

The following example shows how to provide optional parameters:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	priority 1
-	name "optionals"
-	request {
-		method 'POST'
-		url '/users/password'
-		headers {
-			contentType(applicationJson())
-		}
-		body(
-				email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
-				callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
-		)
-	}
-	response {
-		status 404
-		headers {
-			header 'Content-Type': 'application/json'
-		}
-		body(
-				code: value(consumer("123123"), producer(optional("123123")))
-		)
-	}
-}
-
-
-
-

By wrapping a part of the body with the optional() method, you create a regular -expression that must be present 0 or more times.

-
-
-

If you use Spock for, the following test would be generated from the previous example:

-
-
-
-
					"""\
-package com.example
-
-import com.jayway.jsonpath.DocumentContext
-import com.jayway.jsonpath.JsonPath
-import spock.lang.Specification
-import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
-import io.restassured.response.ResponseOptions
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
-import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
-
-@SuppressWarnings("rawtypes")
-class FooSpec extends Specification {
-
-\tdef validate_optionals() throws Exception {
-\t\tgiven:
-\t\t\tMockMvcRequestSpecification request = given()
-\t\t\t\t\t.header("Content-Type", "application/json")
-\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
-
-\t\twhen:
-\t\t\tResponseOptions response = given().spec(request)
-\t\t\t\t\t.post("/users/password")
-
-\t\tthen:
-\t\t\tresponse.statusCode() == 404
-\t\t\tresponse.header("Content-Type") == 'application/json'
-
-\t\tand:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
-\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
-\t}
-
-}
-"""
-
-
-
-

The following stub would also be generated:

-
-
-
-
					'''
-{
-  "request" : {
-	"url" : "/users/password",
-	"method" : "POST",
-	"bodyPatterns" : [ {
-	  "matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
-	}, {
-	  "matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
-	} ],
-	"headers" : {
-	  "Content-Type" : {
-		"equalTo" : "application/json"
-	  }
-	}
-  },
-  "response" : {
-	"status" : 404,
-	"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
-	"headers" : {
-	  "Content-Type" : "application/json"
-	}
-  },
-  "priority" : 1
-}
-'''
-
-
-
-
-

Executing Custom Methods on the Server Side

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can define a method call that executes on the server side during the test. Such a -method can be added to the class defined as "baseClassForTests" in the configuration. The -following code shows an example of the contract portion of the test case:

-
-
-
-
-
-
-
-

The following code shows the base class portion of the test case:

-
-
-
-
abstract class BaseMockMvcSpec extends Specification {
-
-	def setup() {
-		RestAssuredMockMvc.standaloneSetup(new PairIdController())
-	}
-
-	void isProperCorrelationId(Integer correlationId) {
-		assert correlationId == 123456
-	}
-
-	void isEmpty(String value) {
-		assert value == null
-	}
-
-}
-
-
-
- - - - - -
- - -You cannot use both a String and execute to perform concatenation. For -example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to -improper results. Instead, call header('Authorization', execute('authToken()')) and -ensure that the authToken() method returns everything you need. -
-
-
-

The type of the object read from the JSON can be one of the following, depending on the -JSON path:

-
-
-
    -
  • -

    String: If you point to a String value in the JSON.

    -
  • -
  • -

    JSONArray: If you point to a List in the JSON.

    -
  • -
  • -

    Map: If you point to a Map in the JSON.

    -
  • -
  • -

    Number: If you point to Integer, Double etc. in the JSON.

    -
  • -
  • -

    Boolean: If you point to a Boolean in the JSON.

    -
  • -
-
-
-

In the request part of the contract, you can specify that the body should be taken from -a method.

-
-
- - - - - -
- - -You must provide both the consumer and the producer side. The execute part -is applied for the whole body - not for parts of it. -
-
-
-

The following example shows how to read an object from JSON:

-
-
-
-
Contract contractDsl = Contract.make {
-	request {
-		method 'GET'
-		url '/something'
-		body(
-				$(c('foo'), p(execute('hashCode()')))
-		)
-	}
-	response {
-		status OK()
-	}
-}
-
-
-
-

The preceding example results in calling the hashCode() method in the request body. -It should resemble the following code:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .body(hashCode());
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/something");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-
-

Referencing the Request from the Response

-
-

The best situation is to provide fixed values, but sometimes you need to reference a -request in your response.

-
-
-

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets -you reference a bunch of elements from the HTTP request. You can use the following -options:

-
-
-
    -
  • -

    fromRequest().url(): Returns the request URL and query parameters.

    -
  • -
  • -

    fromRequest().query(String key): Returns the first query parameter with a given name.

    -
  • -
  • -

    fromRequest().query(String key, int index): Returns the nth query parameter with a -given name.

    -
  • -
  • -

    fromRequest().path(): Returns the full path.

    -
  • -
  • -

    fromRequest().path(int index): Returns the nth path element.

    -
  • -
  • -

    fromRequest().header(String key): Returns the first header with a given name.

    -
  • -
  • -

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    -
  • -
  • -

    fromRequest().body(): Returns the full request body.

    -
  • -
  • -

    fromRequest().body(String jsonPath): Returns the element from the request that -matches the JSON Path.

    -
  • -
-
-
-

If you’re using the YAML contract definition you have to use the -Handlebars {{{ }}} notation with custom, Spring Cloud Contract - functions to achieve this.

-
-
-
    -
  • -

    {{{ request.url }}}: Returns the request URL and query parameters.

    -
  • -
  • -

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. -E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    -
  • -
  • -

    {{{ request.path }}}: Returns the full path.

    -
  • -
  • -

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. -for first entry `{{{ request.path.[0] }}}

    -
  • -
  • -

    {{{ request.headers.key }}}: Returns the first header with a given name.

    -
  • -
  • -

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    -
  • -
  • -

    {{{ request.body }}}: Returns the full request body.

    -
  • -
  • -

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that -matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    -
  • -
-
-
-

Consider the following contract:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
request:
-  method: GET
-  url: /api/v1/xxxx
-  queryParameters:
-    foo:
-      - bar
-      - bar2
-  headers:
-    Authorization:
-      - secret
-      - secret2
-  body:
-    foo: bar
-    baz: 5
-response:
-  status: 200
-  headers:
-    Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
-  body:
-    url: "{{{ request.url }}}"
-    path: "{{{ request.path }}}"
-    pathIndex: "{{{ request.path.1 }}}"
-    param: "{{{ request.query.foo }}}"
-    paramIndex: "{{{ request.query.foo.1 }}}"
-    authorization: "{{{ request.headers.Authorization.0 }}}"
-    authorization2: "{{{ request.headers.Authorization.1 }}"
-    fullBody: "{{{ request.body }}}"
-    responseFoo: "{{{ jsonpath this '$.foo' }}}"
-    responseBaz: "{{{ jsonpath this '$.baz' }}}"
-    responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"
-
-
-
-

Running a JUnit test generation leads to a test that resembles the following example:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Authorization", "secret")
-   .header("Authorization", "secret2")
-   .body("{\"foo\":\"bar\",\"baz\":5}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .queryParam("foo","bar")
-   .queryParam("foo","bar2")
-   .get("/api/v1/xxxx");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
- assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
- assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
- assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
- assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
- assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
- assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
- assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
- assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
-
-
-
-

As you can see, elements from the request have been properly referenced in the response.

-
-
-

The generated WireMock stub should resemble the following example:

-
-
-
-
{
-  "request" : {
-    "urlPath" : "/api/v1/xxxx",
-    "method" : "POST",
-    "headers" : {
-      "Authorization" : {
-        "equalTo" : "secret2"
-      }
-    },
-    "queryParameters" : {
-      "foo" : {
-        "equalTo" : "bar2"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
-    "headers" : {
-      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
-    },
-    "transformers" : [ "response-template" ]
-  }
-}
-
-
-
-

Sending a request such as the one presented in the request part of the contract results -in sending the following response body:

-
-
-
-
{
-  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
-  "path" : "/api/v1/xxxx",
-  "pathIndex" : "v1",
-  "param" : "bar",
-  "paramIndex" : "bar2",
-  "authorization" : "secret",
-  "authorization2" : "secret2",
-  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
-  "responseFoo" : "bar",
-  "responseBaz" : 5,
-  "responseBaz2" : "Bla bla bar bla bla"
-}
-
-
-
- - - - - -
- - -This feature works only with WireMock having a version greater than or equal -to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s -response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into -proper values. Additionally, it registers two helper functions: -
-
-
-
    -
  • -

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    -
  • -
  • -

    jsonpath: For a given parameter, find an object in the request body.

    -
  • -
-
-
-
-

Registering Your Own WireMock Extension

-
-

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers -the transformer, which lets you reference a request from a response. If you want to -provide your own extensions, you can register an implementation of the -org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. -Since we use the spring.factories extension approach, you can create an entry in -META-INF/spring.factories file similar to the following:

-
-
-
-
org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
-org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
-org.springframework.cloud.contract.spec.ContractConverter=\
-org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter
-
-
-
-

The following is an example of a custom extension:

-
-
-
TestWireMockExtensions.groovy
-
-
/*
- * Copyright 2013-2019 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cloud.contract.verifier.dsl.wiremock
-
-import com.github.tomakehurst.wiremock.extension.Extension
-
-/**
- * Extension that registers the default transformer and the custom one
- */
-class TestWireMockExtensions implements WireMockExtensions {
-	@Override
-	List<Extension> extensions() {
-		return [
-				new DefaultResponseTransformer(),
-				new CustomExtension()
-		]
-	}
-}
-
-class CustomExtension implements Extension {
-
-	@Override
-	String getName() {
-		return "foo-transformer"
-	}
-}
-
-
-
- - - - - -
- - -Remember to override the applyGlobally() method and set it to false if you -want the transformation to be applied only for a mapping that explicitly requires it. -
-
-
-
-

Dynamic Properties in the Matchers Sections

-
-

If you work with Pact, the following discussion may seem familiar. -Quite a few users are used to having a separation between the body and setting the -dynamic parts of a contract.

-
-
-

You can use the bodyMatchers section for two reasons:

-
-
-
    -
  • -

    Define the dynamic values that should end up in a stub. -You can set it in the request or inputMessage part of your contract.

    -
  • -
  • -

    Verify the result of your test. -This section is present in the response or outputMessage side of the -contract.

    -
  • -
-
-
-

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the -following matching possibilities:

-
-
-
Groovy DSL
-
    -
  • -

    For the stubs(in tests on the Consumer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be -equal to the value provided in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must -match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      -
    • -
    • -

      byDate(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO Time value.

      -
    • -
    -
    -
  • -
  • -

    For the verification(in generated tests on the Producer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be -equal to the provided value in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must -match the regex.

      -
    • -
    • -

      byDate(): The value taken from the producer’s response via the provided JSON Path must match -the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the producer’s response via the provided JSON Path must match -the regex for an ISO Time value.

      -
    • -
    • -

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be -of the same type as the type defined in the body of the response in the contract. -byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. -That way, you can assert the size of the flattened collection. To check the size of an -unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      -
    • -
    • -

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is -passed as an input to the custom method that you provide. For example, -byCommand('foo($it)') results in calling a foo method to which the value matching the -JSON Path gets passed. The type of the object read from the JSON can be one of the -following, depending on the JSON path:

      -
      -
        -
      • -

        String: If you point to a String value.

        -
      • -
      • -

        JSONArray: If you point to a List.

        -
      • -
      • -

        Map: If you point to a Map.

        -
      • -
      • -

        Number: If you point to Integer, Double, or other kind of number.

        -
      • -
      • -

        Boolean: If you point to a Boolean.

        -
      • -
      -
      -
    • -
    • -

      byNull(): The value taken from the response via the provided JSON Path must be null

      -
    • -
    -
    -
  • -
-
-
-
YAML
-

Please read the Groovy section for detailed explanation of -what the types mean

-
-
-

For YAML the structure of a matcher looks like this

-
-
-
-
- path: $.foo
-  type: by_regex
-  value: bar
-  regexType: as_string
-
-
-
-

Or if you want to use one of the predefined regular expressions -[only_alpha_unicode, number, any_boolean, ip_address, hostname, -email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

-
-
-
-
- path: $.foo
-  type: by_regex
-  predefined: only_alpha_unicode
-
-
-
-

Below you can find the allowed list of `type`s.

-
-
-
    -
  • -

    For stubMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        -
      • -
      -
      -
    • -
    -
    -
  • -
  • -

    For testMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        -
      • -
      -
      -
    • -
    • -

      by_command

      -
    • -
    • -

      by_null

      -
    • -
    -
    -
  • -
-
-
-

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

-
-
-
    -
  • -

    as_integer

    -
  • -
  • -

    as_double

    -
  • -
  • -

    as_float,

    -
  • -
  • -

    as_long

    -
  • -
  • -

    as_short

    -
  • -
  • -

    as_boolean

    -
  • -
  • -

    as_string

    -
  • -
-
-
-

Consider the following example:

-
-
-
Groovy DSL
-
-
Contract contractDsl = Contract.make {
-	request {
-		method 'GET'
-		urlPath '/get'
-		body([
-				duck                : 123,
-				alpha               : 'abc',
-				number              : 123,
-				aBoolean            : true,
-				date                : '2017-01-01',
-				dateTime            : '2017-01-01T01:23:45',
-				time                : '01:02:34',
-				valueWithoutAMatcher: 'foo',
-				valueWithTypeMatch  : 'string',
-				key                 : [
-						'complex.key': 'foo'
-				]
-		])
-		bodyMatchers {
-			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
-			jsonPath('$.duck', byEquality())
-			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
-			jsonPath('$.alpha', byEquality())
-			jsonPath('$.number', byRegex(number()).asInteger())
-			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
-			jsonPath('$.date', byDate())
-			jsonPath('$.dateTime', byTimestamp())
-			jsonPath('$.time', byTime())
-			jsonPath("\$.['key'].['complex.key']", byEquality())
-		}
-		headers {
-			contentType(applicationJson())
-		}
-	}
-	response {
-		status OK()
-		body([
-				duck                 : 123,
-				alpha                : 'abc',
-				number               : 123,
-				positiveInteger      : 1234567890,
-				negativeInteger      : -1234567890,
-				positiveDecimalNumber: 123.4567890,
-				negativeDecimalNumber: -123.4567890,
-				aBoolean             : true,
-				date                 : '2017-01-01',
-				dateTime             : '2017-01-01T01:23:45',
-				time                 : "01:02:34",
-				valueWithoutAMatcher : 'foo',
-				valueWithTypeMatch   : 'string',
-				valueWithMin         : [
-						1, 2, 3
-				],
-				valueWithMax         : [
-						1, 2, 3
-				],
-				valueWithMinMax      : [
-						1, 2, 3
-				],
-				valueWithMinEmpty    : [],
-				valueWithMaxEmpty    : [],
-				key                  : [
-						'complex.key': 'foo'
-				],
-				nullValue            : null
-		])
-		bodyMatchers {
-			// asserts the jsonpath value against manual regex
-			jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
-			// asserts the jsonpath value against the provided value
-			jsonPath('$.duck', byEquality())
-			// asserts the jsonpath value against some default regex
-			jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
-			jsonPath('$.alpha', byEquality())
-			jsonPath('$.number', byRegex(number()).asInteger())
-			jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
-			jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
-			jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
-			jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
-			jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
-			// asserts vs inbuilt time related regex
-			jsonPath('$.date', byDate())
-			jsonPath('$.dateTime', byTimestamp())
-			jsonPath('$.time', byTime())
-			// asserts that the resulting type is the same as in response body
-			jsonPath('$.valueWithTypeMatch', byType())
-			jsonPath('$.valueWithMin', byType {
-				// results in verification of size of array (min 1)
-				minOccurrence(1)
-			})
-			jsonPath('$.valueWithMax', byType {
-				// results in verification of size of array (max 3)
-				maxOccurrence(3)
-			})
-			jsonPath('$.valueWithMinMax', byType {
-				// results in verification of size of array (min 1 & max 3)
-				minOccurrence(1)
-				maxOccurrence(3)
-			})
-			jsonPath('$.valueWithMinEmpty', byType {
-				// results in verification of size of array (min 0)
-				minOccurrence(0)
-			})
-			jsonPath('$.valueWithMaxEmpty', byType {
-				// results in verification of size of array (max 0)
-				maxOccurrence(0)
-			})
-			// will execute a method `assertThatValueIsANumber`
-			jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
-			jsonPath("\$.['key'].['complex.key']", byEquality())
-			jsonPath('$.nullValue', byNull())
-		}
-		headers {
-			contentType(applicationJson())
-			header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
-		}
-	}
-}
-
-
-
-
YAML
-
-
request:
-  method: GET
-  urlPath: /get/1
-  headers:
-    Content-Type: application/json
-  cookies:
-    foo: 2
-    bar: 3
-  queryParameters:
-    limit: 10
-    offset: 20
-    filter: 'email'
-    sort: name
-    search: 55
-    age: 99
-    name: John.Doe
-    email: 'bob@email.com'
-  body:
-    duck: 123
-    alpha: "abc"
-    number: 123
-    aBoolean: true
-    date: "2017-01-01"
-    dateTime: "2017-01-01T01:23:45"
-    time: "01:02:34"
-    valueWithoutAMatcher: "foo"
-    valueWithTypeMatch: "string"
-    key:
-      "complex.key": 'foo'
-    nullValue: null
-    valueWithMin:
-      - 1
-      - 2
-      - 3
-    valueWithMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinEmpty: []
-    valueWithMaxEmpty: []
-  matchers:
-    url:
-      regex: /get/[0-9]
-      # predefined:
-      # execute a method
-      #command: 'equals($it)'
-    queryParameters:
-      - key: limit
-        type: equal_to
-        value: 20
-      - key: offset
-        type: containing
-        value: 20
-      - key: sort
-        type: equal_to
-        value: name
-      - key: search
-        type: not_matching
-        value: '^[0-9]{2}$'
-      - key: age
-        type: not_matching
-        value: '^\\w*$'
-      - key: name
-        type: matching
-        value: 'John.*'
-      - key: hello
-        type: absent
-    cookies:
-      - key: foo
-        regex: '[0-9]'
-      - key: bar
-        command: 'equals($it)'
-    headers:
-      - key: Content-Type
-        regex: "application/json.*"
-    body:
-      - path: $.duck
-        type: by_regex
-        value: "[0-9]{3}"
-      - path: $.duck
-        type: by_equality
-      - path: $.alpha
-        type: by_regex
-        predefined: only_alpha_unicode
-      - path: $.alpha
-        type: by_equality
-      - path: $.number
-        type: by_regex
-        predefined: number
-      - path: $.aBoolean
-        type: by_regex
-        predefined: any_boolean
-      - path: $.date
-        type: by_date
-      - path: $.dateTime
-        type: by_timestamp
-      - path: $.time
-        type: by_time
-      - path: "$.['key'].['complex.key']"
-        type: by_equality
-      - path: $.nullvalue
-        type: by_null
-      - path: $.valueWithMin
-        type: by_type
-        minOccurrence: 1
-      - path: $.valueWithMax
-        type: by_type
-        maxOccurrence: 3
-      - path: $.valueWithMinMax
-        type: by_type
-        minOccurrence: 1
-        maxOccurrence: 3
-response:
-  status: 200
-  cookies:
-    foo: 1
-    bar: 2
-  body:
-    duck: 123
-    alpha: "abc"
-    number: 123
-    aBoolean: true
-    date: "2017-01-01"
-    dateTime: "2017-01-01T01:23:45"
-    time: "01:02:34"
-    valueWithoutAMatcher: "foo"
-    valueWithTypeMatch: "string"
-    valueWithMin:
-      - 1
-      - 2
-      - 3
-    valueWithMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinMax:
-      - 1
-      - 2
-      - 3
-    valueWithMinEmpty: []
-    valueWithMaxEmpty: []
-    key:
-      'complex.key': 'foo'
-    nulValue: null
-  matchers:
-    headers:
-      - key: Content-Type
-        regex: "application/json.*"
-    cookies:
-      - key: foo
-        regex: '[0-9]'
-      - key: bar
-        command: 'equals($it)'
-    body:
-      - path: $.duck
-        type: by_regex
-        value: "[0-9]{3}"
-      - path: $.duck
-        type: by_equality
-      - path: $.alpha
-        type: by_regex
-        predefined: only_alpha_unicode
-      - path: $.alpha
-        type: by_equality
-      - path: $.number
-        type: by_regex
-        predefined: number
-      - path: $.aBoolean
-        type: by_regex
-        predefined: any_boolean
-      - path: $.date
-        type: by_date
-      - path: $.dateTime
-        type: by_timestamp
-      - path: $.time
-        type: by_time
-      - path: $.valueWithTypeMatch
-        type: by_type
-      - path: $.valueWithMin
-        type: by_type
-        minOccurrence: 1
-      - path: $.valueWithMax
-        type: by_type
-        maxOccurrence: 3
-      - path: $.valueWithMinMax
-        type: by_type
-        minOccurrence: 1
-        maxOccurrence: 3
-      - path: $.valueWithMinEmpty
-        type: by_type
-        minOccurrence: 0
-      - path: $.valueWithMaxEmpty
-        type: by_type
-        maxOccurrence: 0
-      - path: $.duck
-        type: by_command
-        value: assertThatValueIsANumber($it)
-      - path: $.nullValue
-        type: by_null
-        value: null
-  headers:
-    Content-Type: application/json
-
-
-
-

In the preceding example, you can see the dynamic portions of the contract in the -matchers sections. For the request part, you can see that, for all fields but -valueWithoutAMatcher, the values of the regular expressions that the stub should -contain are explicitly set. For the valueWithoutAMatcher, the verification takes place -in the same way as without the use of matchers. In that case, the test performs an -equality check.

-
-
-

For the response side in the bodyMatchers section, we define the dynamic parts in a -similar manner. The only difference is that the byType matchers are also present. The -verifier engine checks four fields to verify whether the response from the test -has a value for which the JSON path matches the given field, is of the same type as the one -defined in the response body, and passes the following check (based on the method being called):

-
-
-
    -
  • -

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    -
  • -
  • -

    For $.valueWithMin, the engine check the type and asserts whether the size is greater -than or equal to the minimum occurrence.

    -
  • -
  • -

    For $.valueWithMax, the engine checks the type and asserts whether the size is -smaller than or equal to the maximum occurrence.

    -
  • -
  • -

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is -between the min and maximum occurrence.

    -
  • -
-
-
-

The resulting test would resemble the following example (note that an and section -separates the autogenerated assertions and the assertion from matchers):

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Content-Type", "application/json")
-   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/get");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Content-Type")).matches("application/json.*");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
-// and:
- assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
- assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
- assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
- assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
- assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
- assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
- assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
- assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
- assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
- assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
- assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
- assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
- assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
- assertThatValueIsANumber(parsedJson.read("$.duck"));
- assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
-
-
-
- - - - - -
- - -Notice that, for the byCommand method, the example calls the -assertThatValueIsANumber. This method must be defined in the test base class or be -statically imported to your tests. Notice that the byCommand call was converted to -assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took -the method name and passed the proper JSON path as a parameter to it. -
-
-
-

The resulting WireMock stub is in the following example:

-
-
-
-
					'''
-{
-  "request" : {
-    "urlPath" : "/get",
-    "method" : "POST",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "application/json.*"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
-    }, {
-      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
-    }, {
-      "matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.duck == 123)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.alpha == 'abc')]"
-    }, {
-      "matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
-    }, {
-      "matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMin.size() >= 1)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 4)]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
-    "headers" : {
-      "Content-Type" : "application/json"
-    },
-    "transformers" : [ "response-template" ]
-  }
-}
-'''
-
-
-
- - - - - -
- - -If you use a matcher, then the part of the request and response that the -matcher addresses with the JSON Path gets removed from the assertion. In the case of -verifying a collection, you must create matchers for all the elements of the -collection. -
-
-
-

Consider the following example:

-
-
-
-
Contract.make {
-    request {
-        method 'GET'
-        url("/foo")
-    }
-    response {
-        status OK()
-        body(events: [[
-                                 operation          : 'EXPORT',
-                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
-                                 status             : 'OK'
-                         ], [
-                                 operation          : 'INPUT_PROCESSING',
-                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
-                                 status             : 'OK'
-                         ]
-                ]
-        )
-        bodyMatchers {
-            jsonPath('$.events[0].operation', byRegex('.+'))
-            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
-            jsonPath('$.events[0].status', byRegex('.+'))
-        }
-    }
-}
-
-
-
-

The preceding code leads to creating the following test (the code block shows only the assertion section):

-
-
-
-
and:
-	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
-	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
-	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
-	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
-	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
-	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
-and:
-	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
-	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
-	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
-
-
-
-

As you can see, the assertion is malformed. Only the first element of the array got -asserted. In order to fix this, you should apply the assertion to the whole $.events -collection and assert it with the byCommand(…​) method.

-
-
-
-
-

JAX-RS Support

-
-

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs -to define protected WebTarget webTarget and server initialization. The only option for -testing JAX-RS API is to start a web server. Also, a request with a body needs to have a -content type set. Otherwise, the default of application/octet-stream gets used.

-
-
-

In order to use JAX-RS mode, use the following settings:

-
-
-
-
testMode == 'JAXRSCLIENT'
-
-
-
-

The following example shows a generated test API:

-
-
-
-
					"""\
-package com.example;
-
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import org.junit.Test;
-import org.junit.Rule;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Response;
-
-import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
-import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static javax.ws.rs.client.Entity.*;
-
-@SuppressWarnings("rawtypes")
-public class FooTest {
-\tWebTarget webTarget;
-
-\t@Test
-\tpublic void validate_() throws Exception {
-
-\t\t// when:
-\t\t\tResponse response = webTarget
-\t\t\t\t\t\t\t.path("/users")
-\t\t\t\t\t\t\t.queryParam("limit", "10")
-\t\t\t\t\t\t\t.queryParam("offset", "20")
-\t\t\t\t\t\t\t.queryParam("filter", "email")
-\t\t\t\t\t\t\t.queryParam("sort", "name")
-\t\t\t\t\t\t\t.queryParam("search", "55")
-\t\t\t\t\t\t\t.queryParam("age", "99")
-\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
-\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
-\t\t\t\t\t\t\t.request()
-\t\t\t\t\t\t\t.build("GET")
-\t\t\t\t\t\t\t.invoke();
-\t\t\tString responseAsString = response.readEntity(String.class);
-
-\t\t// then:
-\t\t\tassertThat(response.getStatus()).isEqualTo(200);
-
-\t\t// and:
-\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
-\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
-\t}
-
-}
-
-"""
-
-
-
-
-

Async Support

-
-

If you’re using asynchronous communication on the server side (your controllers are -returning Callable, DeferredResult, and so on), then, inside your contract, you must -provide an async() method in the response section. The following code shows an example:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status OK()
-        body 'Passed'
-        async()
-    }
-}
-
-
-
-
YAML
-
-
response:
-    async: true
-
-
-
-

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status 200
-        body 'Passed'
-        fixedDelayMilliseconds 1000
-    }
-}
-
-
-
-
YAML
-
-
response:
-    fixedDelayMilliseconds: 1000
-
-
-
-
-

Working with Context Paths

-
-

Spring Cloud Contract supports context paths.

-
-
- - - - - -
- - -The only change needed to fully support context paths is the switch on the -PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer -side remains untouched. In order for the generated test to pass, you must use EXPLICIT -mode. -
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'EXPLICIT'
-}
-
-
-
-

That way, you generate a test that DOES NOT use MockMvc. It means that you generate -real requests and you need to setup your generated test’s base class to work on a real -socket.

-
-
-

Consider the following contract:

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		method 'GET'
-		url '/my-context-path/url'
-	}
-	response {
-		status OK()
-	}
-}
-
-
-
-

The following example shows how to set up a base class and Rest Assured:

-
-
-
-
import io.restassured.RestAssured;
-import org.junit.Before;
-import org.springframework.boot.web.server.LocalServerPort;
-import org.springframework.boot.test.context.SpringBootTest;
-
-@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-class ContextPathTestingBaseClass {
-
-	@LocalServerPort int port;
-
-	@Before
-	public void setup() {
-		RestAssured.baseURI = "http://localhost";
-		RestAssured.port = this.port;
-	}
-}
-
-
-
-

If you do it this way:

-
-
-
    -
  • -

    All of your requests in the autogenerated tests are sent to the real endpoint with your -context path included (for example, /my-context-path/url).

    -
  • -
  • -

    Your contracts reflect that you have a context path. Your generated stubs also have -that information (for example, in the stubs, you have to call /my-context-path/url).

    -
  • -
-
-
-
-

Working with WebFlux

-
-

Spring Cloud Contract offers two ways of working with WebFlux.

-
-
-

WebFlux with WebTestClient

-
-

One of them is via the WebTestClient mode.

-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>WEBTESTCLIENT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'WEBTESTCLIENT'
-}
-
-
-
-

The following example shows how to set up a WebTestClient base class and RestAssured -for WebFlux:

-
-
-
-
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
-import org.junit.Before;
-
-public abstract class BeerRestBase {
-
-	@Before
-	public void setup() {
-		RestAssuredWebTestClient.standaloneSetup(
-		new ProducerController(personToCheck -> personToCheck.age >= 20));
-	}
-}
-}
-
-
-
-
-

WebFlux with Explicit mode

-
-

Another way is with the EXPLICIT mode in your generated tests -to work with WebFlux.

-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'EXPLICIT'
-}
-
-
-
-

The following example shows how to set up a base class and Rest Assured for Web Flux:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(classes = BeerRestBase.Config.class,
-		webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
-		properties = "server.port=0")
-public abstract class BeerRestBase {
-
-    // your tests go here
-
-    // in this config class you define all controllers and mocked services
-@Configuration
-@EnableAutoConfiguration
-static class Config {
-
-	@Bean
-	PersonCheckingService personCheckingService()  {
-		return personToCheck -> personToCheck.age >= 20;
-	}
-
-	@Bean
-	ProducerController producerController() {
-		return new ProducerController(personCheckingService());
-	}
-}
-
-}
-
-
-
-
-
-

XML Support for REST

-
-

For REST contracts, we also support XML request and response body. -The XML body has to be passed within the body element -as a String or GString. Also body matchers can be provided for -both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath -method should be used, with the desired xPath provided as the first argument -and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

-
-
-

Here is an example of a Groovy DSL contract with XML response body:

-
-
-
-
					Contract.make {
-						request {
-							method GET()
-							urlPath '/get'
-							headers {
-								contentType(applicationXml())
-							}
-						}
-						response {
-							status(OK())
-							headers {
-								contentType(applicationXml())
-							}
-							body """
-<test>
-<duck type='xtype'>123</duck>
-<alpha>abc</alpha>
-<list>
-<elem>abc</elem>
-<elem>def</elem>
-<elem>ghi</elem>
-</list>
-<number>123</number>
-<aBoolean>true</aBoolean>
-<date>2017-01-01</date>
-<dateTime>2017-01-01T01:23:45</dateTime>
-<time>01:02:34</time>
-<valueWithoutAMatcher>foo</valueWithoutAMatcher>
-<key><complex>foo</complex></key>
-</test>"""
-							bodyMatchers {
-								xPath('/test/duck/text()', byRegex("[0-9]{3}"))
-								xPath('/test/duck/text()', byCommand('equals($it)'))
-								xPath('/test/duck/xxx', byNull())
-								xPath('/test/duck/text()', byEquality())
-								xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
-								xPath('/test/alpha/text()', byEquality())
-								xPath('/test/number/text()', byRegex(number()))
-								xPath('/test/date/text()', byDate())
-								xPath('/test/dateTime/text()', byTimestamp())
-								xPath('/test/time/text()', byTime())
-								xPath('/test/*/complex/text()', byEquality())
-								xPath('/test/duck/@type', byEquality())
-							}
-						}
-					}
-
-
-
-

And below is an example of a YAML contract with XML request and response bodies:

-
-
-
-
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
-
-
-
-

Here is an example of an automatically generated test for XML response body:

-
-
-
-
@Test
-public void validate_xmlMatches() throws Exception {
-	// given:
-	MockMvcRequestSpecification request = given()
-				.header("Content-Type", "application/xml");
-
-	// when:
-	ResponseOptions response = given().spec(request).get("/get");
-
-	// then:
-	assertThat(response.statusCode()).isEqualTo(200);
-	// and:
-	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
-					.newDocumentBuilder();
-	Document parsedXml = documentBuilder.parse(new InputSource(
-				new StringReader(response.getBody().asString())));
-	// and:
-	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
-	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
-	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
-	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
-	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
-	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
-	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
-	}
-
-
-
-
-

Messaging Top-Level Elements

-
-

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences:

-
- -
-

Output Triggered by a Method

-
-

The output message can be triggered by calling a method (such as a Scheduler when a was -started and a message was sent), as shown in the following example:

-
-
-
Groovy DSL
-
-
def dsl = Contract.make {
-	// Human readable description
-	description 'Some description'
-	// Label by means of which the output message can be triggered
-	label 'some_label'
-	// input to the contract
-	input {
-		// the contract will be triggered by a method
-		triggeredBy('bookReturnedTriggered()')
-	}
-	// output message of the contract
-	outputMessage {
-		// destination to which the output message will be sent
-		sentTo('output')
-		// the body of the output message
-		body('''{ "bookName" : "foo" }''')
-		// the headers of the output message
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-
YAML
-
-
# Human readable description
-description: Some description
-# Label by means of which the output message can be triggered
-label: some_label
-input:
-  # the contract will be triggered by a method
-  triggeredBy: bookReturnedTriggered()
-# output message of the contract
-outputMessage:
-  # destination to which the output message will be sent
-  sentTo: output
-  # the body of the output message
-  body:
-    bookName: foo
-  # the headers of the output message
-  headers:
-    BOOK-NAME: foo
-
-
-
-

In the previous example case, the output message is sent to output if a method called -bookReturnedTriggered is executed. On the message publisher’s side, we generate a -test that calls that method to trigger the message. On the consumer side, you can use -the some_label to trigger the message.

-
-
-
-

Output Triggered by a Message

-
-

The output message can be triggered by receiving a message, as shown in the following -example:

-
-
-
Groovy DSL
-
-
def dsl = Contract.make {
-	description 'Some Description'
-	label 'some_label'
-	// input is a message
-	input {
-		// the message was received from this destination
-		messageFrom('input')
-		// has the following body
-		messageBody([
-				bookName: 'foo'
-		])
-		// and the following headers
-		messageHeaders {
-			header('sample', 'header')
-		}
-	}
-	outputMessage {
-		sentTo('output')
-		body([
-				bookName: 'foo'
-		])
-		headers {
-			header('BOOK-NAME', 'foo')
-		}
-	}
-}
-
-
-
-
YAML
-
-
# Human readable description
-description: Some description
-# Label by means of which the output message can be triggered
-label: some_label
-# input is a message
-input:
-  messageFrom: input
-  # has the following body
-  messageBody:
-    bookName: 'foo'
-  # and the following headers
-  messageHeaders:
-    sample: 'header'
-# output message of the contract
-outputMessage:
-  # destination to which the output message will be sent
-  sentTo: output
-  # the body of the output message
-  body:
-    bookName: foo
-  # the headers of the output message
-  headers:
-    BOOK-NAME: foo
-
-
-
-

In the preceding example, the output message is sent to output if a proper message is -received on the input destination. On the message publisher’s side, the engine -generates a test that sends the input message to the defined destination. On the -consumer side, you can either send a message to the input destination or use a label -(some_label in the example) to trigger the message.

-
-
-
-

Consumer/Producer

-
- - - - - -
- - -This section is valid only for Groovy DSL. -
-
-
-

In HTTP, you have a notion of client/stub and `server/test notation. You can also -use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also -provides the consumer and producer methods, as presented in the following example -(note that you can use either $ or value methods to provide consumer and producer -parts):

-
-
-
-
					Contract.make {
-				name "foo"
-						label 'some_label'
-						input {
-							messageFrom value(consumer('jms:output'), producer('jms:input'))
-							messageBody([
-									bookName: 'foo'
-							])
-							messageHeaders {
-								header('sample', 'header')
-							}
-						}
-						outputMessage {
-							sentTo $(consumer('jms:input'), producer('jms:output'))
-							body([
-									bookName: 'foo'
-							])
-						}
-					}
-
-
-
-
-

Common

-
-

In the input or outputMessage section you can call assertThat with the name -of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the -base class or in a static import. Spring Cloud Contract will execute that method -in the generated test.

-
-
-
-
-

Multiple Contracts in One File

-
-

You can define multiple contracts in one file. Such a contract might resemble the -following example:

-
-
-
Groovy DSL
-
-
import org.springframework.cloud.contract.spec.Contract
-
-[
-	Contract.make {
-		name("should post a user")
-		request {
-			method 'POST'
-			url('/users/1')
-		}
-		response {
-			status OK()
-		}
-	},
-	Contract.make {
-		request {
-			method 'POST'
-			url('/users/2')
-		}
-		response {
-			status OK()
-		}
-	}
-]
-
-
-
-
YAML
-
-
---
-name: should post a user
-request:
-  method: POST
-  url: /users/1
-response:
-  status: 200
----
-request:
-  method: POST
-  url: /users/2
-response:
-  status: 200
----
-request:
-  method: POST
-  url: /users/3
-response:
-  status: 200
-
-
-
-

In the preceding example, one contract has the name field and the other does not. This -leads to generation of two tests that look more or less like this:

-
-
-
-
package org.springframework.cloud.contract.verifier.tests.com.hello;
-
-import com.example.TestBase;
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
-import com.jayway.restassured.response.ResponseOptions;
-import org.junit.Test;
-
-import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class V1Test extends TestBase {
-
-	@Test
-	public void validate_should_post_a_user() throws Exception {
-		// given:
-			MockMvcRequestSpecification request = given();
-
-		// when:
-			ResponseOptions response = given().spec(request)
-					.post("/users/1");
-
-		// then:
-			assertThat(response.statusCode()).isEqualTo(200);
-	}
-
-	@Test
-	public void validate_withList_1() throws Exception {
-		// given:
-			MockMvcRequestSpecification request = given();
-
-		// when:
-			ResponseOptions response = given().spec(request)
-					.post("/users/2");
-
-		// then:
-			assertThat(response.statusCode()).isEqualTo(200);
-	}
-
-}
-
-
-
-

Notice that, for the contract that has the name field, the generated test method is named -validate_should_post_a_user. For the one that does not have the name, it is called -validate_withList_1. It corresponds to the name of the file WithList.groovy and the -index of the contract in the list.

-
-
-

The generated stubs is shown in the following example:

-
-
-
-
should post a user.json
-1_WithList.json
-
-
-
-

As you can see, the first file got the name parameter from the contract. The second -got the name of the contract file (WithList.groovy) prefixed with the index (in this -case, the contract had an index of 1 in the list of contracts in the file).

-
-
- - - - - -
- - -As you can see, it is much better if you name your contracts because doing so makes -your tests far more meaningful. -
-
-
-
-

Generating Spring REST Docs snippets from the contracts

-
-

When you want to include the requests and responses of your API using Spring REST Docs, -you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. -Simply include the following dependencies if you haven’t already.

-
-
-
Maven
-
-
<dependency>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
-	<scope>test</scope>
-</dependency>
-<dependency>
-	<groupId>org.springframework.restdocs</groupId>
-	<artifactId>spring-restdocs-mockmvc</artifactId>
-	<optional>true</optional>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'
-
-
-
-

Next you need to make some changes to your base class like the following example.

-
-
-
-
package com.example.fraud;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.restdocs.JUnitRestDocumentation;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import org.springframework.web.context.WebApplicationContext;
-
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = Application.class)
-public abstract class FraudBaseWithWebAppSetup {
-
-	private static final String OUTPUT = "target/generated-snippets";
-
-	@Rule
-	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
-
-	@Rule
-	public TestName testName = new TestName();
-
-	@Autowired
-	private WebApplicationContext context;
-
-	@Before
-	public void setup() {
-		RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
-				.apply(documentationConfiguration(this.restDocumentation))
-				.alwaysDo(document(
-						getClass().getSimpleName() + "_" + testName.getMethodName()))
-				.build());
-	}
-
-	protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
-		assert rejectionReason == null;
-	}
-
-}
-
-
-
-

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

-
-
-
-
package com.example.fraud;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-
-import org.springframework.restdocs.JUnitRestDocumentation;
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
-import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
-
-public abstract class FraudBaseWithStandaloneSetup {
-
-	private static final String OUTPUT = "target/generated-snippets";
-
-	@Rule
-	public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
-
-	@Rule
-	public TestName testName = new TestName();
-
-	@Before
-	public void setup() {
-		RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
-				.standaloneSetup(new FraudDetectionController())
-				.apply(documentationConfiguration(this.restDocumentation))
-				.alwaysDo(document(
-						getClass().getSimpleName() + "_" + testName.getMethodName())));
-	}
-
-}
-
-
-
- - - - - -
- - -You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. -
-
-
-
-
-
-

Customization

-
-
- - - - - -
- - -This section is valid only for Groovy DSL -
-
-
-

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in -the remainder of this section.

-
-
-

Extending the DSL

-
-

You can provide your own functions to the DSL. The key requirement for this feature is to -maintain the static compatibility. Later in this document, you can see examples of:

-
-
-
    -
  • -

    Creating a JAR with reusable classes.

    -
  • -
  • -

    Referencing of these classes in the DSLs.

    -
  • -
-
-
-

You can find the full example -here.

-
-
-

Common JAR

-
-

The following examples show three classes that can be reused in the DSLs.

-
-
-

PatternUtils contains functions used by both the consumer and the producer.

-
-
-
-
package com.example;
-
-import java.util.regex.Pattern;
-
-/**
- * If you want to use {@link Pattern} directly in your tests
- * then you can create a class resembling this one. It can
- * contain all the {@link Pattern} you want to use in the DSL.
- *
- * <pre>
- * {@code
- * request {
- *     body(
- *         [ age: $(c(PatternUtils.oldEnough()))]
- *     )
- * }
- * </pre>
- *
- * Notice that we're using both {@code $()} for dynamic values
- * and {@code c()} for the consumer side.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class PatternUtils {
-
-	public static String tooYoung() {
-		//remove::start[]
-		return "[0-1][0-9]";
-		//remove::end[return]
-	}
-
-	public static Pattern oldEnough() {
-		//remove::start[]
-		return Pattern.compile("[2-9][0-9]");
-		//remove::end[return]
-	}
-
-	/**
-	 * Makes little sense but it's just an example ;)
-	 */
-	public static Pattern ok() {
-		//remove::start[]
-		return Pattern.compile("OK");
-		//remove::end[return]
-	}
-}
-//end::impl[]
-
-
-
-

ConsumerUtils contains functions used by the consumer.

-
-
-
-
package com.example;
-
-import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
-
-/**
- * DSL Properties passed to the DSL from the consumer's perspective.
- * That means that on the input side {@code Request} for HTTP
- * or {@code Input} for messaging you can have a regular expression.
- * On the {@code Response} for HTTP or {@code Output} for messaging
- * you have to have a concrete value.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class ConsumerUtils {
-	/**
-	 * Consumer side property. By using the {@link ClientDslProperty}
-	 * you can omit most of boilerplate code from the perspective
-	 * of dynamic values. Example
-	 *
-	 * <pre>
-	 * {@code
-	 * request {
-	 *     body(
-	 *         [ age: $(ConsumerUtils.oldEnough())]
-	 *     )
-	 * }
-	 * </pre>
-	 *
-	 * That way it's in the implementation that we decide what value we will pass to the consumer
-	 * and which one to the producer.
-	 *
-	 * @author Marcin Grzejszczak
-	 */
-	public static ClientDslProperty oldEnough() {
-		//remove::start[]
-		// this example is not the best one and
-		// theoretically you could just pass the regex instead of `ServerDslProperty` but
-		// it's just to show some new tricks :)
-		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
-		//remove::end[return]
-	}
-
-}
-//end::impl[]
-
-
-
-

ProducerUtils contains functions used by the producer.

-
-
-
-
package com.example;
-
-import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
-
-/**
- * DSL Properties passed to the DSL from the producer's perspective.
- * That means that on the input side {@code Request} for HTTP
- * or {@code Input} for messaging you have to have a concrete value.
- * On the {@code Response} for HTTP or {@code Output} for messaging
- * you can have a regular expression.
- *
- * @author Marcin Grzejszczak
- */
-//tag::impl[]
-public class ProducerUtils {
-
-	/**
-	 * Producer side property. By using the {@link ProducerUtils}
-	 * you can omit most of boilerplate code from the perspective
-	 * of dynamic values. Example
-	 *
-	 * <pre>
-	 * {@code
-	 * response {
-	 *     body(
-	 *         [ status: $(ProducerUtils.ok())]
-	 *     )
-	 * }
-	 * </pre>
-	 *
-	 * That way it's in the implementation that we decide what value we will pass to the consumer
-	 * and which one to the producer.
-	 */
-	public static ServerDslProperty ok() {
-		// this example is not the best one and
-		// theoretically you could just pass the regex instead of `ServerDslProperty` but
-		// it's just to show some new tricks :)
-		return new ServerDslProperty( PatternUtils.ok(), "OK");
-	}
-}
-//end::impl[]
-
-
-
-
-

Adding the Dependency to the Project

-
-

In order for the plugins and IDE to be able to reference the common JAR classes, you need -to pass the dependency to your project.

-
-
-
-

Test the Dependency in the Project’s Dependencies

-
-

First, add the common jar dependency as a test dependency. Because your contracts files -are available on the test resources path, the common jar classes automatically become -visible in your Groovy files. The following examples show how to test the dependency:

-
-
-
Maven
-
-
<dependency>
-	<groupId>com.example</groupId>
-	<artifactId>beer-common</artifactId>
-	<version>${project.version}</version>
-	<scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")
-
-
-
-
-

Test a Dependency in the Plugin’s Dependencies

-
-

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the -following example:

-
-
-
Maven
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-	<configuration>
-		<packageWithBaseClasses>com.example</packageWithBaseClasses>
-		<baseClassMappings>
-			<baseClassMapping>
-				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
-				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
-			</baseClassMapping>
-		</baseClassMappings>
-	</configuration>
-	<dependencies>
-		<dependency>
-			<groupId>com.example</groupId>
-			<artifactId>beer-common</artifactId>
-			<version>${project.version}</version>
-			<scope>compile</scope>
-		</dependency>
-	</dependencies>
-</plugin>
-
-
-
-
Gradle
-
-
classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"
-
-
-
-
-

Referencing classes in DSLs

-
-

You can now reference your classes in your DSL, as shown in the following example:

-
-
-
-
package contracts.beer.rest
-
-import com.example.ConsumerUtils
-import com.example.ProducerUtils
-import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-	description("""
-Represents a successful scenario of getting a beer
-
-```
-given:
-	client is old enough
-when:
-	he applies for a beer
-then:
-	we'll grant him the beer
-```
-
-""")
-	request {
-		method 'POST'
-		url '/check'
-		body(
-				age: $(ConsumerUtils.oldEnough())
-		)
-		headers {
-			contentType(applicationJson())
-		}
-	}
-	response {
-		status 200
-		body("""
-			{
-				"status": "${value(ProducerUtils.ok())}"
-			}
-			""")
-		headers {
-			contentType(applicationJson())
-		}
-	}
-}
-
-
-
- - - - - -
- - -You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. -
-
-
-
-
-
-
-

Using the Pluggable Architecture

-
-
-

You may encounter cases where you have your contracts have been defined in other formats, -such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic -generation of tests and stubs. You can add your own implementation for generating both -tests and stubs. Also, you can customize the way tests are generated (for example, you -can generate tests for other languages) and the way stubs are generated (for example, you -can generate stubs for other HTTP server implementations).

-
-
-

Custom Contract Converter

-
-

The ContractConverter interface lets you register your own implementation of a contract -structure converter. The following code listing shows the ContractConverter interface:

-
-
-
-
package org.springframework.cloud.contract.spec;
-
-import java.io.File;
-import java.util.Collection;
-
-/**
- * Converter to be used to convert FROM {@link File} TO {@link Contract} and from
- * {@link Contract} to {@code T}.
- *
- * @param <T> - type to which we want to convert the contract
- * @author Marcin Grzejszczak
- * @since 1.1.0
- */
-public interface ContractConverter<T> extends ContractStorer<T> {
-
-	/**
-	 * Should this file be accepted by the converter. Can use the file extension to check
-	 * if the conversion is possible.
-	 * @param file - file to be considered for conversion
-	 * @return - {@code true} if the given implementation can convert the file
-	 */
-	boolean isAccepted(File file);
-
-	/**
-	 * Converts the given {@link File} to its {@link Contract} representation.
-	 * @param file - file to convert
-	 * @return - {@link Contract} representation of the file
-	 */
-	Collection<Contract> convertFrom(File file);
-
-	/**
-	 * Converts the given {@link Contract} to a {@link T} representation.
-	 * @param contract - the parsed contract
-	 * @return - {@link T} the type to which we do the conversion
-	 */
-	T convertTo(Collection<Contract> contract);
-
-}
-
-
-
-

Your implementation must define the condition on which it should start the -conversion. Also, you must define how to perform that conversion in both directions.

-
-
- - - - - -
- - -Once you create your implementation, you must create a -/META-INF/spring.factories file in which you provide the fully qualified name of your -implementation. -
-
-
-

The following example shows a typical spring.factories file:

-
-
-
-
org.springframework.cloud.contract.spec.ContractConverter=\
-org.springframework.cloud.contract.verifier.converter.YamlContractConverter
-
-
-
-

Pact Converter

-
-

Spring Cloud Contract includes support for Pact representation of -contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we -present how to add Pact support for your project. Note however that not all functionality is supported. -Starting with v3 you can combine multiple matcher for the same element; -you can use matchers for the body, headers, request and path; and you can use value generators. -Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. -Next to that the request and path matchers are skipped during the conversion. -When using a date, time or datetime value generator with a given format, -the given format will be skipped and the ISO format will be used.

-
-
-

In order to properly support the Spring Cloud Contract way of doing messaging -with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

-
-
-
    -
  • -

    to define the destination to which a message gets sent, you have to -set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    -
  • -
-
-
-
-

Pact Contract

-
-

Consider following example of a Pact contract, which is a file under the -src/test/resources/contracts folder.

-
-
-
-
{
-  "provider": {
-    "name": "Provider"
-  },
-  "consumer": {
-    "name": "Consumer"
-  },
-  "interactions": [
-    {
-      "description": "",
-      "request": {
-        "method": "PUT",
-        "path": "/fraudcheck",
-        "headers": {
-          "Content-Type": "application/vnd.fraud.v1+json"
-        },
-        "body": {
-          "clientId": "1234567890",
-          "loanAmount": 99999
-        },
-        "generators": {
-          "body": {
-            "$.clientId": {
-              "type": "Regex",
-              "regex": "[0-9]{10}"
-            }
-          }
-        },
-        "matchingRules": {
-          "header": {
-            "Content-Type": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
-                }
-              ],
-              "combine": "AND"
-            }
-          },
-          "body": {
-            "$.clientId": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "[0-9]{10}"
-                }
-              ],
-              "combine": "AND"
-            }
-          }
-        }
-      },
-      "response": {
-        "status": 200,
-        "headers": {
-          "Content-Type": "application/vnd.fraud.v1+json"
-        },
-        "body": {
-          "fraudCheckStatus": "FRAUD",
-          "rejectionReason": "Amount too high"
-        },
-        "matchingRules": {
-          "header": {
-            "Content-Type": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "application/vnd\\.fraud\\.v1\\+json.*"
-                }
-              ],
-              "combine": "AND"
-            }
-          },
-          "body": {
-            "$.fraudCheckStatus": {
-              "matchers": [
-                {
-                  "match": "regex",
-                  "regex": "FRAUD"
-                }
-              ],
-              "combine": "AND"
-            }
-          }
-        }
-      }
-    }
-  ],
-  "metadata": {
-    "pact-specification": {
-      "version": "3.0.0"
-    },
-    "pact-jvm": {
-      "version": "3.5.13"
-    }
-  }
-}
-
-
-
-

The remainder of this section about using Pact refers to the preceding file.

-
-
-
-

Pact for Producers

-
-

On the producer side, you must add two additional dependencies to your plugin -configuration. One is the Spring Cloud Contract Pact support, and the other represents -the current Pact version that you use.

-
-
-
Maven
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-	<configuration>
-		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
-	</configuration>
-	<dependencies>
-		<dependency>
-			<groupId>org.springframework.cloud</groupId>
-			<artifactId>spring-cloud-contract-pact</artifactId>
-			<version>${spring-cloud-contract.version}</version>
-		</dependency>
-	</dependencies>
-</plugin>
-
-
-
-
Gradle
-
-
classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"
-
-
-
-

When you execute the build of your application, a test will be generated. The generated -test might be as follows:

-
-
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-	// given:
-		MockMvcRequestSpecification request = given()
-				.header("Content-Type", "application/vnd.fraud.v1+json")
-				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
-
-	// when:
-		ResponseOptions response = given().spec(request)
-				.put("/fraudcheck");
-
-	// then:
-		assertThat(response.statusCode()).isEqualTo(200);
-		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
-	// and:
-		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
-	// and:
-		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
-}
-
-
-
-

The corresponding generated stub might be as follows:

-
-
-
-
{
-  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "request" : {
-    "url" : "/fraudcheck",
-    "method" : "PUT",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
-    "headers" : {
-      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
-    },
-    "transformers" : [ "response-template" ]
-  },
-}
-
-
-
-
-

Pact for Consumers

-
-

On the producer side, you must add two additional dependencies to your project -dependencies. One is the Spring Cloud Contract Pact support, and the other represents the -current Pact version that you use.

-
-
-
Maven
-
-
<dependency>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-pact</artifactId>
-	<scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile "org.springframework.cloud:spring-cloud-contract-pact"
-
-
-
-
-
-

Using the Custom Test Generator

-
-

If you want to generate tests for languages other than Java or you are not happy with the -way the verifier builds Java tests, you can register your own implementation.

-
-
-

The SingleTestGenerator interface lets you register your own implementation. The -following code listing shows the SingleTestGenerator interface:

-
-
-
-
package org.springframework.cloud.contract.verifier.builder;
-
-import java.nio.file.Path;
-import java.util.Collection;
-
-import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
-import org.springframework.cloud.contract.verifier.file.ContractMetadata;
-
-/**
- * Builds a single test.
- *
- * @since 1.1.0
- */
-public interface SingleTestGenerator {
-
-	/**
-	 * Creates contents of a single test class in which all test scenarios from the
-	 * contract metadata should be placed.
-	 * @param properties - properties passed to the plugin
-	 * @param listOfFiles - list of parsed contracts with additional metadata
-	 * @param className - the name of the generated test class
-	 * @param classPackage - the name of the package in which the test class should be
-	 * stored
-	 * @param includedDirectoryRelativePath - relative path to the included directory
-	 * @return contents of a single test class
-	 * @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
-	 */
-	@Deprecated
-	String buildClass(ContractVerifierConfigProperties properties,
-			Collection<ContractMetadata> listOfFiles, String className,
-			String classPackage, String includedDirectoryRelativePath);
-
-	/**
-	 * Creates contents of a single test class in which all test scenarios from the
-	 * contract metadata should be placed.
-	 * @param properties - properties passed to the plugin
-	 * @param listOfFiles - list of parsed contracts with additional metadata
-	 * @param generatedClassData - information about the generated class
-	 * @param includedDirectoryRelativePath - relative path to the included directory
-	 * @return contents of a single test class
-	 */
-	default String buildClass(ContractVerifierConfigProperties properties,
-			Collection<ContractMetadata> listOfFiles,
-			String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
-		String className = generatedClassData.className;
-		String classPackage = generatedClassData.classPackage;
-		String path = includedDirectoryRelativePath;
-		return buildClass(properties, listOfFiles, className, classPackage, path);
-	}
-
-	/**
-	 * Extension that should be appended to the generated test class. E.g. {@code .java}
-	 * or {@code .php}
-	 * @param properties - properties passed to the plugin
-	 */
-	String fileExtension(ContractVerifierConfigProperties properties);
-
-	class GeneratedClassData {
-
-		public final String className;
-
-		public final String classPackage;
-
-		public final Path testClassPath;
-
-		public GeneratedClassData(String className, String classPackage,
-				Path testClassPath) {
-			this.className = className;
-			this.classPackage = classPackage;
-			this.testClassPath = testClassPath;
-		}
-
-	}
-
-}
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

-
-
-
-
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
-com.example.MyGenerator
-
-
-
-
-

Using the Custom Stub Generator

-
-

If you want to generate stubs for stub servers other than WireMock, you can plug in your -own implementation of the StubGenerator interface. The following code listing shows the -StubGenerator interface:

-
-
-
-
package org.springframework.cloud.contract.verifier.converter;
-
-import java.util.Map;
-
-import org.springframework.cloud.contract.spec.Contract;
-import org.springframework.cloud.contract.verifier.file.ContractMetadata;
-
-/**
- * Converts contracts into their stub representation.
- *
- * @since 1.1.0
- */
-public interface StubGenerator {
-
-	/**
-	 * @param fileName - file name
-	 * @return {@code true} if the converter can handle the file to convert it into a
-	 * stub.
-	 */
-	default boolean canHandleFileName(String fileName) {
-		return fileName.endsWith(fileExtension());
-	}
-
-	/**
-	 * @param rootName - root name of the contract
-	 * @param content - metadata of the contract
-	 * @return the collection of converted contracts into stubs. One contract can result
-	 * in multiple stubs.
-	 */
-	Map<Contract, String> convertContents(String rootName, ContractMetadata content);
-
-	/**
-	 * @param inputFileName - name of the input file
-	 * @return the name of the converted stub file. If you have multiple contracts in a
-	 * single file then a prefix will be added to the generated file. If you provide the
-	 * {@link Contract#name} field then that field will override the generated file name.
-	 *
-	 * Example: name of file with 2 contracts is {@code foo.groovy}, it will be converted
-	 * by the implementation to {@code foo.json}. The recursive file converter will create
-	 * two files {@code 0_foo.json} and {@code 1_foo.json}
-	 */
-	String generateOutputFileNameForInput(String inputFileName);
-
-	/**
-	 * Describes the file extension that this stub generator can handle.
-	 * @return string describing the file extension
-	 */
-	default String fileExtension() {
-		return ".json";
-	}
-
-}
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

-
-
-
-
# Stub converters
-org.springframework.cloud.contract.verifier.converter.StubGenerator=\
-org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter
-
-
-
-

The default implementation is the WireMock stub generation.

-
-
- - - - - -
- - -You can provide multiple stub generator implementations. For example, from a single -DSL, you can produce both WireMock stubs and Pact files. -
-
-
-
-

Using the Custom Stub Runner

-
-

If you decide to use a custom stub generation, you also need a custom way of running -stubs with your different stub provider.

-
-
-

Assume that you use Moco to build your stubs and that -you have written a stub generator and placed your stubs in a JAR file.

-
-
-

In order for Stub Runner to know how to run your stubs, you have to define a custom -HTTP Stub server implementation, which might resemble the following example:

-
-
-
-
package org.springframework.cloud.contract.stubrunner.provider.moco
-
-import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
-import com.github.dreamhead.moco.runner.JsonRunner
-import com.github.dreamhead.moco.runner.RunnerSetting
-import groovy.util.logging.Commons
-
-import org.springframework.cloud.contract.stubrunner.HttpServerStub
-import org.springframework.util.SocketUtils
-
-@Commons
-class MocoHttpServerStub implements HttpServerStub {
-
-	private boolean started
-	private JsonRunner runner
-	private int port
-
-	@Override
-	int port() {
-		if (!isRunning()) {
-			return -1
-		}
-		return port
-	}
-
-	@Override
-	boolean isRunning() {
-		return started
-	}
-
-	@Override
-	HttpServerStub start() {
-		return start(SocketUtils.findAvailableTcpPort())
-	}
-
-	@Override
-	HttpServerStub start(int port) {
-		this.port = port
-		return this
-	}
-
-	@Override
-	HttpServerStub stop() {
-		if (!isRunning()) {
-			return this
-		}
-		this.runner.stop()
-		return this
-	}
-
-	@Override
-	HttpServerStub registerMappings(Collection<File> stubFiles) {
-		List<RunnerSetting> settings = stubFiles.findAll { it.name.endsWith("json") }
-			.collect {
-			log.info("Trying to parse [${it.name}]")
-			try {
-				return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
-					build()
-			}
-			catch (Exception e) {
-				log.warn("Exception occurred while trying to parse file [${it.name}]", e)
-				return null
-			}
-		}.findAll { it }
-		this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
-			HttpArgs.httpArgs().withPort(this.port).build())
-		this.runner.run()
-		this.started = true
-		return this
-	}
-
-	@Override
-	String registeredMappings() {
-		return ""
-	}
-
-	@Override
-	boolean isAccepted(File file) {
-		return file.name.endsWith(".json")
-	}
-}
-
-
-
-

Then, you can register it in your spring.factories file, as shown in the following -example:

-
-
-
-
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
-org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
-
-
-
-

Now you can run stubs with Moco.

-
-
- - - - - -
- - -If you do not provide any implementation, then the default (WireMock) -implementation is used. If you provide more than one, the first one on the list is used. -
-
-
-
-

Using the Custom Stub Downloader

-
-

You can customize the way your stubs are downloaded by creating an implementation of the -StubDownloaderBuilder interface, as shown in the following example:

-
-
-
-
package com.example;
-
-class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
-
-	@Override
-	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
-		return new StubDownloader() {
-			@Override
-			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
-					StubConfiguration config) {
-				File unpackedStubs = retrieveStubs();
-				return new AbstractMap.SimpleEntry<>(
-						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
-								config.getClassifier()), unpackedStubs);
-			}
-
-			File retrieveStubs() {
-			    // here goes your custom logic to provide a folder where all the stubs reside
-			}
-}
-
-
-
-

Then you can register it in your spring.factories file, as shown in the following -example:

-
-
-
-
# Example of a custom Stub Downloader Provider
-org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
-com.example.CustomStubDownloaderBuilder
-
-
-
-

Now you can pick a folder with the source of your stubs.

-
-
- - - - - -
- - -If you do not provide any implementation, then the default is used (scan classpath). -If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or -, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used -If you provide more than one, then the first one on the list is used. -
-
-
-
-

Using the SCM Stub Downloader

-
-

Whenever the repositoryRoot starts with a SCM protocol -(currently we support only git://), the stub downloader will try -to clone the repository and use it as a source of contracts -to generate tests or stubs.

-
-
-

Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader’s behaviour. Below you can find the list of -properties

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

-

* stubrunner.properties.git.branch (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

-

* stubrunner.properties.git.username (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

-

* stubrunner.properties.git.password (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

-

* stubrunner.properties.git.no-of-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

-

* stubrunner.properties.git.wait-between-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

-
-
-

Using the Pact Stub Downloader

-
-

Whenever the repositoryRoot starts with a Pact protocol -(starts with pact://), the stub downloader will try -to fetch the Pact contract definitions from the Pact Broker. -Whatever is set after pact:// will be parsed as the Pact Broker URL.

-
-
-

Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader’s behaviour. Below you can find the list of -properties

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

-

* stubrunner.properties.pactbroker.host (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

-

* stubrunner.properties.pactbroker.port (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

-

* stubrunner.properties.pactbroker.protocol (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

-

* stubrunner.properties.pactbroker.tags (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

-

* stubrunner.properties.pactbroker.auth.scheme (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

-

* stubrunner.properties.pactbroker.auth.username (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

-

* stubrunner.properties.pactbroker.auth.password (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

-

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/spring-cloud-wiremock.html b/reference/html/spring-cloud-wiremock.html index f1d35e0e99..9990b6e5bb 100644 --- a/reference/html/spring-cloud-wiremock.html +++ b/reference/html/spring-cloud-wiremock.html @@ -1,700 +1,12 @@ - - - + + - - - -Spring Cloud Contract WireMock - - + - - - - - - -
-
-

Spring Cloud Contract WireMock

-
-
-

The Spring Cloud Contract WireMock modules let you use WireMock in a -Spring Boot application. Check out the -samples -for more details.

-
-
-

If you have a Spring Boot application that uses Tomcat as an embedded server (which is -the default with spring-boot-starter-web), you can add -spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in -order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you -can register stub behavior using a Java API or via static JSON declarations as part of -your test. The following code shows an example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-@AutoConfigureWireMock(port = 0)
-public class WiremockForDocsTests {
+Page Redirection
 
-	// A service that calls out over HTTP
-	@Autowired
-	private Service service;
-
-	@Before
-	public void setup() {
-		this.service.setBase("http://localhost:"
-				+ this.environment.getProperty("wiremock.server.port"));
-	}
-
-	// Using the WireMock APIs in the normal way:
-	@Test
-	public void contextLoads() throws Exception {
-		// Stubbing WireMock
-		stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
-				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
-		// We're asserting if WireMock responded properly
-		assertThat(this.service.go()).isEqualTo("Hello World!");
-	}
-
-}
-
-
-
-

To start the stub server on a different port use (for example), -@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub -server port can be bound in the test application context with the "wiremock.server.port" -property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to -your test application context, where it will be cached in between methods and classes -having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

-
-
-

Registering Stubs Automatically

-
-

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file -system or classpath (by default, from file:src/test/resources/mappings). You can -customize the locations using the stubs attribute in the annotation, which can be an -Ant-style resource pattern or a directory. In the case of a directory, */.json is -appended. The following code shows an example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureWireMock(stubs="classpath:/stubs")
-public class WiremockImportApplicationTests {
-
-	@Autowired
-	private Service service;
-
-	@Test
-	public void contextLoads() throws Exception {
-		assertThat(this.service.go()).isEqualTo("Hello World!");
-	}
-
-}
-
-
-
- - - - - -
- - -Actually, WireMock always loads mappings from src/test/resources/mappings as -well as the custom locations in the stubs attribute. To change this behavior, you can -also specify a files root as described in the next section of this document. -
-
-
-

If you’re using Spring Cloud Contract’s default stub jars, then your -stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

-
-
-
-
@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")
-
-
-
-
-

Using Files to Specify the Stub Bodies

-
-

WireMock can read response bodies from files on the classpath or the file system. In that -case, you can see in the JSON DSL that the response has a bodyFileName instead of a -(literal) body. The files are resolved relative to a root directory (by default, -src/test/resources/__files). To customize this location you can set the files -attribute in the @AutoConfigureWireMock annotation to the location of the parent -directory (in other words, __files is a subdirectory). You can use Spring resource -notation to refer to file:…​ or classpath:…​ locations. Generic URLs are not -supported. A list of values can be given, in which case WireMock resolves the first file -that exists when it needs to find a response body.

-
-
- - - - - -
- - -When you configure the files root, it also affects the -automatic loading of stubs, because they come from the root location -in a subdirectory called "mappings". The value of files has no -effect on the stubs loaded explicitly from the stubs attribute. -
-
-
-
-

Alternative: Using JUnit Rules

-
-

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop -the server. To do so, use the WireMockSpring convenience class to obtain an Options -instance, as shown in the following example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-public class WiremockForDocsClassRuleTests {
-
-	// Start WireMock on some dynamic port
-	// for some reason `dynamicPort()` is not working properly
-	@ClassRule
-	public static WireMockClassRule wiremock = new WireMockClassRule(
-			WireMockSpring.options().dynamicPort());
-
-	// A service that calls out over HTTP to wiremock's port
-	@Autowired
-	private Service service;
-
-	@Before
-	public void setup() {
-		this.service.setBase("http://localhost:" + wiremock.port());
-	}
-
-	// Using the WireMock APIs in the normal way:
-	@Test
-	public void contextLoads() throws Exception {
-		// Stubbing WireMock
-		wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
-				.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
-		// We're asserting if WireMock responded properly
-		assertThat(this.service.go()).isEqualTo("Hello World!");
-	}
-
-}
-
-
-
-

The @ClassRule means that the server shuts down after all the methods in this class -have been run.

-
-
-
-

Relaxed SSL Validation for Rest Template

-
-

WireMock lets you stub a "secure" server with an "https" URL protocol. If your -application wants to contact that stub server in an integration test, it will find that -the SSL certificates are not valid (the usual problem with self-installed certificates). -The best option is often to re-configure the client to use "http". If that’s not an -option, you can ask Spring to configure an HTTP client that ignores SSL validation errors -(do so only for tests, of course).

-
-
-

To make this work with minimum fuss, you need to be using the Spring Boot -RestTemplateBuilder in your app, as shown in the following example:

-
-
-
-
@Bean
-public RestTemplate restTemplate(RestTemplateBuilder builder) {
-	return builder.build();
-}
-
-
-
-

You need RestTemplateBuilder because the builder is passed through callbacks to -initialize it, so the SSL validation can be set up in the client at that point. This -happens automatically in your test if you are using the @AutoConfigureWireMock -annotation or the stub runner. If you use the JUnit @Rule approach, you need to add the -@AutoConfigureHttpClient annotation as well, as shown in the following example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest("app.baseUrl=https://localhost:6443")
-@AutoConfigureHttpClient
-public class WiremockHttpsServerApplicationTests {
-
-	@ClassRule
-	public static WireMockClassRule wiremock = new WireMockClassRule(
-			WireMockSpring.options().httpsPort(6443));
-...
-}
-
-
-
-

If you are using spring-boot-starter-test, you have the Apache HTTP client on the -classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL -errors. If you use the default java.net client, you do not need the annotation (but it -won’t do any harm). There is no support currently for other clients, but it may be added -in future releases.

-
-
-

To disable the custom RestTemplateBuilder, set the wiremock.rest-template-ssl-enabled -property to false.

-
-
-
-

WireMock and Spring MVC Mocks

-
-

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into -a Spring MockRestServiceServer. The following code shows an example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.NONE)
-public class WiremockForDocsMockServerApplicationTests {
-
-	@Autowired
-	private RestTemplate restTemplate;
-
-	@Autowired
-	private Service service;
-
-	@Test
-	public void contextLoads() throws Exception {
-		// will read stubs classpath
-		MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
-				.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
-				.build();
-		// We're asserting if WireMock responded properly
-		assertThat(this.service.go()).isEqualTo("Hello World");
-		server.verify();
-	}
-
-}
-
-
-
-

The baseUrl value is prepended to all mock calls, and the stubs() method takes a stub -path resource pattern as an argument. In the preceding example, the stub defined at -/stubs/resource.json is loaded into the mock server. If the RestTemplate is asked to -visit https://example.org/, it gets the responses as being declared at that URL. More -than one stub pattern can be specified, and each one can be a directory (for a recursive -list of all ".json"), a fixed filename (as in the example above), or an Ant-style -pattern. The JSON format is the normal WireMock format, which you can read about in the -WireMock website.

-
-
-

Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as -Spring Boot embedded servers, and Wiremock itself has "native" support for a particular -version of Jetty (currently 9.2). To use the native Jetty, you need to add the native -Wiremock dependencies and exclude the Spring Boot container (if there is one).

-
-
-
-

Customization of WireMock configuration

-
-

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type -in order to customize the WireMock configuration (e.g. add custom transformers). -Example:

-
-
-
-
		@Bean
-		WireMockConfigurationCustomizer optionsCustomizer() {
-			return new WireMockConfigurationCustomizer() {
-				@Override
-				public void customize(WireMockConfiguration options) {
-// perform your customization here
-				}
-			};
-		}
-
-
-
-
-

Generating Stubs using REST Docs

-
-

Spring REST Docs can be used to generate -documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc -or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also -generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your -normal REST Docs test cases and use @AutoConfigureRestDocs to have stubs be -automatically generated in the REST Docs output directory. The following code shows an -example using MockMvc:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureMockMvc
-public class ApplicationTests {
-
-	@Autowired
-	private MockMvc mockMvc;
-
-	@Test
-	public void contextLoads() throws Exception {
-		mockMvc.perform(get("/resource"))
-				.andExpect(content().string("Hello World"))
-				.andDo(document("resource"));
-	}
-}
-
-
-
-

This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches -all GET requests to the "/resource" path. The same example with WebTestClient (used -for testing Spring WebFlux applications) would look like this:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureWebTestClient
-public class ApplicationTests {
-
-	@Autowired
-	private WebTestClient client;
-
-	@Test
-	public void contextLoads() throws Exception {
-		client.get().uri("/resource").exchange()
-				.expectBody(String.class).isEqualTo("Hello World")
- 				.consumeWith(document("resource"));
-	}
-}
-
-
-
-

Without any additional configuration, these tests create a stub with a request matcher -for the HTTP method and all headers except "host" and "content-length". To match the -request more precisely (for example, to match the body of a POST or PUT), we need to -explicitly create a request matcher. Doing so has two effects:

-
-
-
    -
  • -

    Creating a stub that matches only in the way you specify.

    -
  • -
  • -

    Asserting that the request in the test case also matches the same conditions.

    -
  • -
-
-
-

The main entry point for this feature is WireMockRestDocs.verify(), which can be used -as a substitute for the document() convenience method, as shown in the following -example:

-
-
-
-
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
-
-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureRestDocs(outputDir = "target/snippets")
-@AutoConfigureMockMvc
-public class ApplicationTests {
-
-	@Autowired
-	private MockMvc mockMvc;
-
-	@Test
-	public void contextLoads() throws Exception {
-		mockMvc.perform(post("/resource")
-                .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
-				.andExpect(status().isOk())
-				.andDo(verify().jsonPath("$.id")
-                        .stub("resource"));
-	}
-}
-
-
-
-

This contract specifies that any valid POST with an "id" field receives the response -defined in this test. You can chain together calls to .jsonPath() to add additional -matchers. If JSON Path is unfamiliar, The JayWay -documentation can help you get up to speed. The WebTestClient version of this test -has a similar verify() static helper that you insert in the same place.

-
-
-

Instead of the jsonPath and contentType convenience methods, you can also use the -WireMock APIs to verify that the request matches the created stub, as shown in the -following example:

-
-
-
-
@Test
-public void contextLoads() throws Exception {
-	mockMvc.perform(post("/resource")
-               .content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
-			.andExpect(status().isOk())
-			.andDo(verify()
-					.wiremock(WireMock.post(
-						urlPathEquals("/resource"))
-						.withRequestBody(matchingJsonPath("$.id"))
-                       .stub("post-resource"));
-}
-
-
-
-

The WireMock API is rich. You can match headers, query parameters, and request body by -regex as well as by JSON path. These features can be used to create stubs with a wider -range of parameters. The above example generates a stub resembling the following example:

-
-
-
post-resource.json
-
-
{
-  "request" : {
-    "url" : "/resource",
-    "method" : "POST",
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$.id"
-    }]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "Hello World",
-    "headers" : {
-      "X-Application-Context" : "application:-1",
-      "Content-Type" : "text/plain"
-    }
-  }
-}
-
-
-
- - - - - -
- - -You can use either the wiremock() method or the jsonPath() and contentType() -methods to create request matchers, but you can’t use both approaches. -
-
-
-

On the consumer side, you can make the resource.json generated earlier in this section -available on the classpath (by -<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a -number of different ways, including by using -@AutoConfigureWireMock(stubs="classpath:resource.json"), as described earlier in this -document.

-
-
-
-

Generating Contracts by Using REST Docs

-
-

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST -Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts -and the stubs.

-
-
-

Why would you want to use this feature? Some people in the community asked questions -about a situation in which they would like to move to DSL-based contract definition, -but they already have a lot of Spring MVC tests. Using this feature lets you generate -the contract files that you can later modify and move to folders (defined in your -configuration) so that the plugin finds them.

-
-
- - - - - -
- - -You might wonder why this functionality is in the WireMock module. The functionality -is there because it makes sense to generate both the contracts and the stubs. -
-
-
-

Consider the following test:

-
-
-
-
		this.mockMvc
-				.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
-						.accept(MediaType.APPLICATION_JSON)
-						.contentType(MediaType.APPLICATION_JSON)
-						.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
-				.andExpect(status().isOk()).andExpect(content().string("bar"))
-				// first WireMock
-				.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
-						.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
-						.contentType(MediaType.valueOf("application/json"))
-						.stub("shouldGrantABeerIfOldEnough"))
-				// then Contract DSL documentation
-				.andDo(document("index", SpringCloudContractRestDocs.dslContract()));
-
-
-
-

The preceding test creates the stub presented in the previous section, generating both -the contract and a documentation file.

-
-
-

The contract is called index.groovy and might look like the following example:

-
-
-
-
import org.springframework.cloud.contract.spec.Contract
-
-Contract.make {
-    request {
-        method 'POST'
-        url '/foo'
-        body('''
-            {"foo": 23 }
-        ''')
-        headers {
-            header('''Accept''', '''application/json''')
-            header('''Content-Type''', '''application/json''')
-        }
-    }
-    response {
-        status OK()
-        body('''
-        bar
-        ''')
-        headers {
-            header('''Content-Type''', '''application/json;charset=UTF-8''')
-            header('''Content-Length''', '''3''')
-        }
-        testMatchers {
-            jsonPath('$[?(@.foo >= 20)]', byType())
-        }
-    }
-}
-
-
-
-

The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be index/dsl-contract.adoc.

-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/using.html b/reference/html/using.html index 892887f3ac..9990b6e5bb 100644 --- a/reference/html/using.html +++ b/reference/html/using.html @@ -1,1235 +1,12 @@ - - - + + - - - -Using Spring Cloud Contract - - - - - - - - - -
-
-
-
-

This section goes into more detail about how you should use Spring Cloud Contract. It covers topics -such as flows of how to work with Spring Cloud Contract. We also -cover some Spring Cloud Contract best practices.

-
-
-

If you are starting out with Spring Cloud Contract, you should probably read the -Getting Started guide before diving into this -section.

-
-
-
-
-

1. Provider Contract Testing with Stubs in Nexus or Artifactory

-
-
-

You can check the Developing Your First Spring Cloud Contract based application link to see the provider contract testing with stubs in the Nexus or Artifactory flow.

-
-
-

You can also check the workshop page for a step-by-step instruction on how to do this flow.

-
-
-
-
-

2. Provider Contract Testing with Stubs in Git

-
-
-

In this flow, we perform the provider contract testing (the producer has no knowledge of how consumers use their API). The stubs are uploaded to a separate repository (they are not uploaded to Artifactory or Nexus).

-
-
-

2.1. Prerequisites

-
-

Before testing provider contracts with stubs in git, you must provide a git repository -that contains all the stubs for each producer. For an example of such a project, see -this samples or this sample. -As a result of pushing stubs there, the repository has the following structure:

-
-
-
-
-
-
$ tree .
-└── META-INF
-   └── folder.with.group.id.as.its.name
-       └── folder-with-artifact-id
-           └── folder-with-version
-               ├── contractA.groovy
-               ├── contractB.yml
-               └── contractC.groovy
-
-
-
-
-
-

You must also provide consumer code that has Spring Cloud Contract Stub Runner set up. For -an example of such a project, see this sample and search for a -BeerControllerGitTest test. You must also provide producer code that has Spring Cloud -Contract set up, together with a plugin. For an example of such a project, see -this sample.

-
-
-
-

2.2. The Flow

-
-

The flow looks exactly as the one presented in -Developing Your First Spring Cloud Contract based application, -but the Stub Storage implementation is a git repository.

-
-
-

You can read more about setting up a git repository and setting consumer and producer side -in the How To page of the documentation.

-
-
-
-

2.3. Consumer setup

-
-

In order to fetch the stubs from a git repository instead of Nexus or Artifactory, you -need to use the git protocol in the URL of the repositoryRoot property in Stub Runner. -The following example shows how to set it up:

-
-
-
-
-
Annotation
-
-
@AutoConfigureStubRunner(
-stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-        repositoryRoot = "git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
-        ids = "com.example:artifact-id:0.0.1")
-
-
-
-
JUnit 4 Rule
-
-
@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example","artifact-id", "0.0.1")
-            .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
JUnit 5 Extension
-
-
@RegisterExtension
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example","artifact-id", "0.0.1")
-            .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
-
-
-

2.4. Setting up the Producer

-
-

In order to push the stubs to a git repository instead of Nexus or Artifactory, you need -to use the git protocol in the URL of the plugin setup. Also you need to explicitly tell -the plugin to push the stubs at the end of the build process. The following example shows -how to do so:

-
-
-
-
-
maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- Base class mappings etc. -->
+Page Redirection
 
-        <!-- We want to pick contracts from a Git repository -->
-        <contractsRepositoryUrl>git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
-
-        <!-- We reuse the contract dependency section to set up the path
-        to the folder that contains the contract definitions. In our case the
-        path will be /groupId/artifactId/version/contracts -->
-        <contractDependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>${project.artifactId}</artifactId>
-            <version>${project.version}</version>
-        </contractDependency>
-
-        <!-- The contracts mode can't be classpath -->
-        <contractsMode>REMOTE</contractsMode>
-    </configuration>
-    <executions>
-        <execution>
-            <phase>package</phase>
-            <goals>
-                <!-- By default we will not push the stubs back to SCM,
-                you have to explicitly add it as a goal -->
-                <goal>pushStubsToScm</goal>
-            </goals>
-        </execution>
-    </executions>
-</plugin>
-
-
-
-
gradle
-
-
contracts {
-    // We want to pick contracts from a Git repository
-    contractDependency {
-        stringNotation = "${project.group}:${project.name}:${project.version}"
-    }
-    /*
-    We reuse the contract dependency section to set up the path
-    to the folder that contains the contract definitions. In our case the
-    path will be /groupId/artifactId/version/contracts
-     */
-    contractRepository {
-        repositoryUrl = "git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
-    }
-    // The mode can't be classpath
-    contractsMode = "REMOTE"
-    // Base class mappings etc.
-}
-
-/*
-In this scenario we want to publish stubs to SCM whenever
-the `publish` task is executed
-*/
-publish.dependsOn("publishStubsToScm")
-
-
-
-
-
-

You can read more about setting up a git repository in the -How To page of the documentation.

-
-
-
-
-
-

3. Consumer Driven Contracts with Contracts on the Producer Side

-
-
-

See Step-by-step Guide to Consumer Driven -Contracts (CDC) with Contracts on the Producer Side to see the Consumer Driven Contracts -with contracts on the producer side flow.

-
-
-
-
-

4. Consumer Driven Contracts with Contracts in an External Repository

-
-
-

In this flow, we perform Consumer Driven Contract testing. The contract definitions are -stored in a separate repository.

-
-
-

See the workshop page -for step-by-step instructions on how to do this flow.

-
-
-

4.1. Prerequisites

-
-

To use consumer-driven contracts with the contracts held in an external repository, you need to set up a git repository that:

-
-
-
    -
  • -

    Contains all the contract definitions for each producer.

    -
  • -
  • -

    Can package the contract definitions in a JAR.

    -
  • -
  • -

    For each contract producer, contains a way (for example, pom.xml) to install stubs -locally through the Spring Cloud Contract Plugin (SCC Plugin)

    -
  • -
-
-
-

For more information, see the How To section, -where we describe how to set up such a repository -For an example of such a project, see this sample.

-
-
-

You also need consumer code that has Spring Cloud Contract Stub Runner set up. -For an example of such a project, see this sample. -You also need producer code that has Spring Cloud Contract set up, together with a plugin. -For an example of such a project, see this sample. -The stub storage is Nexus or Artifactory

-
-
-

At a high level, the flow looks as follows:

-
-
-
    -
  1. -

    The consumer works with the contract definitions from the separate repository

    -
  2. -
  3. -

    Once the consumer’s work is done, a branch with working code is done on the consumer -side and a pull request is made to the separate repository that holds the contract definitions.

    -
  4. -
  5. -

    The producer takes over the pull request to the separate repository with contract -definitions and installs the JAR with all contracts locally.

    -
  6. -
  7. -

    The producer generates tests from the locally stored JAR and writes the missing -implementation to make the tests pass.

    -
  8. -
  9. -

    Once the producer’s work is done, the pull request to the repository that holds the -contract definitions is merged.

    -
  10. -
  11. -

    After the CI tool builds the repository with the contract definitions and the JAR with -contract definitions gets uploaded to Nexus or Artifactory, the producer can merge its branch.

    -
  12. -
  13. -

    Finally, the consumer can switch to working online to fetch stubs of the producer from a -remote location, and the branch can be merged to master.

    -
  14. -
-
-
-
-

4.2. Consumer Flow

-
-

The consumer:

-
-
-
    -
  1. -

    Writes a test that would send a request to the producer.

    -
    -

    The test fails due to no server being present.

    -
    -
  2. -
  3. -

    Clones the repository that holds the contract definitions.

    -
  4. -
  5. -

    Set up the requirements as contracts under the folder with the consumer name as a subfolder of the producer.

    -
    -

    For example, for a producer named producer and a consumer named consumer, the contracts would be stored under src/main/resources/contracts/producer/consumer/)

    -
    -
  6. -
  7. -

    Once the contracts are defined, installs the producer stubs to local storage, as the following example shows:

    -
    -
    -
    -
    -
    $ cd src/main/resource/contracts/producer
    -$ ./mvnw clean install
    -
    -
    -
    -
    -
  8. -
  9. -

    Sets up Spring Cloud Contract (SCC) Stub Runner in the consumer tests, to:

    -
    -
      -
    • -

      Fetch the producer stubs from local storage.

      -
    • -
    • -

      Work in the stubs-per-consumer mode (this enables consumer driven contracts mode).

      -
      -

      The SCC Stub Runner:

      -
      -
    • -
    • -

      Fetches the producer stubs.

      -
    • -
    • -

      Runs an in-memory HTTP server stub with the producer stubs.

      -
    • -
    • -

      Now your test communicates with the HTTP server stub and your tests pass

      -
    • -
    • -

      Create a pull request to the repository with contract definitions, with the new contracts for the producer

      -
    • -
    • -

      Branch your consumer code, until the producer team has merged their code

      -
    • -
    -
    -
  10. -
-
-
-

The following UML diagram shows the consumer flow:

-
-
-
-flow overview consumer cdc external consumer -
-
-
-
-

4.3. Producer Flow

-
-

The producer:

-
-
-
    -
  1. -

    Takes over the pull request to the repository with contract definitions. You can do it -from the command line, as follows

    -
    -
    -
    -
    -
    $ git checkout -b the_branch_with_pull_request master
    -git pull https://github.com/user_id/project_name.git the_branch_with_pull_request
    -
    -
    -
    -
    -
  2. -
  3. -

    Installs the contract definitions, as follows

    -
    -
    -
    -
    -
    $ ./mvnw clean install
    -
    -
    -
    -
    -
  4. -
  5. -

    Sets up the plugin to fetch the contract definitions from a JAR instead of from -src/test/resources/contracts, as follows:

    -
    -
    -
    -
    Maven
    -
    -
    <plugin>
    -    <groupId>org.springframework.cloud</groupId>
    -    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    -    <version>${spring-cloud-contract.version}</version>
    -    <extensions>true</extensions>
    -    <configuration>
    -        <!-- We want to use the JAR with contracts with the following coordinates -->
    -        <contractDependency>
    -            <groupId>com.example</groupId>
    -            <artifactId>beer-contracts</artifactId>
    -        </contractDependency>
    -        <!-- The JAR with contracts should be taken from Maven local -->
    -        <contractsMode>LOCAL</contractsMode>
    -        <!-- ... additional configuration -->
    -    </configuration>
    -</plugin>
    -
    -
    -
    -
    Gradle
    -
    -
    contracts {
    -    // We want to use the JAR with contracts with the following coordinates
    -    // group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
    -    contractDependency {
    -        stringNotation = 'com.example:beer-contracts:+:'
    -    }
    -    // The JAR with contracts should be taken from Maven local
    -    contractsMode = "LOCAL"
    -    // Additional configuration
    -}
    -
    -
    -
    -
    -
  6. -
  7. -

    Runs the build to generate tests and stubs, as follows:

    -
    -
    -
    -
    Maven
    -
    -
    ./mvnw clean install
    -
    -
    -
    -
    Gradle
    -
    -
    ./gradlew clean build
    -
    -
    -
    -
    -
  8. -
  9. -

    Writes the missing implementation, to make the tests pass.

    -
  10. -
  11. -

    Merges the pull request to the repository with contract definitions, as follows:

    -
    -
    -
    -
    -
    $ git commit -am "Finished the implementation to make the contract tests pass"
    -$ git checkout master
    -$ git merge --no-ff the_branch_with_pull_request
    -$ git push origin master
    -
    -
    -
    -
    -
  12. -
  13. -

    The CI system builds the project with the contract definitions and uploads the JAR with -the contract definitions to Nexus or Artifactory.

    -
  14. -
  15. -

    Switches to working remotely.

    -
  16. -
  17. -

    Sets up the plugin so that the contract definitions are no longer taken from the local -storage but from a remote location, as follows:

    -
    -
    -
    -
    Maven
    -
    -
    <plugin>
    -    <groupId>org.springframework.cloud</groupId>
    -    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    -    <version>${spring-cloud-contract.version}</version>
    -    <extensions>true</extensions>
    -    <configuration>
    -        <!-- We want to use the JAR with contracts with the following coordinates -->
    -        <contractDependency>
    -            <groupId>com.example</groupId>
    -            <artifactId>beer-contracts</artifactId>
    -        </contractDependency>
    -        <!-- The JAR with contracts should be taken from a remote location -->
    -        <contractsMode>REMOTE</contractsMode>
    -        <!-- ... additional configuration -->
    -    </configuration>
    -</plugin>
    -
    -
    -
    -
    Gradle
    -
    -
    contracts {
    -    // We want to use the JAR with contracts with the following coordinates
    -    // group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
    -    contractDependency {
    -        stringNotation = 'com.example:beer-contracts:+:'
    -    }
    -    // The JAR with contracts should be taken from a remote location
    -    contractsMode = "REMOTE"
    -    // Additional configuration
    -}
    -
    -
    -
    -
    -
  18. -
  19. -

    Merges the producer code with the new implementation.

    -
  20. -
  21. -

    The CI system:

    -
    -
      -
    • -

      Builds the project

      -
    • -
    • -

      Generates tests, stubs, and the stub JAR

      -
    • -
    • -

      Uploads the artifact with the application and the stubs to Nexus or Artifactory.

      -
    • -
    -
    -
  22. -
-
-
-

The following UML diagram shows the producer process:

-
-
-
-flow overview consumer cdc external producer -
-
-
-
-
-
-

5. Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git

-
-
-

You can check Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side to see the consumer driven contracts with contracts on the producer side flow.

-
-
-

The stub storage implementation is a git repository. We describe its setup in the -Provider Contract Testing with Stubs in Git section.

-
-
-

You can read more about setting up a git repository for the consumer and producer sides in -the How To page of the documentation.

-
-
-
-
-

6. Provider Contract Testing with Stubs in Artifactory for a non-Spring Application

-
-
-

6.1. The Flow

-
-

You can check Developing Your First Spring Cloud Contract based application to see the flow for provider contract testing with stubs in Nexus or Artifactory.

-
-
-
-

6.2. Setting up the Consumer

-
-

For the consumer side, you can use a JUnit rule. That way, you need not start a Spring context. The follwoing listing shows such a rule (in JUnit4 and JUnit 5);

-
-
-
-
-
JUnit 4 Rule
-
-
@Rule
-    public StubRunnerRule rule = new StubRunnerRule()
-            .downloadStub("com.example","artifact-id", "0.0.1")
-            .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
JUnit 5 Extension
-
-
@Rule
-    public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
-            .downloadStub("com.example","artifact-id", "0.0.1")
-            .repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
-            .stubsMode(StubRunnerProperties.StubsMode.REMOTE);
-
-
-
-
-
-
-

6.3. Setting up the Producer

-
-

By default, the Spring Cloud Contract Plugin uses Rest Assured’s MockMvc setup for the -generated tests. Since non-Spring applications do not use MockMvc, you can change the -testMode to EXPLICIT to send a real request to an application bound at a specific port.

-
-
-

In this example, we use a framework called Javalin to start a -non-Spring HTTP server.

-
-
-

Assume that we have the following application:

-
-
-
-
-
-
package com.example.demo;
-
-import io.javalin.Javalin;
-
-public class DemoApplication {
-
-    public static void main(String[] args) {
-        new DemoApplication().run(7000);
-    }
-
-    public Javalin start(int port) {
-        return Javalin.create().start(port);
-    }
-
-    public Javalin registerGet(Javalin app) {
-        return app.get("/", ctx -> ctx.result("Hello World"));
-    }
-
-    public Javalin run(int port) {
-        return registerGet(start(port));
-    }
-
-}
-
-
-
-
-
-

Given that application, we can set up the plugin to use the EXPLICIT mode (that is, to -send out requests to a real port), as follows:

-
-
-
-
-
maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <baseClassForTests>com.example.demo.BaseClass</baseClassForTests>
-        <!-- This will setup the EXPLICIT mode for the tests -->
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
gradle
-
-
contracts {
-    // This will setup the EXPLICIT mode for the tests
-    testMode = "EXPLICIT"
-    baseClassForTests = "com.example.demo.BaseClass"
-}
-
-
-
-
-
-

The base class might resemble the following:

-
-
-
-
-
-
import io.javalin.Javalin;
-import io.restassured.RestAssured;
-import org.junit.After;
-import org.junit.Before;
-import org.springframework.util.SocketUtils;
-
-public class BaseClass {
-
-    Javalin app;
-
-    @Before
-    public void setup() {
-        // pick a random port
-        int port = SocketUtils.findAvailableTcpPort();
-        // start the application at a random port
-        this.app = start(port);
-        // tell Rest Assured where the started application is
-        RestAssured.baseURI = "http://localhost:" + port;
-    }
-
-    @After
-    public void close() {
-        // stop the server after each test
-        this.app.stop();
-    }
-
-    private Javalin start(int port) {
-        // reuse the production logic to start a server
-        return new DemoApplication().run(port);
-    }
-}
-
-
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    We have setup the Spring Cloud Contract plugin to use the EXPLICIT mode to send real -requests instead of mocked ones.

    -
  • -
  • -

    We have defined a base class that:

    -
    -
      -
    • -

      Starts the HTTP server on a random port for each test.

      -
    • -
    • -

      Sets Rest Assured to send requests to that port.

      -
    • -
    • -

      Closes the HTTP server after each test.

      -
    • -
    -
    -
  • -
-
-
-
-
-
-

7. Provider Contract Testing with Stubs in Artifactory in a non-JVM World

-
-
-

In this flow, we assume that:

-
-
-
    -
  • -

    The API Producer and API Consumer are non-JVM applications.

    -
  • -
  • -

    The contract definitions are written in YAML.

    -
  • -
  • -

    The Stub Storage is Artifactory or Nexus.

    -
  • -
  • -

    Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker -(SCC Stub Runner Docker) images are used.

    -
  • -
-
-
-

You can read more about how to use Spring Cloud Contract with Docker in this page.

-
-
-

Here, you can -read a blog post about how to use Spring Cloud Contract in a polyglot world.

-
-
-

Here, you can find -a sample of a NodeJS application that uses Spring Cloud Contract both as a producer and a -consumer.

-
-
-

7.1. Producer Flow

-
-

At a high level, the producer:

-
-
-
    -
  1. -

    Writes contract definitions (for example, in YAML).

    -
  2. -
  3. -

    Sets up the build tool to:

    -
    -
      -
    1. -

      Start the application with mocked services on a given port.

      -
      -

      If mocking is not possible, you can setup the infrastructure and define tests in a stateful way.

      -
      -
    2. -
    3. -

      Run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable.

      -
    4. -
    -
    -
  4. -
-
-
-

The SCC Docker image: -* Generates the tests from the attached volume. -* Runs the tests against the running application.

-
-
-

Upon test completion, stubs get uploaded to a stub storage site (such as Artifactory or Git).

-
-
-

The following UML diagram shows the producer flow:

-
-
-
-flows provider non jvm producer -
-
-
-
-

7.2. Consumer Flow

-
-

At a high level, the consumer:

-
-
-
    -
  1. -

    Sets up the build tool to:

    -
    -
      -
    • -

      Start the Spring Cloud Contract Stub Runner Docker image and start the stubs.

      -
      -

      The environment variables configure:

      -
      -
    • -
    • -

      The stubs to fetch.

      -
    • -
    • -

      The location of the repositories.

      -
      -

      Note that:

      -
      -
    • -
    • -

      To use the local storage, you can also attach it as a volume.

      -
    • -
    • -

      The ports at which the stubs are running need to be exposed.

      -
    • -
    -
    -
  2. -
  3. -

    Run the application tests against the running stubs.

    -
  4. -
-
-
-

The following UML diagram shows the consumer flow:

-
-
-
-flows provider non jvm consumer -
-
-
-
-
-
-

8. Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory

-
-
-

In this flow, we do not use a Spring Cloud Contract plugin to generate tests and stubs. We write Spring RESTDocs and, from them, we automatically generate stubs. Finally, we set up our builds to package the stubs and upload them to the stub storage site — in our case, Nexus or Artifactory.

-
-
-

See the workshop page for a step-by-step instruction on how to use this flow.

-
-
-

8.1. Producer Flow

-
-

As a producer, we:

-
-
-
    -
  1. -

    We write RESTDocs tests of our API.

    -
  2. -
  3. -

    We add Spring Cloud Contract Stub Runner starter to our build (spring-cloud-starter-contract-stub-runner), as follows

    -
    -
    -
    -
    maven
    -
    -
    <dependencies>
    -    <dependency>
    -        <groupId>org.springframework.cloud</groupId>
    -        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    -        <scope>test</scope>
    -    </dependency>
    -</dependencies>
    -
    -<dependencyManagement>
    -    <dependencies>
    -        <dependency>
    -            <groupId>org.springframework.cloud</groupId>
    -            <artifactId>spring-cloud-dependencies</artifactId>
    -            <version>${spring-cloud.version}</version>
    -            <type>pom</type>
    -            <scope>import</scope>
    -        </dependency>
    -    </dependencies>
    -</dependencyManagement>
    -
    -
    -
    -
    gradle
    -
    -
    dependencies {
    -    testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
    -}
    -
    -dependencyManagement {
    -    imports {
    -        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    -    }
    -}
    -
    -
    -
    -
    -
  4. -
  5. -

    We set up the build tool to package our stubs, as follows:

    -
    -
    -
    -
    maven
    -
    -
    <!-- pom.xml -->
    -<plugins>
    -    <plugin>
    -        <groupId>org.apache.maven.plugins</groupId>
    -        <artifactId>maven-assembly-plugin</artifactId>
    -        <executions>
    -            <execution>
    -                <id>stub</id>
    -                <phase>prepare-package</phase>
    -                <goals>
    -                    <goal>single</goal>
    -                </goals>
    -                <inherited>false</inherited>
    -                <configuration>
    -                    <attach>true</attach>
    -                    <descriptors>
    -                        ${basedir}/src/assembly/stub.xml
    -                    </descriptors>
    -                </configuration>
    -            </execution>
    -        </executions>
    -    </plugin>
    -</plugins>
    -
    -<!-- src/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">
    -    <id>stubs</id>
    -    <formats>
    -        <format>jar</format>
    -    </formats>
    -    <includeBaseDirectory>false</includeBaseDirectory>
    -    <fileSets>
    -        <fileSet>
    -            <directory>${project.build.directory}/generated-snippets/stubs</directory>
    -            <outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
    -            <includes>
    -                <include>**/*</include>
    -            </includes>
    -        </fileSet>
    -    </fileSets>
    -</assembly>
    -
    -
    -
    -
    gradle
    -
    -
    task stubsJar(type: Jar) {
    -    classifier = "stubs"
    -    into("META-INF/${project.group}/${project.name}/${project.version}/mappings") {
    -        include('**/*.*')
    -        from("${project.buildDir}/generated-snippets/stubs")
    -    }
    -}
    -// we need the tests to pass to build the stub jar
    -stubsJar.dependsOn(test)
    -bootJar.dependsOn(stubsJar)
    -
    -
    -
    -
    -
  6. -
-
-
-

Now, when we run the tests, stubs are automatically published and packaged.

-
-
-

The following UML diagram shows the producer flow:

-
-
-
-flows provider rest docs producer -
-
-
-
-

8.2. Consumer Flow

-
-

Since the consumer flow is not affected by the tool used to generate the stubs, you can check Developing Your First Spring Cloud Contract based application to see the flow for consumer side of the provider contract testing with stubs in Nexus or Artifactory.

-
-
-
-
-
-

9. What to Read Next

-
-
-

You should now understand how you can use Spring Cloud Contract and some best practices that you -should follow. You can now go on to learn about specific -Spring Cloud Contract features, or you could -skip ahead and read about the advanced features of Spring Cloud Contract.

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_contract.html b/reference/html/verifier_contract.html index 6657dc32b1..9990b6e5bb 100644 --- a/reference/html/verifier_contract.html +++ b/reference/html/verifier_contract.html @@ -1,2993 +1,12 @@ - - - + + - - - -Contract DSL - - + - - - - - - -
-
-

Contract DSL

-
-
-

Spring Cloud Contract supports out of the box 2 types of DSL. One written in -Groovy and one written in YAML.

-
-
-

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy -before. Knowledge of the language is not really needed, as the Contract DSL uses only a -tiny subset of it (only literals, method calls and closures). Also, the DSL is statically -typed, to make it programmer-readable without any knowledge of the DSL itself.

-
-
- - - - - -
- - -Remember that, inside the Groovy contract file, you have to provide the fully -qualified name to the Contract class and make static imports, such as -org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to -the Contract class: import org.springframework.cloud.spec.Contract and then call -Contract.make { …​ }. -
-
-
- - - - - -
- - -Spring Cloud Contract supports defining multiple contracts in a single file. -
-
-
-

The following is a complete example of a Groovy contract definition:

-
-
-
-
-
-
-
-

The following is a complete example of a YAML contract definition:

-
-
-
-
-
-
-
- - - - - -
- - -You can compile contracts to stubs mapping using standalone maven command: -mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert -
-
-
-

Limitations

-
- - - - - -
- - -Spring Cloud Contract Verifier does not properly support XML. Please use JSON or -help us implement this feature. -
-
-
- - - - - -
- - -The support for verifying the size of JSON arrays is experimental. If you want -to turn it on, please set the value of the following system property to true: -spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. -You can also provide the assertJsonSize property in the plugin configuration. -
-
-
- - - - - -
- - -Because JSON structure can have any form, it can be impossible to parse it -properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That -is why you should use the Groovy Map notation. -
-
-
-
-

Common Top-Level elements

-
-

The following sections describe the most common top-level elements:

-
- -
-

Description

-
-

You can add a description to your contract. The description is arbitrary text. The -following code shows an example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-
-

Name

-
-

You can provide a name for your contract. Assume that you provided the following name: -should register a user. If you do so, the name of the autogenerated test is -validate_should_register_a_user. Also, the name of the stub in a WireMock stub is -should_register_a_user.json.

-
-
- - - - - -
- - -You must ensure that the name does not contain any characters that make the -generated test not compile. Also, remember that, if you provide the same name for -multiple contracts, your autogenerated tests fail to compile and your generated stubs -override each other. -
-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-
-

Ignoring Contracts

-
-

If you want to ignore a contract, you can either set a value of ignored contracts in the -plugin configuration or set the ignored property on the contract itself:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-
-

Passing Values from Files

-
-

Starting with version 1.2.0, you can pass values from files. Assume that you have the -following resources in our project.

-
-
-
-
└── src
-    └── test
-        └── resources
-            └── contracts
-                ├── readFromFile.groovy
-                ├── request.json
-                └── response.json
-
-
-
-

Further assume that your contract is as follows:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

Further assume that the JSON files is as follows:

-
-
-

request.json

-
-
-
-
-
-
-
-

response.json

-
-
-
-
-
-
-
-

When test or stub generation takes place, the contents of the file is passed to the body -of a request or a response. The name of the file needs to be a file with location -relative to the folder in which the contract lays.

-
-
-

If you need to pass the contents of a file in a binary form -it’s enough for you to use the fileAsBytes method in Groovy DSL or bodyFromFileAsBytes field in YAML.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
- - - - - -
- - -You should use this approach whenever you want to work with binary payloads both for HTTP and messaging. -
-
-
-
-

HTTP Top-Level Elements

-
-

The following methods can be called in the top-level closure of a contract definition. -request and response are mandatory. priority is optional.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-...
-
-
-
- - - - - -
- - -If you want to make your contract have a higher value of priority -you need to pass a lower number to the priority tag / method. E.g. priority with -value 5 has higher priority than priority with value 10. -
-
-
-
-
-

Request

-
-

The HTTP protocol requires only method and url to be specified in a request. The -same information is mandatory in request definition of the Contract.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

It is possible to specify an absolute rather than relative url, but using urlPath is -the recommended way, as doing so makes the tests host-independent.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

request may contain query parameters.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-
-
-
-

request may contain additional request headers, as shown in the following example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-
-
-
-

request may contain additional request cookies, as shown in the following example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-
-
-
-

request may contain a request body:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-
-
-
-

request may contain multipart elements. To include multipart elements, use the -multipart method/section, as shown in the following examples

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

In the preceding example, we define parameters in either of two ways:

-
-
-
Groovy DSL
-
    -
  • -

    Directly, by using the map notation, where the value can be a dynamic property (such as -formParameter: $(consumer(…​), producer(…​))).

    -
  • -
  • -

    By using the named(…​) method that lets you set a named parameter. A named parameter -can set a name and content. You can call it either via a method with two arguments, -such as named("fileName", "fileContent"), or via a map notation, such as -named(name: "fileName", content: "fileContent").

    -
  • -
-
-
-
YAML
-
    -
  • -

    The multipart parameters are set via multipart.params section

    -
  • -
  • -

    The named parameters (the fileName and fileContent for a given parameter name) -can be set via the multipart.named section. That section contains -the paramName (name of the parameter), fileName (name of the file), -fileContent (content of the file) fields

    -
  • -
  • -

    The dynamic bits can be set via the matchers.multipart section

    -
    -
      -
    • -

      for parameters use the params section that can accept -regex or a predefined regular expression

      -
    • -
    • -

      for named params use the named section where first you -define the parameter name via paramName and then you can pass the -parametrization of either fileName or fileContent via -regex or a predefined regular expression

      -
    • -
    -
    -
  • -
-
-
-

From this contract, the generated test is as follows:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
-   .param("formParameter", "\"formParameterValue\"")
-   .param("someBooleanParameter", "true")
-   .multiPart("file", "filename.csv", "file content".getBytes());
+Page Redirection
 
-// when:
- ResponseOptions response = given().spec(request)
-   .put("/multipart");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-

The WireMock stub is as follows:

-
-
-
-
-
-
-
-
-

Response

-
-

The response must contain an HTTP status code and may contain other information. The -following code shows an example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
...
-
-
-
-

Besides status, the response may contain headers, cookies and a body, both of which are -specified the same way as in the request (see the previous paragraph).

-
-
- - - - - -
- - -Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus -methods to provide a meaningful status instead of a digit. E.g. you can call -OK() for a status 200 or BAD_REQUEST() for 400. -
-
-
-
-

Dynamic properties

-
-

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not -want to force the consumers to stub their clocks to always return the same value of time -so that it gets matched by the stub.

-
-
-

For Groovy DSL you can provide the dynamic parts in your contracts -in two ways: pass them directly in the body or set them in a separate section called -bodyMatchers.

-
-
- - - - - -
- - -Before 2.0.0 these were set using testMatchers and stubMatchers, -check out the migration guide for more information. -
-
-
-

For YAML you can only use the matchers section.

-
-
-

Dynamic properties inside the body

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can set the properties inside the body either with the value method or, if you use -the Groovy map notation, with $(). The following example shows how to set dynamic -properties with the value method:

-
-
-
-
value(consumer(...), producer(...))
-value(c(...), p(...))
-value(stub(...), test(...))
-value(client(...), server(...))
-
-
-
-

The following example shows how to set dynamic properties with $():

-
-
-
-
$(consumer(...), producer(...))
-$(c(...), p(...))
-$(stub(...), test(...))
-$(client(...), server(...))
-
-
-
-

Both approaches work equally well. stub and client methods are aliases over the consumer -method. Subsequent sections take a closer look at what you can do with those values.

-
-
-
-

Regular expressions

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can use regular expressions to write your requests in Contract DSL. Doing so is -particularly useful when you want to indicate that a given response should be provided -for requests that follow a given pattern. Also, you can use regular expressions when you -need to use patterns and not exact values both for your test and your server side tests.

-
-
-

Make sure that regex matches a whole region of a sequence as internally a call to -Pattern.matches() -is called. For instance, abc pattern doesn’t match aabc string but .abc does. -There are several additional known limitations as well.

-
-
-

The following example shows how to use regular expressions to write a request:

-
-
-
-
-
-
-
-

You can also provide only one side of the communication with a regular expression. If you -do so, then the contract engine automatically provides the generated string that matches -the provided regular expression. The following code shows an example:

-
-
-
-
-
-
-
-

In the preceding example, the opposite side of the communication has the respective data -generated for request and response.

-
-
-

Spring Cloud Contract comes with a series of predefined regular expressions that you can -use in your contracts, as shown in the following example:

-
-
-
-
-
-
-
-

In your contract, you can use it as shown in the following example:

-
-
-
-
-
-
-
-

To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed. -All of those methods start with any prefix:

-
-
-
-
-
-
-
-

and this is an example of how you can reference those methods:

-
-
-
-
-
-
-
-
Limitations
-
- - - - - -
- - -Due to certain limitations of Xeger library that generates string out of -regex, do not use $ and ^ signs in your regex if you rely on automatic -generation. Issue 899 -
-
-
- - - - - -
- - -Do not use LocalDate instance as a value for $ like this $(consumer(LocalDate.now())). -It causes java.lang.StackOverflowError. Use $(consumer(LocalDate.now().toString())) instead. -Issue 900 -
-
-
-
-
-

Passing Optional Parameters

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

It is possible to provide optional parameters in your contract. However, you can provide -optional parameters only for the following:

-
-
-
    -
  • -

    STUB side of the Request

    -
  • -
  • -

    TEST side of the Response

    -
  • -
-
-
-

The following example shows how to provide optional parameters:

-
-
-
-
-
-
-
-

By wrapping a part of the body with the optional() method, you create a regular -expression that must be present 0 or more times.

-
-
-

If you use Spock for, the following test would be generated from the previous example:

-
-
-
-
-
-
-
-

The following stub would also be generated:

-
-
-
-
-
-
-
-
-

Executing Custom Methods on the Server Side

-
- - - - - -
- - -This section is valid only for Groovy DSL. Check out the -Dynamic Properties in the Matchers Sections section for YAML examples of a similar feature. -
-
-
-

You can define a method call that executes on the server side during the test. Such a -method can be added to the class defined as "baseClassForTests" in the configuration. The -following code shows an example of the contract portion of the test case:

-
-
-
-
-
-
-
-

The following code shows the base class portion of the test case:

-
-
-
-
-
-
-
- - - - - -
- - -You cannot use both a String and execute to perform concatenation. For -example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to -improper results. Instead, call header('Authorization', execute('authToken()')) and -ensure that the authToken() method returns everything you need. -
-
-
-

The type of the object read from the JSON can be one of the following, depending on the -JSON path:

-
-
-
    -
  • -

    String: If you point to a String value in the JSON.

    -
  • -
  • -

    JSONArray: If you point to a List in the JSON.

    -
  • -
  • -

    Map: If you point to a Map in the JSON.

    -
  • -
  • -

    Number: If you point to Integer, Double etc. in the JSON.

    -
  • -
  • -

    Boolean: If you point to a Boolean in the JSON.

    -
  • -
-
-
-

In the request part of the contract, you can specify that the body should be taken from -a method.

-
-
- - - - - -
- - -You must provide both the consumer and the producer side. The execute part -is applied for the whole body - not for parts of it. -
-
-
-

The following example shows how to read an object from JSON:

-
-
-
-
-
-
-
-

The preceding example results in calling the hashCode() method in the request body. -It should resemble the following code:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .body(hashCode());
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/something");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
-
-
-
-
-

Referencing the Request from the Response

-
-

The best situation is to provide fixed values, but sometimes you need to reference a -request in your response.

-
-
-

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets -you reference a bunch of elements from the HTTP request. You can use the following -options:

-
-
-
    -
  • -

    fromRequest().url(): Returns the request URL and query parameters.

    -
  • -
  • -

    fromRequest().query(String key): Returns the first query parameter with a given name.

    -
  • -
  • -

    fromRequest().query(String key, int index): Returns the nth query parameter with a -given name.

    -
  • -
  • -

    fromRequest().path(): Returns the full path.

    -
  • -
  • -

    fromRequest().path(int index): Returns the nth path element.

    -
  • -
  • -

    fromRequest().header(String key): Returns the first header with a given name.

    -
  • -
  • -

    fromRequest().header(String key, int index): Returns the nth header with a given name.

    -
  • -
  • -

    fromRequest().body(): Returns the full request body.

    -
  • -
  • -

    fromRequest().body(String jsonPath): Returns the element from the request that -matches the JSON Path.

    -
  • -
-
-
-

If you’re using the YAML contract definition you have to use the -Handlebars {{{ }}} notation with custom, Spring Cloud Contract - functions to achieve this.

-
-
-
    -
  • -

    {{{ request.url }}}: Returns the request URL and query parameters.

    -
  • -
  • -

    {{{ request.query.key.[index] }}}: Returns the nth query parameter with a given name. -E.g. for key foo, first entry {{{ request.query.foo.[0] }}}

    -
  • -
  • -

    {{{ request.path }}}: Returns the full path.

    -
  • -
  • -

    {{{ request.path.[index] }}}: Returns the nth path element. E.g. -for first entry `{{{ request.path.[0] }}}

    -
  • -
  • -

    {{{ request.headers.key }}}: Returns the first header with a given name.

    -
  • -
  • -

    {{{ request.headers.key.[index] }}}: Returns the nth header with a given name.

    -
  • -
  • -

    {{{ request.body }}}: Returns the full request body.

    -
  • -
  • -

    {{{ jsonpath this 'your.json.path' }}}: Returns the element from the request that -matches the JSON Path. E.g. for json path $.foo - {{{ jsonpath this '$.foo' }}}

    -
  • -
-
-
-

Consider the following contract:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

Running a JUnit test generation leads to a test that resembles the following example:

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Authorization", "secret")
-   .header("Authorization", "secret2")
-   .body("{\"foo\":\"bar\",\"baz\":5}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .queryParam("foo","bar")
-   .queryParam("foo","bar2")
-   .get("/api/v1/xxxx");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
- assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
- assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
- assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
- assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
- assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
- assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
- assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
- assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
- assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
-
-
-
-

As you can see, elements from the request have been properly referenced in the response.

-
-
-

The generated WireMock stub should resemble the following example:

-
-
-
-
{
-  "request" : {
-    "urlPath" : "/api/v1/xxxx",
-    "method" : "POST",
-    "headers" : {
-      "Authorization" : {
-        "equalTo" : "secret2"
-      }
-    },
-    "queryParameters" : {
-      "foo" : {
-        "equalTo" : "bar2"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['baz'] == 5)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
-    "headers" : {
-      "Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
-    },
-    "transformers" : [ "response-template" ]
-  }
-}
-
-
-
-

Sending a request such as the one presented in the request part of the contract results -in sending the following response body:

-
-
-
-
{
-  "url" : "/api/v1/xxxx?foo=bar&foo=bar2",
-  "path" : "/api/v1/xxxx",
-  "pathIndex" : "v1",
-  "param" : "bar",
-  "paramIndex" : "bar2",
-  "authorization" : "secret",
-  "authorization2" : "secret2",
-  "fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
-  "responseFoo" : "bar",
-  "responseBaz" : 5,
-  "responseBaz2" : "Bla bla bar bla bla"
-}
-
-
-
- - - - - -
- - -This feature works only with WireMock having a version greater than or equal -to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s -response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into -proper values. Additionally, it registers two helper functions: -
-
-
-
    -
  • -

    escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.

    -
  • -
  • -

    jsonpath: For a given parameter, find an object in the request body.

    -
  • -
-
-
-
-

Registering Your Own WireMock Extension

-
-

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers -the transformer, which lets you reference a request from a response. If you want to -provide your own extensions, you can register an implementation of the -org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions interface. -Since we use the spring.factories extension approach, you can create an entry in -META-INF/spring.factories file similar to the following:

-
-
-
-
-
-
-
-

The following is an example of a custom extension:

-
-
-
TestWireMockExtensions.groovy
-
-
-
-
-
- - - - - -
- - -Remember to override the applyGlobally() method and set it to false if you -want the transformation to be applied only for a mapping that explicitly requires it. -
-
-
-
-

Dynamic Properties in the Matchers Sections

-
-

If you work with Pact, the following discussion may seem familiar. -Quite a few users are used to having a separation between the body and setting the -dynamic parts of a contract.

-
-
-

You can use the bodyMatchers section for two reasons:

-
-
-
    -
  • -

    Define the dynamic values that should end up in a stub. -You can set it in the request or inputMessage part of your contract.

    -
  • -
  • -

    Verify the result of your test. -This section is present in the response or outputMessage side of the -contract.

    -
  • -
-
-
-

Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the -following matching possibilities:

-
-
-
Groovy DSL
-
    -
  • -

    For the stubs(in tests on the Consumer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the consumer’s request via the provided JSON Path must be -equal to the value provided in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the consumer’s request via the provided JSON Path must -match the regex. You can also pass the type of the expected matched value (e.g. asString(), asLong() etc.)

      -
    • -
    • -

      byDate(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the consumer’s request via the provided JSON Path must -match the regex for an ISO Time value.

      -
    • -
    -
    -
  • -
  • -

    For the verification(in generated tests on the Producer’s side):

    -
    -
      -
    • -

      byEquality(): The value taken from the producer’s response via the provided JSON Path must be -equal to the provided value in the contract.

      -
    • -
    • -

      byRegex(…​): The value taken from the producer’s response via the provided JSON Path must -match the regex.

      -
    • -
    • -

      byDate(): The value taken from the producer’s response via the provided JSON Path must match -the regex for an ISO Date value.

      -
    • -
    • -

      byTimestamp(): The value taken from the producer’s response via the provided JSON Path must -match the regex for an ISO DateTime value.

      -
    • -
    • -

      byTime(): The value taken from the producer’s response via the provided JSON Path must match -the regex for an ISO Time value.

      -
    • -
    • -

      byType(): The value taken from the producer’s response via the provided JSON Path needs to be -of the same type as the type defined in the body of the response in the contract. -byType can take a closure, in which you can set minOccurrence and maxOccurrence. For the request side, you should use the closure to assert size of the collection. -That way, you can assert the size of the flattened collection. To check the size of an -unflattened collection, use a custom method with the byCommand(…​) testMatcher.

      -
    • -
    • -

      byCommand(…​): The value taken from the producer’s response via the provided JSON Path is -passed as an input to the custom method that you provide. For example, -byCommand('foo($it)') results in calling a foo method to which the value matching the -JSON Path gets passed. The type of the object read from the JSON can be one of the -following, depending on the JSON path:

      -
      -
        -
      • -

        String: If you point to a String value.

        -
      • -
      • -

        JSONArray: If you point to a List.

        -
      • -
      • -

        Map: If you point to a Map.

        -
      • -
      • -

        Number: If you point to Integer, Double, or other kind of number.

        -
      • -
      • -

        Boolean: If you point to a Boolean.

        -
      • -
      -
      -
    • -
    • -

      byNull(): The value taken from the response via the provided JSON Path must be null

      -
    • -
    -
    -
  • -
-
-
-
YAML
-

Please read the Groovy section for detailed explanation of -what the types mean

-
-
-

For YAML the structure of a matcher looks like this

-
-
-
-
- path: $.foo
-  type: by_regex
-  value: bar
-  regexType: as_string
-
-
-
-

Or if you want to use one of the predefined regular expressions -[only_alpha_unicode, number, any_boolean, ip_address, hostname, -email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]:

-
-
-
-
- path: $.foo
-  type: by_regex
-  predefined: only_alpha_unicode
-
-
-
-

Below you can find the allowed list of `type`s.

-
-
-
    -
  • -

    For stubMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        -
      • -
      -
      -
    • -
    -
    -
  • -
  • -

    For testMatchers:

    -
    -
      -
    • -

      by_equality

      -
    • -
    • -

      by_regex

      -
    • -
    • -

      by_date

      -
    • -
    • -

      by_timestamp

      -
    • -
    • -

      by_time

      -
    • -
    • -

      by_type

      -
      -
        -
      • -

        there are 2 additional fields accepted: minOccurrence and maxOccurrence.

        -
      • -
      -
      -
    • -
    • -

      by_command

      -
    • -
    • -

      by_null

      -
    • -
    -
    -
  • -
-
-
-

You can also define which type the regular expression corresponds to via the regexType field. Below you can find the allowed list of regular expression types:

-
-
-
    -
  • -

    as_integer

    -
  • -
  • -

    as_double

    -
  • -
  • -

    as_float,

    -
  • -
  • -

    as_long

    -
  • -
  • -

    as_short

    -
  • -
  • -

    as_boolean

    -
  • -
  • -

    as_string

    -
  • -
-
-
-

Consider the following example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

In the preceding example, you can see the dynamic portions of the contract in the -matchers sections. For the request part, you can see that, for all fields but -valueWithoutAMatcher, the values of the regular expressions that the stub should -contain are explicitly set. For the valueWithoutAMatcher, the verification takes place -in the same way as without the use of matchers. In that case, the test performs an -equality check.

-
-
-

For the response side in the bodyMatchers section, we define the dynamic parts in a -similar manner. The only difference is that the byType matchers are also present. The -verifier engine checks four fields to verify whether the response from the test -has a value for which the JSON path matches the given field, is of the same type as the one -defined in the response body, and passes the following check (based on the method being called):

-
-
-
    -
  • -

    For $.valueWithTypeMatch, the engine checks whether the type is the same.

    -
  • -
  • -

    For $.valueWithMin, the engine check the type and asserts whether the size is greater -than or equal to the minimum occurrence.

    -
  • -
  • -

    For $.valueWithMax, the engine checks the type and asserts whether the size is -smaller than or equal to the maximum occurrence.

    -
  • -
  • -

    For $.valueWithMinMax, the engine checks the type and asserts whether the size is -between the min and maximum occurrence.

    -
  • -
-
-
-

The resulting test would resemble the following example (note that an and section -separates the autogenerated assertions and the assertion from matchers):

-
-
-
-
// given:
- MockMvcRequestSpecification request = given()
-   .header("Content-Type", "application/json")
-   .body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\",\"key\":{\"complex.key\":\"foo\"}}");
-
-// when:
- ResponseOptions response = given().spec(request)
-   .get("/get");
-
-// then:
- assertThat(response.statusCode()).isEqualTo(200);
- assertThat(response.header("Content-Type")).matches("application/json.*");
-// and:
- DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
- assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
-// and:
- assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
- assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
- assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
- assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
- assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
- assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
- assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
- assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
- assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
- assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
- assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
- assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
- assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
- assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
- assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
- assertThatValueIsANumber(parsedJson.read("$.duck"));
- assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");
-
-
-
- - - - - -
- - -Notice that, for the byCommand method, the example calls the -assertThatValueIsANumber. This method must be defined in the test base class or be -statically imported to your tests. Notice that the byCommand call was converted to -assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took -the method name and passed the proper JSON path as a parameter to it. -
-
-
-

The resulting WireMock stub is in the following example:

-
-
-
-
-
-
-
- - - - - -
- - -If you use a matcher, then the part of the request and response that the -matcher addresses with the JSON Path gets removed from the assertion. In the case of -verifying a collection, you must create matchers for all the elements of the -collection. -
-
-
-

Consider the following example:

-
-
-
-
Contract.make {
-    request {
-        method 'GET'
-        url("/foo")
-    }
-    response {
-        status OK()
-        body(events: [[
-                                 operation          : 'EXPORT',
-                                 eventId            : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
-                                 status             : 'OK'
-                         ], [
-                                 operation          : 'INPUT_PROCESSING',
-                                 eventId            : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
-                                 status             : 'OK'
-                         ]
-                ]
-        )
-        bodyMatchers {
-            jsonPath('$.events[0].operation', byRegex('.+'))
-            jsonPath('$.events[0].eventId', byRegex('^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})$'))
-            jsonPath('$.events[0].status', byRegex('.+'))
-        }
-    }
-}
-
-
-
-

The preceding code leads to creating the following test (the code block shows only the assertion section):

-
-
-
-
and:
-	DocumentContext parsedJson = JsonPath.parse(response.body.asString())
-	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
-	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
-	assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
-	assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
-	assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
-and:
-	assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
-	assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$")
-	assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")
-
-
-
-

As you can see, the assertion is malformed. Only the first element of the array got -asserted. In order to fix this, you should apply the assertion to the whole $.events -collection and assert it with the byCommand(…​) method.

-
-
-
-
-

JAX-RS Support

-
-

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs -to define protected WebTarget webTarget and server initialization. The only option for -testing JAX-RS API is to start a web server. Also, a request with a body needs to have a -content type set. Otherwise, the default of application/octet-stream gets used.

-
-
-

In order to use JAX-RS mode, use the following settings:

-
-
-
-
testMode == 'JAXRSCLIENT'
-
-
-
-

The following example shows a generated test API:

-
-
-
-
-
-
-
-
-

Async Support

-
-

If you’re using asynchronous communication on the server side (your controllers are -returning Callable, DeferredResult, and so on), then, inside your contract, you must -provide an async() method in the response section. The following code shows an example:

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status OK()
-        body 'Passed'
-        async()
-    }
-}
-
-
-
-
YAML
-
-
response:
-    async: true
-
-
-
-

You can also use the fixedDelayMilliseconds method / property to add delay to your stubs.

-
-
-
Groovy DSL
-
-
org.springframework.cloud.contract.spec.Contract.make {
-    request {
-        method GET()
-        url '/get'
-    }
-    response {
-        status 200
-        body 'Passed'
-        fixedDelayMilliseconds 1000
-    }
-}
-
-
-
-
YAML
-
-
response:
-    fixedDelayMilliseconds: 1000
-
-
-
-
-

Working with Context Paths

-
-

Spring Cloud Contract supports context paths.

-
-
- - - - - -
- - -The only change needed to fully support context paths is the switch on the -PRODUCER side. Also, the autogenerated tests must use EXPLICIT mode. The consumer -side remains untouched. In order for the generated test to pass, you must use EXPLICIT -mode. -
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'EXPLICIT'
-}
-
-
-
-

That way, you generate a test that DOES NOT use MockMvc. It means that you generate -real requests and you need to setup your generated test’s base class to work on a real -socket.

-
-
-

Consider the following contract:

-
-
-
-
-
-
-
-

The following example shows how to set up a base class and Rest Assured:

-
-
-
-
-
-
-
-

If you do it this way:

-
-
-
    -
  • -

    All of your requests in the autogenerated tests are sent to the real endpoint with your -context path included (for example, /my-context-path/url).

    -
  • -
  • -

    Your contracts reflect that you have a context path. Your generated stubs also have -that information (for example, in the stubs, you have to call /my-context-path/url).

    -
  • -
-
-
-
-

Working with WebFlux

-
-

Spring Cloud Contract offers two ways of working with WebFlux.

-
-
-

WebFlux with WebTestClient

-
-

One of them is via the WebTestClient mode.

-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>WEBTESTCLIENT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'WEBTESTCLIENT'
-}
-
-
-
-

The following example shows how to set up a WebTestClient base class and RestAssured -for WebFlux:

-
-
-
-
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
-import org.junit.Before;
-
-public abstract class BeerRestBase {
-
-	@Before
-	public void setup() {
-		RestAssuredWebTestClient.standaloneSetup(
-		new ProducerController(personToCheck -> personToCheck.age >= 20));
-	}
-}
-}
-
-
-
-
-

WebFlux with Explicit mode

-
-

Another way is with the EXPLICIT mode in your generated tests -to work with WebFlux.

-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <testMode>EXPLICIT</testMode>
-    </configuration>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-		testMode = 'EXPLICIT'
-}
-
-
-
-

The following example shows how to set up a base class and Rest Assured for Web Flux:

-
-
-
-
    // your tests go here
-
-    // in this config class you define all controllers and mocked services
-
-}
-
-
-
-
-
-

XML Support for REST

-
-

For REST contracts, we also support XML request and response body. -The XML body has to be passed within the body element -as a String or GString. Also body matchers can be provided for -both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath -method should be used, with the desired xPath provided as the first argument -and the appropriate MatchingType as second. All the body matchers apart from byType() are supported.

-
-
-

Here is an example of a Groovy DSL contract with XML response body:

-
-
-
-
-
-
-
-

And below is an example of a YAML contract with XML request and response bodies:

-
-
-
-
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
-
-
-
-

Here is an example of an automatically generated test for XML response body:

-
-
-
-
@Test
-public void validate_xmlMatches() throws Exception {
-	// given:
-	MockMvcRequestSpecification request = given()
-				.header("Content-Type", "application/xml");
-
-	// when:
-	ResponseOptions response = given().spec(request).get("/get");
-
-	// then:
-	assertThat(response.statusCode()).isEqualTo(200);
-	// and:
-	DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
-					.newDocumentBuilder();
-	Document parsedXml = documentBuilder.parse(new InputSource(
-				new StringReader(response.getBody().asString())));
-	// and:
-	assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
-	assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
-	assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
-	assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
-	assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
-	assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
-	assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
-	}
-
-
-
-
-

Messaging Top-Level Elements

-
-

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences:

-
- -
-

Output Triggered by a Method

-
-

The output message can be triggered by calling a method (such as a Scheduler when a was -started and a message was sent), as shown in the following example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

In the previous example case, the output message is sent to output if a method called -bookReturnedTriggered is executed. On the message publisher’s side, we generate a -test that calls that method to trigger the message. On the consumer side, you can use -the some_label to trigger the message.

-
-
-
-

Output Triggered by a Message

-
-

The output message can be triggered by receiving a message, as shown in the following -example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

In the preceding example, the output message is sent to output if a proper message is -received on the input destination. On the message publisher’s side, the engine -generates a test that sends the input message to the defined destination. On the -consumer side, you can either send a message to the input destination or use a label -(some_label in the example) to trigger the message.

-
-
-
-

Consumer/Producer

-
- - - - - -
- - -This section is valid only for Groovy DSL. -
-
-
-

In HTTP, you have a notion of client/stub and `server/test notation. You can also -use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also -provides the consumer and producer methods, as presented in the following example -(note that you can use either $ or value methods to provide consumer and producer -parts):

-
-
-
-
-
-
-
-
-

Common

-
-

In the input or outputMessage section you can call assertThat with the name -of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the -base class or in a static import. Spring Cloud Contract will execute that method -in the generated test.

-
-
-
-
-

Multiple Contracts in One File

-
-

You can define multiple contracts in one file. Such a contract might resemble the -following example:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

In the preceding example, one contract has the name field and the other does not. This -leads to generation of two tests that look more or less like this:

-
-
-
-
package org.springframework.cloud.contract.verifier.tests.com.hello;
-
-import com.example.TestBase;
-import com.jayway.jsonpath.DocumentContext;
-import com.jayway.jsonpath.JsonPath;
-import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
-import com.jayway.restassured.response.ResponseOptions;
-import org.junit.Test;
-
-import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
-import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class V1Test extends TestBase {
-
-	@Test
-	public void validate_should_post_a_user() throws Exception {
-		// given:
-			MockMvcRequestSpecification request = given();
-
-		// when:
-			ResponseOptions response = given().spec(request)
-					.post("/users/1");
-
-		// then:
-			assertThat(response.statusCode()).isEqualTo(200);
-	}
-
-	@Test
-	public void validate_withList_1() throws Exception {
-		// given:
-			MockMvcRequestSpecification request = given();
-
-		// when:
-			ResponseOptions response = given().spec(request)
-					.post("/users/2");
-
-		// then:
-			assertThat(response.statusCode()).isEqualTo(200);
-	}
-
-}
-
-
-
-

Notice that, for the contract that has the name field, the generated test method is named -validate_should_post_a_user. For the one that does not have the name, it is called -validate_withList_1. It corresponds to the name of the file WithList.groovy and the -index of the contract in the list.

-
-
-

The generated stubs is shown in the following example:

-
-
-
-
should post a user.json
-1_WithList.json
-
-
-
-

As you can see, the first file got the name parameter from the contract. The second -got the name of the contract file (WithList.groovy) prefixed with the index (in this -case, the contract had an index of 1 in the list of contracts in the file).

-
-
- - - - - -
- - -As you can see, it is much better if you name your contracts because doing so makes -your tests far more meaningful. -
-
-
-
-

Generating Spring REST Docs snippets from the contracts

-
-

When you want to include the requests and responses of your API using Spring REST Docs, -you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. -Simply include the following dependencies if you haven’t already.

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-

Next you need to make some changes to your base class like the following example.

-
-
-
-
-
-
-
-

In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:

-
-
-
-
-
-
-
- - - - - -
- - -You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs. -
-
-
-
-
-
-

Customization

-
-
- - - - - -
- - -This section is valid only for Groovy DSL -
-
-
-

You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in -the remainder of this section.

-
-
-

Extending the DSL

-
-

You can provide your own functions to the DSL. The key requirement for this feature is to -maintain the static compatibility. Later in this document, you can see examples of:

-
-
-
    -
  • -

    Creating a JAR with reusable classes.

    -
  • -
  • -

    Referencing of these classes in the DSLs.

    -
  • -
-
-
-

You can find the full example -here.

-
-
-

Common JAR

-
-

The following examples show three classes that can be reused in the DSLs.

-
-
-

PatternUtils contains functions used by both the consumer and the producer.

-
-
-
-
-
-
-
-

ConsumerUtils contains functions used by the consumer.

-
-
-
-
-
-
-
-

ProducerUtils contains functions used by the producer.

-
-
-
-
-
-
-
-
-

Adding the Dependency to the Project

-
-

In order for the plugins and IDE to be able to reference the common JAR classes, you need -to pass the dependency to your project.

-
-
-
-

Test the Dependency in the Project’s Dependencies

-
-

First, add the common jar dependency as a test dependency. Because your contracts files -are available on the test resources path, the common jar classes automatically become -visible in your Groovy files. The following examples show how to test the dependency:

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-

Test a Dependency in the Plugin’s Dependencies

-
-

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the -following example:

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-

Referencing classes in DSLs

-
-

You can now reference your classes in your DSL, as shown in the following example:

-
-
-
-
-
-
-
- - - - - -
- - -You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones. -
-
-
-
-
-
-
-

Using the Pluggable Architecture

-
-
-

You may encounter cases where you have your contracts have been defined in other formats, -such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic -generation of tests and stubs. You can add your own implementation for generating both -tests and stubs. Also, you can customize the way tests are generated (for example, you -can generate tests for other languages) and the way stubs are generated (for example, you -can generate stubs for other HTTP server implementations).

-
-
-

Custom Contract Converter

-
-

The ContractConverter interface lets you register your own implementation of a contract -structure converter. The following code listing shows the ContractConverter interface:

-
-
-
-
-
-
-
-

Your implementation must define the condition on which it should start the -conversion. Also, you must define how to perform that conversion in both directions.

-
-
- - - - - -
- - -Once you create your implementation, you must create a -/META-INF/spring.factories file in which you provide the fully qualified name of your -implementation. -
-
-
-

The following example shows a typical spring.factories file:

-
-
-
-
org.springframework.cloud.contract.spec.ContractConverter=\
-org.springframework.cloud.contract.verifier.converter.YamlContractConverter
-
-
-
-

Pact Converter

-
-

Spring Cloud Contract includes support for Pact representation of -contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we -present how to add Pact support for your project. Note however that not all functionality is supported. -Starting with v3 you can combine multiple matcher for the same element; -you can use matchers for the body, headers, request and path; and you can use value generators. -Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic. -Next to that the request and path matchers are skipped during the conversion. -When using a date, time or datetime value generator with a given format, -the given format will be skipped and the ISO format will be used.

-
-
-

In order to properly support the Spring Cloud Contract way of doing messaging -with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

-
-
-
    -
  • -

    to define the destination to which a message gets sent, you have to -set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    -
  • -
-
-
-
-

Pact Contract

-
-

Consider following example of a Pact contract, which is a file under the -src/test/resources/contracts folder.

-
-
-
-
-
-
-
-

The remainder of this section about using Pact refers to the preceding file.

-
-
-
-

Pact for Producers

-
-

On the producer side, you must add two additional dependencies to your plugin -configuration. One is the Spring Cloud Contract Pact support, and the other represents -the current Pact version that you use.

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-

When you execute the build of your application, a test will be generated. The generated -test might be as follows:

-
-
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-	// given:
-		MockMvcRequestSpecification request = given()
-				.header("Content-Type", "application/vnd.fraud.v1+json")
-				.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
-
-	// when:
-		ResponseOptions response = given().spec(request)
-				.put("/fraudcheck");
-
-	// then:
-		assertThat(response.statusCode()).isEqualTo(200);
-		assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
-	// and:
-		DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-		assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
-	// and:
-		assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
-}
-
-
-
-

The corresponding generated stub might be as follows:

-
-
-
-
{
-  "id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
-  "request" : {
-    "url" : "/fraudcheck",
-    "method" : "PUT",
-    "headers" : {
-      "Content-Type" : {
-        "matches" : "application/vnd\\.fraud\\.v1\\+json.*"
-      }
-    },
-    "bodyPatterns" : [ {
-      "matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
-    }, {
-      "matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
-    } ]
-  },
-  "response" : {
-    "status" : 200,
-    "body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
-    "headers" : {
-      "Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
-    },
-    "transformers" : [ "response-template" ]
-  },
-}
-
-
-
-
-

Pact for Consumers

-
-

On the producer side, you must add two additional dependencies to your project -dependencies. One is the Spring Cloud Contract Pact support, and the other represents the -current Pact version that you use.

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-
-

Using the Custom Test Generator

-
-

If you want to generate tests for languages other than Java or you are not happy with the -way the verifier builds Java tests, you can register your own implementation.

-
-
-

The SingleTestGenerator interface lets you register your own implementation. The -following code listing shows the SingleTestGenerator interface:

-
-
-
-
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

-
-
-
-
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
-com.example.MyGenerator
-
-
-
-
-

Using the Custom Stub Generator

-
-

If you want to generate stubs for stub servers other than WireMock, you can plug in your -own implementation of the StubGenerator interface. The following code listing shows the -StubGenerator interface:

-
-
-
-
-
-
-
-

Again, you must provide a spring.factories file, such as the one shown in the following -example:

-
-
-
-
-
-
-
-

The default implementation is the WireMock stub generation.

-
-
- - - - - -
- - -You can provide multiple stub generator implementations. For example, from a single -DSL, you can produce both WireMock stubs and Pact files. -
-
-
-
-

Using the Custom Stub Runner

-
-

If you decide to use a custom stub generation, you also need a custom way of running -stubs with your different stub provider.

-
-
-

Assume that you use Moco to build your stubs and that -you have written a stub generator and placed your stubs in a JAR file.

-
-
-

In order for Stub Runner to know how to run your stubs, you have to define a custom -HTTP Stub server implementation, which might resemble the following example:

-
-
-
-
-
-
-
-

Then, you can register it in your spring.factories file, as shown in the following -example:

-
-
-
-
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
-org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
-
-
-
-

Now you can run stubs with Moco.

-
-
- - - - - -
- - -If you do not provide any implementation, then the default (WireMock) -implementation is used. If you provide more than one, the first one on the list is used. -
-
-
-
-

Using the Custom Stub Downloader

-
-

You can customize the way your stubs are downloaded by creating an implementation of the -StubDownloaderBuilder interface, as shown in the following example:

-
-
-
-
package com.example;
-
-class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
-
-	@Override
-	public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
-		return new StubDownloader() {
-			@Override
-			public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
-					StubConfiguration config) {
-				File unpackedStubs = retrieveStubs();
-				return new AbstractMap.SimpleEntry<>(
-						new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
-								config.getClassifier()), unpackedStubs);
-			}
-
-			File retrieveStubs() {
-			    // here goes your custom logic to provide a folder where all the stubs reside
-			}
-}
-
-
-
-

Then you can register it in your spring.factories file, as shown in the following -example:

-
-
-
-
# Example of a custom Stub Downloader Provider
-org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
-com.example.CustomStubDownloaderBuilder
-
-
-
-

Now you can pick a folder with the source of your stubs.

-
-
- - - - - -
- - -If you do not provide any implementation, then the default is used (scan classpath). -If you provide the stubsMode = StubRunnerProperties.StubsMode.LOCAL or -, stubsMode = StubRunnerProperties.StubsMode.REMOTE then the Aether implementation will be used -If you provide more than one, then the first one on the list is used. -
-
-
-
-

Using the SCM Stub Downloader

-
-

Whenever the repositoryRoot starts with a SCM protocol -(currently we support only git://), the stub downloader will try -to clone the repository and use it as a source of contracts -to generate tests or stubs.

-
-
-

Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader’s behaviour. Below you can find the list of -properties

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

-

* stubrunner.properties.git.branch (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

-

* stubrunner.properties.git.username (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

Git clone username

* git.password (plugin prop)

-

* stubrunner.properties.git.password (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

Git clone password

* git.no-of-attempts (plugin prop)

-

* stubrunner.properties.git.no-of-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

* git.wait-between-attempts (Plugin prop)

-

* stubrunner.properties.git.wait-between-attempts (system prop)

-

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

Number of millis to wait between attempts to push the commits to origin

-
-
-

Using the Pact Stub Downloader

-
-

Whenever the repositoryRoot starts with a Pact protocol -(starts with pact://), the stub downloader will try -to fetch the Pact contract definitions from the Pact Broker. -Whatever is set after pact:// will be parsed as the Pact Broker URL.

-
-
-

Either via environment variables, system properties, properties set -inside the plugin or contracts repository configuration you can -tweak the downloader’s behaviour. Below you can find the list of -properties

-
- - ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

-

* stubrunner.properties.pactbroker.host (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

-

* stubrunner.properties.pactbroker.port (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

-

* stubrunner.properties.pactbroker.protocol (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

-

* stubrunner.properties.pactbroker.tags (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

-

* stubrunner.properties.pactbroker.auth.scheme (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

-

* stubrunner.properties.pactbroker.auth.username (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

The username passed to contractsRepositoryUsername (maven) or contractRepository.username (gradle)

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

-

* stubrunner.properties.pactbroker.auth.password (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

The password passed to contractsRepositoryPassword (maven) or contractRepository.password (gradle)

Password used to connect to the Pact Broker

* pactbroker.provider-name-with-group-id (plugin prop)

-

* stubrunner.properties.pactbroker.provider-name-with-group-id (system prop)

-

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

When true, the provider name will be a combination of groupId:artifactId. If false, just artifactId is used

-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_faq.html b/reference/html/verifier_faq.html index 0f508134b9..9990b6e5bb 100644 --- a/reference/html/verifier_faq.html +++ b/reference/html/verifier_faq.html @@ -1,1540 +1,12 @@ - - - + + - - - -Spring Cloud Contract FAQ - - + - - - - - - -
-
-

Spring Cloud Contract FAQ

-
-
-

Why use Spring Cloud Contract Verifier and not X ?

-
-

For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you’re already creating -software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make -Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

-
-
-
    -
  • -

    Possibility to do CDC with messaging

    -
  • -
  • -

    Clear and easy to use, statically typed DSL

    -
  • -
  • -

    Possibility to copy paste your current JSON file to the contract and only edit its elements

    -
  • -
  • -

    Automatic generation of tests from the defined Contract

    -
  • -
  • -

    Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory

    -
  • -
  • -

    Spring Cloud integration - no discovery service is needed for integration tests

    -
  • -
  • -

    Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality

    -
  • -
  • -

    Via Docker adds support for any language & framework used

    -
  • -
-
-
-
-

I don’t want to write a contract in Groovy!

-
-

No problem. You can write a contract in YAML!

-
-
-
-

What is this value(consumer(), producer()) ?

-
-

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. -What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. -Imagine the following JSON request

-
-
-
-
{
-    "time" : "2016-10-10 20:10:15",
-    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
-    "body" : "foo"
-}
-
-
-
-

and JSON response

-
-
-
-
{
-    "time" : "2016-10-10 21:10:15",
-    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
-    "body" : "bar"
-}
-
-
-
-

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the -database) by changing the clock in the system or providing stub implementations of data providers. The same is related -to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

-
-
-

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system -will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned -JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words -you would like the stub to work like this:

-
-
-
-
{
-    "time" : "SOMETHING THAT MATCHES TIME",
-    "id" : "SOMETHING THAT MATCHES UUID",
-    "body" : "foo"
-}
-
-
-
-

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

-
-
-
-
{
-    "time" : "2016-10-10 21:10:15",
-    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
-    "body" : "bar"
-}
-
-
-
-

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks -much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. -So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the -producer’s backend can work on. Such a JSON would be a valid one:

-
-
-
-
{
-    "time" : "2016-10-10 20:10:15",
-    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
-    "body" : "foo"
-}
-
-
-
-

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to -contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d -have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side -what you might want is the following response:

-
-
-
-
{
-    "time" : "SOMETHING THAT MATCHES TIME",
-    "id" : "SOMETHING THAT MATCHES UUID",
-    "body" : "bar"
-}
-
-
-
-

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? -In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both -sides of the communication. You can pass the values:

-
-
-

Either via the value method

-
-
-
-
value(consumer(...), producer(...))
-value(stub(...), test(...))
-value(client(...), server(...))
-
-
-
-

or using the $() method

-
-
-
-
$(consumer(...), producer(...))
-$(stub(...), test(...))
-$(client(...), server(...))
-
-
-
-

You can read more about this in the [contract-dsl] section.

-
-
-

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. -Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). -Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

-
-
- - - - - -
- - -If on one side you have passed the regular expression and you haven’t passed the other, then the -other side will get auto-generated. -
-
-
-

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

-
-
-

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression -for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

-
-
-
-
org.springframework.cloud.contract.spec.Contract.make {
-				request {
-					method 'GET'
-					url '/someUrl'
-					body([
-					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
-					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
-					    body: "foo"
-					])
-				}
-			response {
-				status OK()
-				body([
-					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
-					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
-					    body: "bar"
-					])
-			}
-}
-
-
-
- - - - - -
- - -Please read the Groovy docs related to JSON to understand how to -properly structure the request / response bodies. -
-
-
-
-

How to do Stubs versioning?

-
-

API Versioning

-
-

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are -different approaches.

-
-
-
    -
  • -

    use Hypermedia, links and do not version your API by any means

    -
  • -
  • -

    pass versions through headers / urls

    -
  • -
-
-
-

I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate -business value should be picked.

-
-
-

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. -You can create a subfolder for every version or append it to the contract name - whatever suits you more.

-
-
-
-

JAR versioning

-
-

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

-
-
-

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of -the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version -looks like this (it got built on the 20.10.2016 at 20:15:21) :

-
-
-
-
1.0.0.20161020-201521-RELEASE
-
-
-
-

In that case your generated stub jar will look like this.

-
-
-
-
1.0.0.20161020-201521-RELEASE-stubs.jar
-
-
-
-

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the - latest version of the stubs. You can do that by passing the + sign. Example

-
-
-
-
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
-
-
-
-

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar -version. Example for 2.1.1.

-
-
-
-
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
-
-
-
-
-

Dev or prod stubs

-
-

You can manipulate the classifier to run the tests against current development version of the stubs of other services - or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier - once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

-
-
-

Example of tests using development version of stubs

-
-
-
-
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
-
-
-
-

Example of tests using production version of stubs

-
-
-
-
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
-
-
-
-

You can pass those values also via properties from your deployment pipeline.

-
-
-
-
-

Common repo with contracts

-
-

Another way of storing contracts other than having them with the producer is keeping them in a common place. -It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep -contracts in a single place then you, as a producer, will know how many consumers you have and which -consumer you will break with your local changes.

-
-
-

Repo structure

-
-

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, -client2, client3. Then in the repository with common contracts you would have the following setup -(which you can checkout here):

-
-
-
-
├── com
-│   └── example
-│       └── server
-│           ├── client1
-│           │   └── expectation.groovy
-│           ├── client2
-│           │   └── expectation.groovy
-│           ├── client3
-│           │   └── expectation.groovy
-│           └── pom.xml
-├── mvnw
-├── mvnw.cmd
-├── pom.xml
-└── src
-    └── assembly
-        └── contracts.xml
-
-
-
-

As you can see under the slash-delimited groupid / artifact id folder (com/example/server) you have -expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL -contract files as described throughout this documentation. This repository has to produce a JAR file that maps -one to one to the contents of the repo.

-
-
-

Example of a pom.xml inside the server folder.

-
-
-
-
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-		 xmlns="http://maven.apache.org/POM/4.0.0"
-		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
-	<modelVersion>4.0.0</modelVersion>
+Page Redirection
 
-	<groupId>com.example</groupId>
-	<artifactId>server</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-
-	<name>Server Stubs</name>
-	<description>POM used to install locally stubs for consumer side</description>
-
-	<parent>
-		<groupId>org.springframework.boot</groupId>
-		<artifactId>spring-boot-starter-parent</artifactId>
-		<version>2.2.0.BUILD-SNAPSHOT</version>
-		<relativePath/>
-	</parent>
-
-	<properties>
-		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-		<java.version>1.8</java.version>
-		<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
-		<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
-		<excludeBuildFolders>true</excludeBuildFolders>
-	</properties>
-
-	<dependencyManagement>
-		<dependencies>
-			<dependency>
-				<groupId>org.springframework.cloud</groupId>
-				<artifactId>spring-cloud-dependencies</artifactId>
-				<version>${spring-cloud-release.version}</version>
-				<type>pom</type>
-				<scope>import</scope>
-			</dependency>
-		</dependencies>
-	</dependencyManagement>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.springframework.cloud</groupId>
-				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-				<version>${spring-cloud-contract.version}</version>
-				<extensions>true</extensions>
-				<configuration>
-					<!-- By default it would search under src/test/resources/ -->
-					<contractsDirectory>${project.basedir}</contractsDirectory>
-				</configuration>
-			</plugin>
-		</plugins>
-	</build>
-
-	<repositories>
-		<repository>
-			<id>spring-snapshots</id>
-			<name>Spring Snapshots</name>
-			<url>https://repo.spring.io/snapshot</url>
-			<snapshots>
-				<enabled>true</enabled>
-			</snapshots>
-		</repository>
-		<repository>
-			<id>spring-milestones</id>
-			<name>Spring Milestones</name>
-			<url>https://repo.spring.io/milestone</url>
-			<snapshots>
-				<enabled>false</enabled>
-			</snapshots>
-		</repository>
-		<repository>
-			<id>spring-releases</id>
-			<name>Spring Releases</name>
-			<url>https://repo.spring.io/release</url>
-			<snapshots>
-				<enabled>false</enabled>
-			</snapshots>
-		</repository>
-	</repositories>
-	<pluginRepositories>
-		<pluginRepository>
-			<id>spring-snapshots</id>
-			<name>Spring Snapshots</name>
-			<url>https://repo.spring.io/snapshot</url>
-			<snapshots>
-				<enabled>true</enabled>
-			</snapshots>
-		</pluginRepository>
-		<pluginRepository>
-			<id>spring-milestones</id>
-			<name>Spring Milestones</name>
-			<url>https://repo.spring.io/milestone</url>
-			<snapshots>
-				<enabled>false</enabled>
-			</snapshots>
-		</pluginRepository>
-		<pluginRepository>
-			<id>spring-releases</id>
-			<name>Spring Releases</name>
-			<url>https://repo.spring.io/release</url>
-			<snapshots>
-				<enabled>false</enabled>
-			</snapshots>
-		</pluginRepository>
-	</pluginRepositories>
-
-</project>
-
-
-
-

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. -Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install - stubs of the producer project.

-
-
-

The pom.xml in the root folder can look like this:

-
-
-
-
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-		 xmlns="http://maven.apache.org/POM/4.0.0"
-		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
-	<modelVersion>4.0.0</modelVersion>
-
-	<groupId>com.example.standalone</groupId>
-	<artifactId>contracts</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-
-	<name>Contracts</name>
-	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
-		producers to generate tests and stubs
-	</description>
-
-	<properties>
-		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-	</properties>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-assembly-plugin</artifactId>
-				<executions>
-					<execution>
-						<id>contracts</id>
-						<phase>prepare-package</phase>
-						<goals>
-							<goal>single</goal>
-						</goals>
-						<configuration>
-							<attach>true</attach>
-							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
-							<!-- If you want an explicit classifier remove the following line -->
-							<appendAssemblyId>false</appendAssemblyId>
-						</configuration>
-					</execution>
-				</executions>
-			</plugin>
-		</plugins>
-	</build>
-
-</project>
-
-
-
-

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

-
-
-
-
<assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-		  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
-		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
-	<id>project</id>
-	<formats>
-		<format>jar</format>
-	</formats>
-	<includeBaseDirectory>false</includeBaseDirectory>
-	<fileSets>
-		<fileSet>
-			<directory>${project.basedir}</directory>
-			<outputDirectory>/</outputDirectory>
-			<useDefaultExcludes>true</useDefaultExcludes>
-			<excludes>
-				<exclude>**/${project.build.directory}/**</exclude>
-				<exclude>mvnw</exclude>
-				<exclude>mvnw.cmd</exclude>
-				<exclude>.mvn/**</exclude>
-				<exclude>src/**</exclude>
-			</excludes>
-		</fileSet>
-	</fileSets>
-</assembly>
-
-
-
-
-

Workflow

-
-

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference - is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on - common contracts in a common repository.

-
-
-
-

Consumer

-
-

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the -consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) -and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

-
-
- - - - - -
- - -You need to have Maven installed locally -
-
-
-
-

Producer

-
-

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency -of the JAR containing the contracts:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<configuration>
-		<contractsMode>REMOTE</contractsMode>
-		<contractsRepositoryUrl>
-			https://link/to/your/nexus/or/artifactory/or/sth
-		</contractsRepositoryUrl>
-		<contractDependency>
-			<groupId>com.example.standalone</groupId>
-			<artifactId>contracts</artifactId>
-		</contractDependency>
-	</configuration>
-</plugin>
-
-
-
-

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded -from https://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder -and contracts present under the com/example/server will be picked as the ones used to generate the -tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken -when some incompatible changes are done.

-
-
-

The rest of the flow looks the same.

-
-
-
-

How can I define messaging contracts per topic not per producer?

-
-

To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic, -we could create the structure when the rest contracts would be placed in a folder per producer and messaging -contracts in the folder per topic.

-
-
-
For Maven Project
-
-

To make it possible to work on the producer side we should specify an inclusion pattern for -filtering common repository jar by messaging topics we are interested in. includedFiles property of Maven Spring Cloud Contract plugin -allows us to do that. Also contractsPath need to be specified since the default path would be the common repository groupid/artifactid.

-
-
-
-
<plugin>
-   <groupId>org.springframework.cloud</groupId>
-   <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-   <version>${spring-cloud-contract.version}</version>
-   <configuration>
-      <contractsMode>REMOTE</contractsMode>
-      <contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
-      <contractDependency>
-         <groupId>com.example</groupId>
-         <artifactId>common-repo-with-contracts</artifactId>
-         <version>+</version>
-      </contractDependency>
-      <contractsPath>/</contractsPath>
-      <baseClassMappings>
-         <baseClassMapping>
-            <contractPackageRegex>.*messaging.*</contractPackageRegex>
-            <baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
-         </baseClassMapping>
-         <baseClassMapping>
-            <contractPackageRegex>.*rest.*</contractPackageRegex>
-            <baseClassFQN>com.example.services.TestBase</baseClassFQN>
-         </baseClassMapping>
-      </baseClassMappings>
-      <includedFiles>
-         <includedFile>**/${project.artifactId}/**</includedFile>
-         <includedFile>**/${first-topic}/**</includedFile>
-         <includedFile>**/${second-topic}/**</includedFile>
-      </includedFiles>
-   </configuration>
-</plugin>
-
-
-
-
-
For Gradle Project
-
-
    -
  • -

    Add a custom configuration for the common-repo dependency:

    -
  • -
-
-
-
-
ext {
-    conractsGroupId = "com.example"
-    contractsArtifactId = "common-repo"
-    contractsVersion = "1.2.3"
-}
-
-configurations {
-    contracts {
-        transitive = false
-    }
-}
-
-
-
-
    -
  • -

    Add the common-repo dependency to your classpath:

    -
  • -
-
-
-
-
dependencies {
-    contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
-    testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
-}
-
-
-
-
    -
  • -

    Download the dependency to an appropriate folder:

    -
  • -
-
-
-
-
task getContracts(type: Copy) {
-    from configurations.contracts
-    into new File(project.buildDir, "downloadedContracts")
-}
-
-
-
-
    -
  • -

    Unzip JAR:

    -
  • -
-
-
-
-
task unzipContracts(type: Copy) {
-    def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
-    def outputDir = file("${buildDir}/unpackedContracts")
-
-    from zipTree(zipFile)
-    into outputDir
-}
-
-
-
-
    -
  • -

    Cleanup unused contracts:

    -
  • -
-
-
-
-
task deleteUnwantedContracts(type: Delete) {
-    delete fileTree(dir: "${buildDir}/unpackedContracts",
-        include: "**/*",
-        excludes: [
-            "**/${project.name}/**"",
-            "**/${first-topic}/**",
-            "**/${second-topic}/**"])
-}
-
-
-
-
    -
  • -

    Create task dependencies:

    -
  • -
-
-
-
-
unzipContracts.dependsOn("getContracts")
-deleteUnwantedContracts.dependsOn("unzipContracts")
-build.dependsOn("deleteUnwantedContracts")
-
-
-
-
    -
  • -

    Configure plugin by specifying the directory containing contracts using contractsDslDir property

    -
  • -
-
-
-
-
contracts {
-    contractsDslDir = new File("${buildDir}/unpackedContracts")
-}
-
-
-
-
-
-
-

Do I need a Binary Storage? Can’t I use Git?

-
-

In the polyglot world, there are languages that don’t use binary storages like -Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide -mechanisms to store contracts and stubs in a SCM repository. Currently the -only supported SCM is Git.

-
-
-

The repository would have to the following setup -(which you can checkout here):

-
-
-
-
.
-└── META-INF
-    └── com.example
-        └── beer-api-producer-git
-            └── 0.0.1-SNAPSHOT
-                ├── contracts
-                │   └── beer-api-consumer
-                │       ├── messaging
-                │       │   ├── shouldSendAcceptedVerification.groovy
-                │       │   └── shouldSendRejectedVerification.groovy
-                │       └── rest
-                │           ├── shouldGrantABeerIfOldEnough.groovy
-                │           └── shouldRejectABeerIfTooYoung.groovy
-                └── mappings
-                    └── beer-api-consumer
-                        └── rest
-                            ├── shouldGrantABeerIfOldEnough.json
-                            └── shouldRejectABeerIfTooYoung.json
-
-
-
-

Under META-INF folder:

-
-
-
    -
  • -

    we group applications via groupId (e.g. com.example)

    -
  • -
  • -

    then each application is represented via the artifactId (e.g. beer-api-producer-git)

    -
  • -
  • -

    next, the version of the application (e.g. 0.0.1-SNAPSHOT). Starting from Spring Cloud Contract version 2.1.0, you can specify the versions as follows (assuming that your versions follow the semantic versioning)

    -
    -
      -
    • -

      + or latest - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:

      -
      -
        -
      • -

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.BUILD-SNAPSHOT

        -
      • -
      • -

        if you have a version 1.0.0.RELEASE and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        -
      • -
      • -

        if you have a version called latest or + we will pick that folder

        -
      • -
      -
      -
    • -
    • -

      release - to find the latest release version of your stubs. That means:

      -
      -
        -
      • -

        if you have a version 1.0.0.RELEASE, 2.0.0.BUILD-SNAPSHOT and 2.0.0.RELEASE we will assume that the latest is 2.0.0.RELEASE

        -
      • -
      • -

        if you have a version called release we will pick that folder

        -
      • -
      -
      -
    • -
    -
    -
  • -
  • -

    finally, there are two folders:

    -
    -
      -
    • -

      contracts - the good practice is to store the contracts required by each -consumer in the folder with the consumer name (e.g. beer-api-consumer). That way you -can use the stubs-per-consumer feature. Further directory structure is arbitrary.

      -
    • -
    • -

      mappings - in this folder the Maven / Gradle Spring Cloud Contract plugins will push -the stub server mappings. On the consumer side, Stub Runner will scan this folder -to start stub servers with stub definitions. The folder structure will be a copy -of the one created in the contracts subfolder.

      -
    • -
    -
    -
  • -
-
-
-

Protocol convention

-
-

In order to control the type and location of the source of contracts (whether it’s -a binary storage or an SCM repository), you can use the protocol in the URL of -the repository. Spring Cloud Contract iterates over registered protocol resolvers -and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).

-
-
-

For the SCM functionality, currently, we support the Git repository. To use it, -in the property, where the repository URL needs to be placed you just have to prefix -the connection URL with git://. Here you can find a couple of examples:

-
-
-
-
git://file:///foo/bar
-git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
-git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
-
-
-
-
-

Producer

-
-

For the producer, to use the SCM approach, we can reuse the -same mechanism we use for external contracts. We route Spring Cloud Contract -to use the SCM implementation via the URL that contains -the git:// protocol.

-
-
- - - - - -
- - -You have to manually add the pushStubsToScm -goal in Maven or execute (bind) the pushStubsToScm task in -Gradle. We don’t push stubs to origin of your git -repository out of the box. -
-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- Base class mappings etc. -->
-
-        <!-- We want to pick contracts from a Git repository -->
-        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
-
-        <!-- We reuse the contract dependency section to set up the path
-        to the folder that contains the contract definitions. In our case the
-        path will be /groupId/artifactId/version/contracts -->
-        <contractDependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>${project.artifactId}</artifactId>
-            <version>${project.version}</version>
-        </contractDependency>
-
-        <!-- The contracts mode can't be classpath -->
-        <contractsMode>REMOTE</contractsMode>
-    </configuration>
-    <executions>
-        <execution>
-            <phase>package</phase>
-            <goals>
-                <!-- By default we will not push the stubs back to SCM,
-                you have to explicitly add it as a goal -->
-                <goal>pushStubsToScm</goal>
-            </goals>
-        </execution>
-    </executions>
-</plugin>
-
-
-
-
Gradle
-
-
contracts {
-	// We want to pick contracts from a Git repository
-	contractDependency {
-		stringNotation = "${project.group}:${project.name}:${project.version}"
-	}
-	/*
-	We reuse the contract dependency section to set up the path
-	to the folder that contains the contract definitions. In our case the
-	path will be /groupId/artifactId/version/contracts
-	 */
-	contractRepository {
-		repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
-	}
-	// The mode can't be classpath
-	contractsMode = "REMOTE"
-	// Base class mappings etc.
-}
-
-/*
-In this scenario we want to publish stubs to SCM whenever
-the `publish` task is executed
-*/
-publish.dependsOn("publishStubsToScm")
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    Git project will be cloned to a temporary directory

    -
  • -
  • -

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/contracts folder -to find contracts. E.g. for com.example:foo:1.0.0 the path would be -META-INF/com.example/foo/1.0.0/contracts

    -
  • -
  • -

    Tests will be generated from the contracts

    -
  • -
  • -

    Stubs will be created from the contracts

    -
  • -
  • -

    Once the tests pass, the stubs will be committed in the cloned repository

    -
  • -
  • -

    Finally, a push will be done to that repo’s origin

    -
  • -
-
-
-
-

Producer with contracts stored locally

-
-

Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    Contracts from the default src/test/resources/contracts directory will be picked

    -
  • -
  • -

    Tests will be generated from the contracts

    -
  • -
  • -

    Stubs will be created from the contracts

    -
  • -
  • -

    Once the tests pass

    -
    -
      -
    • -

      Git project will be cloned to a temporary directory

      -
    • -
    • -

      The stubs and contracts will be committed in the cloned repository

      -
    • -
    -
    -
  • -
  • -

    Finally, a push will be done to that repo’s origin

    -
  • -
-
-
-
Keeping contracts with the producer and stubs in an external repository
-
-

It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo. -This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to -use an artifact repository for storing the stubs.

-
-
-

In order to do that, use the usual producer setup, and then add the pushStubsToScm goal and set -contractsRepositoryUrl to the repository where you want to keep the stubs.

-
-
-
-
-

Consumer

-
-

On the consumer side when passing the repositoryRoot parameter, -either from the @AutoConfigureStubRunner annotation, the -JUnit rule, JUnit 5 extension or properties, it’s enough to pass the URL of the -SCM repository, prefixed with the protocol. For example

-
-
-
-
@AutoConfigureStubRunner(
-    stubsMode="REMOTE",
-    repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
-    ids="com.example:bookstore:0.0.1.RELEASE"
-)
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    Git project will be cloned to a temporary directory

    -
  • -
  • -

    The SCM stub downloader will go to META-INF/groupId/artifactId/version/ folder -to find stub definitions and contracts. E.g. for com.example:foo:1.0.0 the path would be -META-INF/com.example/foo/1.0.0/

    -
  • -
  • -

    Stub servers will be started and fed with mappings

    -
  • -
  • -

    Messaging definitions will be read and used in the messaging tests

    -
  • -
-
-
-
-
-

Can I use the Pact Broker?

-
-

When using Pact you can use the Pact Broker -to store and share Pact definitions. Starting from Spring Cloud Contract -2.0.0 one can fetch Pact files from the Pact Broker to generate -tests and stubs.

-
-
-

As a prerequisite the Pact Converter and Pact Stub Downloader -are required. You have to add them via the spring-cloud-contract-pact dependency. -You can read more about it in the [pact-converter] section.

-
-
- - - - - -
- - -Pact follows the Consumer Contract convention. That means -that the Consumer creates the Pact definitions first, then -shares the files with the Producer. Those expectations are generated -from the Consumer’s code and can break the Producer if the expectations -are not met. -
-
-
-

Pact Consumer

-
-

The consumer uses Pact framework to generate Pact files. The -Pact files are sent to the Pact Broker. An example of such -setup can be found here.

-
-
-
-

Producer

-
-

For the producer, to use the Pact files from the Pact Broker, we can reuse the -same mechanism we use for external contracts. We route Spring Cloud Contract -to use the Pact implementation via the URL that contains -the pact:// protocol. It’s enough to pass the URL to the -Pact Broker. An example of such setup can be found here.

-
-
-
Maven
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- Base class mappings etc. -->
-
-        <!-- We want to pick contracts from a Git repository -->
-        <contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
-
-        <!-- We reuse the contract dependency section to set up the path
-        to the folder that contains the contract definitions. In our case the
-        path will be /groupId/artifactId/version/contracts -->
-        <contractDependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>${project.artifactId}</artifactId>
-            <!-- When + is passed, a latest tag will be applied when fetching pacts -->
-            <version>+</version>
-        </contractDependency>
-
-        <!-- The contracts mode can't be classpath -->
-        <contractsMode>REMOTE</contractsMode>
-    </configuration>
-    <!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-contract-pact</artifactId>
-            <version>${spring-cloud-contract.version}</version>
-        </dependency>
-    </dependencies>
-</plugin>
-
-
-
-
Gradle
-
-
buildscript {
-	repositories {
-		//...
-	}
-
-	dependencies {
-		// ...
-		// Don't forget to add spring-cloud-contract-pact to the classpath!
-		classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
-	}
-}
-
-contracts {
-	// When + is passed, a latest tag will be applied when fetching pacts
-	contractDependency {
-		stringNotation = "${project.group}:${project.name}:+"
-	}
-	contractRepository {
-		repositoryUrl = "pact://http://localhost:8085"
-	}
-	// The mode can't be classpath
-	contractsMode = "REMOTE"
-	// Base class mappings etc.
-}
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    Pact files will be downloaded from the Pact Broker

    -
  • -
  • -

    Spring Cloud Contract will convert the Pact files into tests and stubs

    -
  • -
  • -

    The JAR with the stubs gets automatically created as usual

    -
  • -
-
-
-
-

Pact Consumer (Producer Contract approach)

-
-

In the scenario where you don’t want to do Consumer Contract approach -(for every single consumer define the expectations) but you’d prefer -to do Producer Contracts (the producer provides the contracts and -publishes stubs), it’s enough to use Spring Cloud Contract with -Stub Runner option. An example of such setup can be found here.

-
-
-

First, remember to add Stub Runner and Spring Cloud Contract Pact module -as test dependencies.

-
-
-
Maven
-
-
<dependencyManagement>
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-dependencies</artifactId>
-            <version>${spring-cloud.version}</version>
-            <type>pom</type>
-            <scope>import</scope>
-        </dependency>
-    </dependencies>
-</dependencyManagement>
-
-<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
-<dependencies>
-    <!-- ... -->
-    <dependency>
-        <groupId>org.springframework.cloud</groupId>
-        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
-        <scope>test</scope>
-    </dependency>
-    <dependency>
-        <groupId>org.springframework.cloud</groupId>
-        <artifactId>spring-cloud-contract-pact</artifactId>
-        <scope>test</scope>
-    </dependency>
-</dependencies>
-
-
-
-
Gradle
-
-
dependencyManagement {
-    imports {
-        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
-    }
-}
-
-dependencies {
-    //...
-    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
-    // Don't forget to add spring-cloud-contract-pact to the classpath!
-    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
-}
-
-
-
-

Next, just pass the URL of the Pact Broker to repositoryRoot, prefixed -with pact:// protocol. E.g. pact://http://localhost:8085

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest
-@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
-		ids = "com.example:beer-api-producer-pact",
-		repositoryRoot = "pact://http://localhost:8085")
-public class BeerControllerTest {
-    //Inject the port of the running stub
-    @StubRunnerPort("beer-api-producer-pact") int producerPort;
-    //...
-}
-
-
-
-

With such a setup:

-
-
-
    -
  • -

    Pact files will be downloaded from the Pact Broker

    -
  • -
  • -

    Spring Cloud Contract will convert the Pact files into stub definitions

    -
  • -
  • -

    The stub servers will be started and fed with stubs

    -
  • -
-
-
-

For more information about Pact support you can go to -the [pact-stub-downloader] section.

-
-
-
-
-

How can I debug the request/response being sent by the generated tests client?

-
-

The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

-
-
-
-
logging.level.org.apache.http.wire=DEBUG
-
-
-
-

How can I debug the mapping/request/response being sent by WireMock?

-
-

Starting from version 1.2.0 we turn on WireMock logging to -info and the WireMock notifier to being verbose. Now you will -exactly know what request was received by WireMock server and which -matching response definition was picked.

-
-
-

To turn off this feature just bump WireMock logging to ERROR

-
-
-
-
logging.level.com.github.tomakehurst.wiremock=ERROR
-
-
-
-
-

How can I see what got registered in the HTTP server stub?

-
-

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or -`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server -was started will be attached.

-
-
-
-

Can I reference text from file?

-
-

Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the -DSL and provide a path relative to where the contract lays. -If you’re using YAML just use the bodyFromFile property.

-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_introduction.html b/reference/html/verifier_introduction.html index 523f98c284..9990b6e5bb 100644 --- a/reference/html/verifier_introduction.html +++ b/reference/html/verifier_introduction.html @@ -1,1607 +1,12 @@ - - - + + - - - -Spring Cloud Contract Verifier Introduction - - + - - - - - - -
-
-

Spring Cloud Contract Verifier Introduction

-
-
-

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of -JVM-based applications. It moves TDD to the level of software architecture.

-
-
-

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract -definitions are used to produce the following resources:

-
-
-
    -
  • -

    JSON stub definitions to be used by WireMock when doing integration testing on the -client code (client tests). Test code must still be written by hand, and test data is -produced by Spring Cloud Contract Verifier.

    -
  • -
  • -

    Messaging routes, if you’re using a messaging service. We integrate with Spring -Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your -own integrations.

    -
  • -
  • -

    Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation -of the API is compliant with the contract (server tests). A full test is generated by -Spring Cloud Contract Verifier.

    -
  • -
-
-
-

History

-
-

Before becoming Spring Cloud Contract, this project was called Accurest. -It was created by Marcin Grzejszczak and Jakub Kubrynski -from (Codearte.

-
-
-

The 0.1.0 release took place on 26 Jan 2015 and it became stable with 1.0.0 release on 29 Feb 2016.

-
-
-
-

Why a Contract Verifier?

-
-

Assume that we have a system consisting of multiple microservices:

-
-
-

Testing issues

-
-

If we wanted to test the application in top left corner to determine whether it can -communicate with other services, we could do one of two things:

-
-
-
    -
  • -

    Deploy all microservices and perform end-to-end tests.

    -
  • -
  • -

    Mock other microservices in unit/integration tests.

    -
  • -
-
-
-

Both have their advantages but also a lot of disadvantages.

-
-
-

Deploy all microservices and perform end to end tests

-
-
-

Advantages:

-
-
-
    -
  • -

    Simulates production.

    -
  • -
  • -

    Tests real communication between services.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

    To test one microservice, we have to deploy 6 microservices, a couple of databases, -etc.

    -
  • -
  • -

    The environment where the tests run is locked for a single suite of tests (nobody else -would be able to run the tests in the meantime).

    -
  • -
  • -

    They take a long time to run.

    -
  • -
  • -

    The feedback comes very late in the process.

    -
  • -
  • -

    They are extremely hard to debug.

    -
  • -
-
-
-

Mock other microservices in unit/integration tests

-
-
-

Advantages:

-
-
-
    -
  • -

    They provide very fast feedback.

    -
  • -
  • -

    They have no infrastructure requirements.

    -
  • -
-
-
-

Disadvantages:

-
-
-
    -
  • -

    The implementor of the service creates stubs that might have nothing to do with -reality.

    -
  • -
  • -

    You can go to production with passing tests and failing production.

    -
  • -
-
-
-

To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was -created. The main idea is to give you very fast feedback, without the need to set up the -whole world of microservices. If you work on stubs, then the only applications you need -are those that your application directly uses.

-
-
-

Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were -created by the service that you’re calling. Also, if you can use them, it means that they -were tested against the producer’s side. In short, you can trust those stubs.

-
-
-
-
-

Purposes

-
-

The main purposes of Spring Cloud Contract Verifier with Stub Runner are:

-
-
-
    -
  • -

    To ensure that WireMock/Messaging stubs (used when developing the client) do exactly -what the actual server-side implementation does.

    -
  • -
  • -

    To promote ATDD method and Microservices architectural style.

    -
  • -
  • -

    To provide a way to publish changes in contracts that are immediately visible on both -sides.

    -
  • -
  • -

    To generate boilerplate test code to be used on the server side.

    -
  • -
-
-
- - - - - -
- - -Spring Cloud Contract Verifier’s purpose is NOT to start writing business -features in the contracts. Assume that we have a business use case of fraud check. If a -user can be a fraud for 100 different reasons, we would assume that you would create 2 -contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior. -
-
-
-
-

How It Works

-
-

This section explores how Spring Cloud Contract Verifier with Stub Runner works.

-
-
-

A Three-second Tour

-
-

This very brief tour walks through using Spring Cloud Contract:

-
- -
-

You can find a somewhat longer tour -here.

-
-
-
On the Producer Side
-
-

To start working with Spring Cloud Contract, add files with REST/ messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

-
-
-

Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as -shown in the following example:

-
-
-
-
-
-
-
-

The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-</plugin>
-
-
-
-

Running ./mvnw clean install automatically generates tests that verify the application -compliance with the added contracts. By default, the tests get generated under -org.springframework.cloud.contract.verifier.tests..

-
-
-

As the implementation of the functionalities described by the contracts is not yet -present, the tests fail.

-
-
-

To make them pass, you must add the correct implementation of either handling HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests, and it -should contain all the setup necessary to run them (for example RestAssuredMockMvc -controller setup or messaging test setup).

-
-
-

Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -The changes can now be merged, and both the application and the stub artifacts may be -published in an online repository.

-
-
-
-
On the Consumer Side
-
-

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service.

-
-
-

To do so, add the dependency to Spring Cloud Contract Stub Runner, as shown in the -following example:

-
-
-
-
-
-
-
-

You can get the Producer-side stubs installed in your Maven repository in either of two -ways:

-
-
-
    -
  • -

    By checking out the Producer side repository and adding contracts and generating the stubs -by running the following commands:

    -
    -
    -
    $ cd local-http-server-repo
    -$ ./mvnw clean install -DskipTests
    -
    -
    -
    - - - - - -
    - - -The tests are being skipped because the Producer-side contract implementation is not -in place yet, so the automatically-generated contract tests fail. -
    -
    -
  • -
  • -

    By getting already-existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URL as Spring Cloud Contract -Stub Runner properties, as shown in the following example:

    -
    -
    -
    -
    -
    -
  • -
-
-
-

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, -provide the group-id and artifact-id values for Spring Cloud Contract Stub Runner to -run the collaborators' stubs for you, as shown in the following example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment=WebEnvironment.NONE)
-@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
-		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
-public class LoanApplicationServiceTests {
-
-
-
- - - - - -
- - -Use the REMOTE stubsMode when downloading stubs from an online repository and -LOCAL for offline work. -
-
-
-

Now, in your integration test, you can receive stubbed versions of HTTP responses or -messages that are expected to be emitted by the collaborator service.

-
-
-
-
-

A Three-minute Tour

-
-

This brief tour walks through using Spring Cloud Contract:

-
- -
-

You can find an even more brief tour -here.

-
-
-
On the Producer Side
-
-

To start working with Spring Cloud Contract, add files with REST/ messaging contracts -expressed in either Groovy DSL or YAML to the contracts directory, which is set by the -contractsDslDir property. By default, it is $rootDir/src/test/resources/contracts.

-
-
-

For the HTTP stubs, a contract defines what kind of response should be returned for a -given request (taking into account the HTTP methods, URLs, headers, status codes, and so -on). The following example shows how an HTTP stub contract in Groovy DSL:

-
-
-
-
package contracts
+Page Redirection
 
-org.springframework.cloud.contract.spec.Contract.make {
-	request {
-		method 'PUT'
-		url '/fraudcheck'
-		body([
-			   "client.id": $(regex('[0-9]{10}')),
-			   loanAmount: 99999
-		])
-		headers {
-			contentType('application/json')
-		}
-	}
-	response {
-		status OK()
-		body([
-			   fraudCheckStatus: "FRAUD",
-			   "rejection.reason": "Amount too high"
-		])
-		headers {
-			contentType('application/json')
-		}
-	}
-}
-
-
-
-

The same contract expressed in YAML would look like the following example:

-
-
-
-
request:
-  method: PUT
-  url: /fraudcheck
-  body:
-    "client.id": 1234567890
-    loanAmount: 99999
-  headers:
-    Content-Type: application/json
-  matchers:
-    body:
-      - path: $.['client.id']
-        type: by_regex
-        value: "[0-9]{10}"
-response:
-  status: 200
-  body:
-    fraudCheckStatus: "FRAUD"
-    "rejection.reason": "Amount too high"
-  headers:
-    Content-Type: application/json;charset=UTF-8
-
-
-
-

In the case of messaging, you can define:

-
-
-
    -
  • -

    The input and the output messages can be defined (taking into account from and where it -was sent, the message body, and the header).

    -
  • -
  • -

    The methods that should be called after the message is received.

    -
  • -
  • -

    The methods that, when called, should trigger a message.

    -
  • -
-
-
-

The following example shows a Camel messaging contract expressed in Groovy DSL:

-
-
-
-
-
-
-
-

The following example shows the same contract expressed in YAML:

-
-
-
-
-
-
-
-

Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file, -as shown in the following example:

-
-
-
-
-
-
-
-

The following listing shows how to add the plugin, which should go in the build/plugins -portion of the file:

-
-
-
-
<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-</plugin>
-
-
-
-

Running ./mvnw clean install automatically generates tests that verify the application -compliance with the added contracts. By default, the generated tests are under -org.springframework.cloud.contract.verifier.tests..

-
-
-

The following example shows a sample auto-generated test for an HTTP contract:

-
-
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-    // given:
-        MockMvcRequestSpecification request = given()
-                .header("Content-Type", "application/vnd.fraud.v1+json")
-                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
-
-    // when:
-        ResponseOptions response = given().spec(request)
-                .put("/fraudcheck");
-
-    // then:
-        assertThat(response.statusCode()).isEqualTo(200);
-        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
-    // and:
-        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
-        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
-}
-
-
-
-

The preceding example uses Spring’s MockMvc to run the tests. This is the default test -mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be -used. (To do so, change the testMode property of the plugin to JAX-RS or EXPLICIT, -respectively.)

-
-
-

Since 2.1.0, it is also possible to use RestAssuredWebTestClient`with Spring’s reactive `WebTestClient -run under the hood. This is particularly recommended while working with Reactive, Web-Flux-based applications. -In order to use WebTestClient set testMode to WEBTESTCLIENT.

-
-
-

Here is an example of a test generated in WEBTESTCLIENT test mode:

-
-
-
-
[source,java,indent=0]
-
-
-
-
-
@Test
-	public void validate_shouldRejectABeerIfTooYoung() throws Exception {
-		// given:
-			WebTestClientRequestSpecification request = given()
-					.header("Content-Type", "application/json")
-					.body("{\"age\":10}");
-
-		// when:
-			WebTestClientResponse response = given().spec(request)
-					.post("/check");
-
-		// then:
-			assertThat(response.statusCode()).isEqualTo(200);
-			assertThat(response.header("Content-Type")).matches("application/json.*");
-		// and:
-			DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-			assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
-	}
-
-
-
-

Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin -testFramework property to either JUNIT5, TESTNG or Spock.

-
-
- - - - - -
- - -You can now also generate WireMock scenarios based on the contracts, by including an -order number followed by an underscore at the beginning of the contract file names. -
-
-
-

The following example shows an auto-generated test in Spock for a messaging stub contract:

-
-
-
-
[source,groovy,indent=0]
-
-
-
-
-
given:
-	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
-		\'\'\'{"bookName":"foo"}\'\'\',
-		['sample': 'header']
-	)
-
-when:
-	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
-
-then:
-	 noExceptionThrown()
-	 bookWasDeleted()
-
-
-
-

As the implementation of the functionalities described by the contracts is not yet -present, the tests fail.

-
-
-

To make them pass, you must add the correct implementation of handling either HTTP -requests or messages. Also, you must add a correct base test class for auto-generated -tests to the project. This class is extended by all the auto-generated tests and should -contain all the setup necessary to run them (for example, RestAssuredMockMvc controller -setup or messaging test setup).

-
-
-

Once the implementation and the test base class are in place, the tests pass, and both the -application and the stub artifacts are built and installed in the local Maven repository. -Information about installing the stubs jar to the local repository appears in the logs, as -shown in the following example:

-
-
-
-
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
-[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
-[INFO]
-[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
-[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
-[INFO]
-[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
-[INFO]
-[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
-[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
-[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
-[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
-
-
-
-

You can now merge the changes and publish both the application and the stub artifacts -in an online repository.

-
-
-

Docker Project

-
-
-

In order to enable working with contracts while creating applications in non-JVM -technologies, the springcloud/spring-cloud-contract Docker image has been created. It -contains a project that automatically generates tests for HTTP contracts and executes them -in EXPLICIT test mode. Then, if the tests pass, it generates Wiremock stubs and, -optionally, publishes them to an artifact manager. In order to use the image, you can -mount the contracts into the /contracts directory and set a few environment variables.

-
-
-
-
On the Consumer Side
-
-

Spring Cloud Contract Stub Runner can be used in the integration tests to get a running -WireMock instance or messaging route that simulates the actual service.

-
-
-

To get started, add the dependency to Spring Cloud Contract Stub Runner:

-
-
-
-
-
-
-
-

You can get the Producer-side stubs installed in your Maven repository in either of two -ways:

-
-
-
    -
  • -

    By checking out the Producer side repository and adding contracts and generating the -stubs by running the following commands:

    -
    -
    -
    $ cd local-http-server-repo
    -$ ./mvnw clean install -DskipTests
    -
    -
    -
    - - - - - -
    - - -The tests are skipped because the Producer-side contract implementation is not yet -in place, so the automatically-generated contract tests fail. -
    -
    -
  • -
  • -

    Getting already existing producer service stubs from a remote repository. To do so, -pass the stub artifact IDs and artifact repository URl as Spring Cloud Contract Stub -Runner properties, as shown in the following example:

    -
    -
    -
    -
    -
    -
  • -
-
-
-

Now you can annotate your test class with @AutoConfigureStubRunner. In the annotation, -provide the group-id and artifact-id for Spring Cloud Contract Stub Runner to run -the collaborators' stubs for you, as shown in the following example:

-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment=WebEnvironment.NONE)
-@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
-		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
-public class LoanApplicationServiceTests {
-
-
-
- - - - - -
- - -Use the REMOTE stubsMode when downloading stubs from an online repository and -LOCAL for offline work. -
-
-
-

In your integration test, you can receive stubbed versions of HTTP responses or messages -that are expected to be emitted by the collaborator service. You can see entries similar -to the following in the build logs:

-
-
-
-
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
-2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
-2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
-2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
-2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
-2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
-2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
-
-
-
-
-
-

Defining the Contract

-
-

As consumers of services, we need to define what exactly we want to achieve. We need to -formulate our expectations. That is why we write contracts.

-
-
-

Assume that you want to send a request containing the ID of a client company and the -amount it wants to borrow from us. You also want to send it to the /fraudcheck url via -the PUT method.

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-
-

Client Side

-
-

Spring Cloud Contract generates stubs, which you can use during client-side testing. -You get a running WireMock instance/Messaging route that simulates the service. -You would like to feed that instance with a proper stub definition.

-
-
-

At some point in time, you need to send a request to the Fraud Detection service.

-
-
-
-
-
-
-
-

Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

-
-
-
-
-
-
-
-

After that, during the tests, Spring Cloud Contract automatically finds the stubs -(simulating the real service) in the Maven repository and exposes them on a configured -(or random) port.

-
-
-
-

Server Side

-
-

Since you are developing your stub, you need to be sure that it actually resembles your -concrete implementation. You cannot have a situation where your stub acts in one way and -your application behaves in a different way, especially in production.

-
-
-

To ensure that your application behaves the way you define in your stub, tests are -generated from the stub you provide.

-
-
-

The autogenerated test looks, more or less, like this:

-
-
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-    // given:
-        MockMvcRequestSpecification request = given()
-                .header("Content-Type", "application/vnd.fraud.v1+json")
-                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
-
-    // when:
-        ResponseOptions response = given().spec(request)
-                .put("/fraudcheck");
-
-    // then:
-        assertThat(response.statusCode()).isEqualTo(200);
-        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
-    // and:
-        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
-        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
-}
-
-
-
-
-
-

Step-by-step Guide to Consumer Driven Contracts (CDC)

-
-

Consider an example of Fraud Detection and the Loan Issuance process. The business -scenario is such that we want to issue loans to people but do not want them to steal from -us. The current implementation of our system grants loans to everybody.

-
-
-

Assume that Loan Issuance is a client to the Fraud Detection server. In the current -sprint, we must develop a new feature: if a client wants to borrow too much money, then -we mark the client as a fraud.

-
-
-

Technical remark - Fraud Detection has an artifact-id of http-server, while Loan -Issuance has an artifact-id of http-client, and both have a group-id of com.example.

-
-
-

Social remark - both client and server development teams need to communicate directly and -discuss changes while going through the process. CDC is all about communication.

-
- -
- - - - - -
- - -In this case, the producer owns the contracts. Physically, all the contract are -in the producer’s repository. -
-
-
-

Technical note

-
-

If using the SNAPSHOT / Milestone / Release Candidate versions please add the -following section to your build:

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-

Consumer side (Loan Issuance)

-
-

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:

-
-
-
    -
  1. -

    Start doing TDD by writing a test for your feature.

    -
  2. -
  3. -

    Write the missing implementation.

    -
  4. -
  5. -

    Clone the Fraud Detection service repository locally.

    -
  6. -
  7. -

    Define the contract locally in the repo of Fraud Detection service.

    -
  8. -
  9. -

    Add the Spring Cloud Contract Verifier plugin.

    -
  10. -
  11. -

    Run the integration tests.

    -
  12. -
  13. -

    File a pull request.

    -
  14. -
  15. -

    Create an initial implementation.

    -
  16. -
  17. -

    Take over the pull request.

    -
  18. -
  19. -

    Write the missing implementation.

    -
  20. -
  21. -

    Deploy your app.

    -
  22. -
  23. -

    Work online.

    -
  24. -
-
-
-

Start doing TDD by writing a test for your feature.

-
-
-
-
-
-
-
-

Assume that you have written a test of your new feature. If a loan application for a big -amount is received, the system should reject that loan application with some description.

-
-
-

Write the missing implementation.

-
-
-

At some point in time, you need to send a request to the Fraud Detection service. Assume -that you need to send the request containing the ID of the client and the amount the -client wants to borrow. You want to send it to the /fraudcheck url via the PUT method.

-
-
-
-
-
-
-
-

For simplicity, the port of the Fraud Detection service is set to 8080, and the -application runs on 8090.

-
-
-

If you start the test at this point, it breaks, because no service currently runs on port -8080.

-
-
-

Clone the Fraud Detection service repository locally.

-
-
-

You can start by playing around with the server side contract. To do so, you must first -clone it.

-
-
-
-
$ git clone https://your-git-server.com/server-side.git local-http-server-repo
-
-
-
-

Define the contract locally in the repo of Fraud Detection service.

-
-
-

As a consumer, you need to define what exactly you want to achieve. You need to formulate -your expectations. To do so, write the following contract:

-
-
- - - - - -
- - -Place the contract under src/test/resources/contracts/fraud folder. The fraud folder -is important because the producer’s test base class name references that folder. -
-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

The YML contract is quite straight-forward. However when you take a look at the Contract -written using a statically typed Groovy DSL - you might wonder what the -value(client(…​), server(…​)) parts are. By using this notation, Spring Cloud -Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case -of an identifier or a timestamp, you need not hardcode a value. You want to allow some -different ranges of values. To enable ranges of values, you can set regular expressions -matching those values for the consumer side. You can provide the body by means of either -a map notation or String with interpolations. -Consult the [contract-dsl] section for more information. We highly recommend using the map notation!

-
-
- - - - - -
- - -You must understand the map notation in order to set up contracts. Please read the -Groovy docs regarding JSON. -
-
-
-

The previously shown contract is an agreement between two sides that:

-
-
-
    -
  • -

    if an HTTP request is sent with all of

    -
    -
      -
    • -

      a PUT method on the /fraudcheck endpoint,

      -
    • -
    • -

      a JSON body with a client.id that matches the regular expression [0-9]{10} and -loanAmount equal to 99999,

      -
    • -
    • -

      and a Content-Type header with a value of application/vnd.fraud.v1+json,

      -
    • -
    -
    -
  • -
  • -

    then an HTTP response is sent to the consumer that

    -
    -
      -
    • -

      has status 200,

      -
    • -
    • -

      contains a JSON body with the fraudCheckStatus field containing a value FRAUD and -the rejectionReason field having value Amount too high,

      -
    • -
    • -

      and a Content-Type header with a value of application/vnd.fraud.v1+json.

      -
    • -
    -
    -
  • -
-
-
-

Once you are ready to check the API in practice in the integration tests, you need to -install the stubs locally.

-
-
-

Add the Spring Cloud Contract Verifier plugin.

-
-
-

We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. -First, add the Spring Cloud Contract BOM.

-
-
-
-
-
-
-
-

Next, add the Spring Cloud Contract Verifier Maven plugin

-
-
-
-
-
-
-
-

Since the plugin was added, you get the Spring Cloud Contract Verifier features which, -from the provided contracts:

-
-
-
    -
  • -

    generate and run tests

    -
  • -
  • -

    produce and install stubs

    -
  • -
-
-
-

You do not want to generate tests since you, as the consumer, want only to play with the -stubs. You need to skip the test generation and execution. When you execute:

-
-
-
-
$ cd local-http-server-repo
-$ ./mvnw clean install -DskipTests
-
-
-
-

In the logs, you see something like this:

-
-
-
-
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
-[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
-[INFO]
-[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
-[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
-[INFO]
-[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
-[INFO]
-[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
-[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
-[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
-[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
-
-
-
-

The following line is extremely important:

-
-
-
-
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
-
-
-
-

It confirms that the stubs of the http-server have been installed in the local -repository.

-
-
-

Run the integration tests.

-
-
-

In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic -stub downloading, you must do the following in your consumer side project (Loan -Application service):

-
-
-

Add the Spring Cloud Contract BOM:

-
-
-
-
-
-
-
-

Add the dependency to Spring Cloud Contract Stub Runner:

-
-
-
-
-
-
-
-

Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the -group-id and artifact-id for the Stub Runner to download the stubs of your -collaborators. (Optional step) Because you’re playing with the collaborators offline, you -can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

-
-
-
-
-
-
-
-

Now, when you run your tests, you see something like this:

-
-
-
-
2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
-2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
-2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
-2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
-2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
-2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
-2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
-
-
-
-

This output means that Stub Runner has found your stubs and started a server for your app -with group id com.example, artifact id http-server with version 0.0.1-SNAPSHOT of -the stubs and with stubs classifier on port 8080.

-
-
-

File a pull request.

-
-
-

What you have done until now is an iterative process. You can play around with the -contract, install it locally, and work on the consumer side until the contract works as -you wish.

-
-
-

Once you are satisfied with the results and the test passes, publish a pull request to -the server side. Currently, the consumer side work is done.

-
-
-
-

Producer side (Fraud Detection server)

-
-

As a developer of the Fraud Detection server (a server to the Loan Issuance service):

-
-
-

Create an initial implementation.

-
-
-

As a reminder, you can see the initial implementation here:

-
-
-
-
}
-
-
-
-

Take over the pull request.

-
-
-
-
$ git checkout -b contract-change-pr master
-$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
-
-
-
-

You must add the dependencies needed by the autogenerated tests:

-
-
-
-
-
-
-
-

In the configuration of the Maven plugin, pass the packageWithBaseClasses property

-
-
-
-
-
-
-
- - - - - -
- - -This example uses "convention based" naming by setting the -packageWithBaseClasses property. Doing so means that the two last packages combine to -make the name of the base test class. In our case, the contracts were placed under -src/test/resources/contracts/fraud. Since you do not have two packages starting from -the contracts folder, pick only one, which should be fraud. Add the Base suffix and -capitalize fraud. That gives you the FraudBase test class name. -
-
-
-

All the generated tests extend that class. Over there, you can set up your Spring Context -or whatever is necessary. In this case, use Rest Assured MVC to -start the server side FraudDetectionController.

-
-
-
-
-
-
-
-

Now, if you run the ./mvnw clean install, you get something like this:

-
-
-
-
Results :
-
-Tests in error:
-  ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
-
-
-
-

This error occurs because you have a new contract from which a test was generated and it -failed since you have not implemented the feature. The auto-generated test would look -like this:

-
-
-
-
@Test
-public void validate_shouldMarkClientAsFraud() throws Exception {
-    // given:
-        MockMvcRequestSpecification request = given()
-                .header("Content-Type", "application/vnd.fraud.v1+json")
-                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
-
-    // when:
-        ResponseOptions response = given().spec(request)
-                .put("/fraudcheck");
-
-    // then:
-        assertThat(response.statusCode()).isEqualTo(200);
-        assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
-    // and:
-        DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
-        assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
-        assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
-}
-
-
-
-

If you used the Groovy DSL, you can see, all the producer() parts of the Contract that were present in the -value(consumer(…​), producer(…​)) blocks got injected into the test. -In case of using YAML, the same applied for the matchers sections of the response.

-
-
-

Note that, on the producer side, you are also doing TDD. The expectations are expressed -in the form of a test. This test sends a request to our own application with the URL, -headers, and body defined in the contract. It also is expecting precisely defined values -in the response. In other words, you have the red part of red, green, and -refactor. It is time to convert the red into the green.

-
-
-

Write the missing implementation.

-
-
-

Because you know the expected input and expected output, you can write the missing -implementation:

-
-
-
-
}
-
-
-
-

When you execute ./mvnw clean install again, the tests pass. Since the Spring Cloud -Contract Verifier plugin adds the tests to the generated-test-sources, you can -actually run those tests from your IDE.

-
-
-

Deploy your app.

-
-
-

Once you finish your work, you can deploy your change. First, merge the branch:

-
-
-
-
$ git checkout master
-$ git merge --no-ff contract-change-pr
-$ git push origin master
-
-
-
-

Your CI might run something like ./mvnw clean deploy, which would publish both the -application and the stub artifacts.

-
-
-
-

Consumer Side (Loan Issuance) Final Step

-
-

As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

-
-
-

Merge branch to master.

-
-
-
-
$ git checkout master
-$ git merge --no-ff contract-change-pr
-
-
-
-

Work online.

-
-
-

Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate -where the repository with your stubs is located. At this moment the stubs of the server -side are automatically downloaded from Nexus/Artifactory. You can set the value of -stubsMode to REMOTE. The following code shows an example of -achieving the same thing by changing the properties.

-
-
-
-
-
-
-
-

That’s it!

-
-
-
-
-

Dependencies

-
-

The best way to add dependencies is to use the proper starter dependency.

-
-
-

For stub-runner, use spring-cloud-starter-stub-runner. When you use a plugin, add -spring-cloud-starter-contract-verifier.

-
-
-
- -
-

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note -that some may be outdated, because the Spring Cloud Contract Verifier project is under -constant development.

-
-
-

Spring Cloud Contract video

-
-

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

-
-
-
- -
-
-
- -
-
-

Samples

-
-

You can find some samples at -samples.

-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_messaging.html b/reference/html/verifier_messaging.html index d022acd558..9990b6e5bb 100644 --- a/reference/html/verifier_messaging.html +++ b/reference/html/verifier_messaging.html @@ -1,401 +1,12 @@ - - - + + - - - -Spring Cloud Contract Verifier Messaging - - + - - - - - - -
-
-

Spring Cloud Contract Verifier Messaging

-
-
-

Spring Cloud Contract Verifier lets you verify applications that use messaging as a -means of communication. All of the integrations shown in this document work with Spring, -but you can also create one of your own and use that.

-
-
-

Integrations

-
-

You can use one of the following four integration configurations:

-
-
-
    -
  • -

    Apache Camel

    -
  • -
  • -

    Spring Integration

    -
  • -
  • -

    Spring Cloud Stream

    -
  • -
  • -

    Spring AMQP

    -
  • -
-
-
-

Since we use Spring Boot, if you have added one of these libraries to the classpath, all -the messaging configuration is automatically set up.

-
-
- - - - - -
- - -Remember to put @AutoConfigureMessageVerifier on the base class of your -generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not -work. -
-
-
- - - - - -
- - -If you want to use Spring Cloud Stream, remember to add a dependency on -org.springframework.cloud:spring-cloud-stream-test-support, as shown here: -
-
-
-
Maven
-
-
<dependency>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-stream-test-support</artifactId>
-    <scope>test</scope>
-</dependency>
-
-
-
-
Gradle
-
-
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
-
-
-
-
-

Manual Integration Testing

-
-

The main interface used by the tests is -org.springframework.cloud.contract.verifier.messaging.MessageVerifier. -It defines how to send and receive messages. You can create your own implementation to -achieve the same goal.

-
-
-

In a test, you can inject a ContractVerifierMessageExchange to send and receive -messages that follow the contract. Then add @AutoConfigureMessageVerifier to your test. -Here’s an example:

-
-
-
-
@RunWith(SpringTestRunner.class)
-@SpringBootTest
-@AutoConfigureMessageVerifier
-public static class MessagingContractTests {
+Page Redirection
 
-  @Autowired
-  private MessageVerifier verifier;
-  ...
-}
-
-
-
- - - - - -
- - -If your tests require stubs as well, then @AutoConfigureStubRunner includes the -messaging configuration, so you only need the one annotation. -
-
-
-
-

Publisher-Side Test Generation

-
-

Having the input or outputMessage sections in your DSL results in creation of tests -on the publisher’s side. By default, JUnit 4 tests are created. However, there is also a -possibility to create JUnit 5, TestNG or Spock tests.

-
-
-

There are 3 main scenarios that we should take into consideration:

-
-
-
    -
  • -

    Scenario 1: There is no input message that produces an output message. The output -message is triggered by a component inside the application (for example, scheduler).

    -
  • -
  • -

    Scenario 2: The input message triggers an output message.

    -
  • -
  • -

    Scenario 3: The input message is consumed and there is no output message.

    -
  • -
-
-
- - - - - -
- - -The destination passed to messageFrom or sentTo can have different -meanings for different messaging implementations. For Stream and Integration it is -first resolved as a destination of a channel. Then, if there is no such destination -it is resolved as a channel name. For Camel, that’s a certain component (for example, -jms). -
-
-
-

Scenario 1: No Input Message

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

The following JUnit test is created:

-
-
-
-
-
-
-
-

And the following Spock test would be created:

-
-
-
-
-
-
-
-
-

Scenario 2: Output Triggered by Input

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

The following JUnit test is created:

-
-
-
-
-
-
-
-

And the following Spock test would be created:

-
-
-
-
-
-
-
-
-

Scenario 3: No Output Message

-
-

For the given contract:

-
-
-
Groovy DSL
-
-
-
-
-
-
YAML
-
-
-
-
-
-

The following JUnit test is created:

-
-
-
-
-
-
-
-

And the following Spock test would be created:

-
-
-
-
-
-
-
-
-
-

Consumer Stub Generation

-
-

Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with -a stub. Then it is parsed on the consumer side and proper stubbed routes are created.

-
-
-

For more information, see [stub-runner-for-messaging] section.

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_setup.html b/reference/html/verifier_setup.html index fe087233ef..9990b6e5bb 100644 --- a/reference/html/verifier_setup.html +++ b/reference/html/verifier_setup.html @@ -1,1764 +1,12 @@ - - - + + - - - -Spring Cloud Contract Verifier Setup - - + - - - - - - -
-
-

Spring Cloud Contract Verifier Setup

-
-
-

You can set up Spring Cloud Contract Verifier in the following ways:

-
- -
-

Gradle Project

-
-

To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the -following sections:

-
- -
-

Prerequisites

-
-

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a -Gradle or a Maven plugin.

-
-
- - - - - -
- - -If you want to use Spock in your projects, you must add separately the -spock-core and spock-spring modules. Check Spock -docs for more information -
-
-
-
-

Add Gradle Plugin with Dependencies

-
-

To add a Gradle plugin with dependencies, use code similar to this:

-
-
-
-
buildscript {
-	repositories {
-		mavenCentral()
-	}
-	dependencies {
-		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
-		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
-	}
-}
+Page Redirection
 
-apply plugin: 'groovy'
-apply plugin: 'spring-cloud-contract'
-
-dependencyManagement {
-	imports {
-		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
-	}
-}
-
-dependencies {
-	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
-	// example with adding Spock core and Spock Spring
-	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
-	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
-	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}
-
-
-
-
-

Gradle and Rest Assured 2.0

-
-

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x -you can add it to the plugins classpath, as shown here:

-
-
-
-
buildscript {
-	repositories {
-		mavenCentral()
-	}
-	dependencies {
-		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
-		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
-		classpath "com.jayway.restassured:rest-assured:2.5.0"
-		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
-	}
-}
-
-depenendencies {
-    // all dependencies
-    // you can exclude rest-assured from spring-cloud-contract-verifier
-    testCompile "com.jayway.restassured:rest-assured:2.5.0"
-    testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
-}
-
-
-
-

That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath -and modifies the imports accordingly.

-
-
-
-

Snapshot Versions for Gradle

-
-

Add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as shown here:

-
-
-
-
}
-
-
-
-
-

Add stubs

-
-

By default, Spring Cloud Contract Verifier is looking for stubs in the -src/test/resources/contracts directory.

-
-
-

The directory containing stub definitions is treated as a class name, and each stub -definition is treated as a single test. Spring Cloud Contract Verifier assumes that it -contains at least one level of directories that are to be used as the test class name. -If more than one level of nested directories is present, all except the last one is used -as the package name. For example, with following structure:

-
-
-
-
src/test/resources/contracts/myservice/shouldCreateUser.groovy
-src/test/resources/contracts/myservice/shouldReturnUser.groovy
-
-
-
-

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods:

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-

Run the Plugin

-
-

The plugin registers itself to be invoked before a check task. If you want it to be -part of your build process, you need to do nothing more. If you just want to generate -tests, invoke the generateContractTests task.

-
-
-
-

Default Setup

-
-

The default Gradle Plugin setup creates the following Gradle part of the build (in -pseudocode):

-
-
-
-
contracts {
-    testFramework ='JUNIT'
-    testMode = 'MockMvc'
-    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
-    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
-    contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
-    basePackageForTests = 'org.springframework.cloud.verifier.tests'
-    stubsOutputDir = project.file("${project.buildDir}/stubs")
-
-    // the following properties are used when you want to provide where the JAR with contract lays
-    contractDependency {
-        stringNotation = ''
-    }
-    contractsPath = ''
-    contractsWorkOffline = false
-    contractRepository {
-        cacheDownloadedContracts(true)
-    }
-}
-
-tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
-    baseName = project.name
-    classifier = contracts.stubsSuffix
-    from contractVerifier.stubsOutputDir
-}
-
-project.artifacts {
-    archives task
-}
-
-tasks.create(type: Copy, name: 'copyContracts') {
-    from contracts.contractsDslDir
-    into contracts.stubsOutputDir
-}
-
-verifierStubsJar.dependsOn 'copyContracts'
-
-publishing {
-    publications {
-        stubs(MavenPublication) {
-            artifactId project.name
-            artifact verifierStubsJar
-        }
-    }
-}
-
-
-
-
-

Configure Plugin

-
-

To change the default configuration, add a contracts snippet to your Gradle config, as -shown here:

-
-
-
-
contracts {
-	testMode = 'MockMvc'
-	baseClassForTests = 'org.mycompany.tests'
-	generatedTestSourcesDir = project.file('src/generatedContract')
-}
-
-
-
-
-

Configuration Options

-
-
    -
  • -

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.

    -
  • -
  • -

    imports: Creates an array with imports that should be included in generated tests -(for example ['org.myorg.Matchers']). By default, it creates an empty array.

    -
  • -
  • -

    staticImports: Creates an array with static imports that should be included in -generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty -array.

    -
  • -
  • -

    basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.

    -
  • -
  • -

    baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.

    -
  • -
  • -

    packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests.

    -
  • -
  • -

    baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This -setting takes precedence over packageWithBaseClasses and baseClassForTests.

    -
  • -
  • -

    ruleClassForTests: Specifies a rule that should be added to the generated test -classes.

    -
  • -
  • -

    ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing -should be skipped. By default, it is an empty array.

    -
  • -
  • -

    contractsDslDir: Specifies the directory containing contracts written using the -GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.

    -
  • -
  • -

    generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.

    -
  • -
  • -

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-resources/contracts.

    -
  • -
  • -

    stubsOutputDir: Specifies the directory where the generated WireMock stubs from -the Groovy DSL should be placed.

    -
  • -
  • -

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT), TestNG and -JUnit 5 are supported with JUnit 4 being the default framework.

    -
  • -
  • -

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    -
  • -
-
-
-

The following properties are used when you want to specify the location of the JAR -containing the contracts:

-
-
-
    -
  • -

    contractDependency: Specifies the Dependency that provides -groupid:artifactid:version:classifier coordinates. You can use the contractDependency -closure to set it up.

    -
  • -
  • -

    contractsPath: Specifies the path to the jar. If contract dependencies are -downloaded, the path defaults to groupid/artifactid where groupid is slash -separated. Otherwise, it scans contracts under the provided directory.

    -
  • -
  • -

    contractsMode: Specifies the mode of downloading contracts (whether the -JAR is available offline, remotely etc.)

    -
  • -
  • -

    deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

    -
  • -
-
-
-

Below you can find a list of experimental features you can turn on via the plugin:

-
-
-
    -
  • -

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    -
  • -
  • -

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    -
  • -
-
-
-
-

Single Base Class for All Tests

-
-

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified.

-
-
-
-
-
-
-
-

If you use Explicit mode, you can use a base class to initialize the whole tested app -as you might see in regular integration tests. If you use the JAXRSCLIENT mode, this -base class should also contain a protected WebTarget webTarget field. Right now, the -only option to test the JAX-RS API is to start a web server.

-
-
-
-

Different Base Classes for Contracts

-
-

If your base classes differ between contracts, you can tell the Spring Cloud Contract -plugin which class should get extended by the autogenerated tests. You have two options:

-
-
-
    -
  • -

    Follow a convention by providing the packageWithBaseClasses

    -
  • -
  • -

    Provide explicit mapping via baseClassMappings

    -
  • -
-
-
-

By Convention

-
-
-

The convention is such that if you have a contract under (for example) -src/test/resources/contract/foo/bar/baz/ and set the value of the -packageWithBaseClasses property to com.example.base, then Spring Cloud Contract -Verifier assumes that there is a BarBazBase class under the com.example.base package. -In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a Base suffix. This rule takes precedence over baseClassForTests. -Here is an example of how it works in the contracts closure:

-
-
-
-
-
-
-
-

By Mapping

-
-
-

You can manually map a regular expression of the contract’s package to fully qualified -name of the base class for the matched contract. You have to provide a list called -baseClassMappings that consists baseClassMapping objects that takes a -contractPackageRegex to baseClassFQN mapping. Consider the following example:

-
-
-
-
-
-
-
-

Let’s assume that you have contracts under - - src/test/resources/contract/com/ - - src/test/resources/contract/foo/

-
-
-

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. -(You could also provide the packageWithBaseClasses as a fallback.) That way, the tests -generated from src/test/resources/contract/com/ contracts extend the -com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

-
-
-
-

Invoking Generated Tests

-
-

To ensure that the provider side is compliant with defined contracts, you need to invoke:

-
-
-
-
./gradlew generateContractTests test
-
-
-
-
-

Pushing stubs to SCM

-
-

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to call the pushStubsToScm -task. Example:

-
-
-
-
$ ./gradlew pushStubsToScm
-
-
-
-

Under [scm-stub-downloader] you can find all possible -configuration options that you can pass either via -the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, -via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, -a system property or an environment variable.

-
-
-
-

Spring Cloud Contract Verifier on the Consumer Side

-
-

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin -in exactly the same way as in case of provider. If you do not want to use Stub Runner -then you need to copy contracts stored in src/test/resources/contracts and generate -WireMock JSON stubs using:

-
-
-
-
./gradlew generateClientStubs
-
-
-
- - - - - -
- - -The stubsOutputDir option has to be set for stub generation to work. -
-
-
-

When present, JSON stubs can be used in automated tests of consuming a service.

-
-
-
-
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
-class LoanApplicationServiceSpec extends Specification {
-
- @ClassRule
- @Shared
- WireMockClassRule wireMockRule == new WireMockClassRule()
-
- @Autowired
- LoanApplicationService sut
-
- def 'should successfully apply for loan'() {
-   given:
- 	LoanApplication application =
-			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
-   when:
-	LoanApplicationResult loanApplication == sut.loanApplication(application)
-   then:
-	loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
-	loanApplication.rejectionReason == null
- }
-}
-
-
-
-

LoanApplication makes a call to FraudDetection service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

-
-
-
-
-

Maven Project

-
-

To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the -following sections:

-
- -
-

Add maven plugin

-
-

Add the Spring Cloud Contract BOM in a fashion similar to this:

-
-
-
-
-
-
-
-

Next, add the Spring Cloud Contract Verifier Maven plugin:

-
-
-
-
-
-
- -
-
-

Maven and Rest Assured 2.0

-
-

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest -Assured 2.x by adding it to the plugins classpath, as shown here:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <packageWithBaseClasses>com.example</packageWithBaseClasses>
-    </configuration>
-    <dependencies>
-        <dependency>
-            <groupId>org.springframework.cloud</groupId>
-            <artifactId>spring-cloud-contract-verifier</artifactId>
-            <version>${spring-cloud-contract.version}</version>
-        </dependency>
-        <dependency>
-           <groupId>com.jayway.restassured</groupId>
-           <artifactId>rest-assured</artifactId>
-           <version>2.5.0</version>
-           <scope>compile</scope>
-        </dependency>
-        <dependency>
-           <groupId>com.jayway.restassured</groupId>
-           <artifactId>spring-mock-mvc</artifactId>
-           <version>2.5.0</version>
-           <scope>compile</scope>
-        </dependency>
-    </dependencies>
-</plugin>
-
-<dependencies>
-    <!-- all dependencies -->
-    <!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
-    <dependency>
-       <groupId>com.jayway.restassured</groupId>
-       <artifactId>rest-assured</artifactId>
-       <version>2.5.0</version>
-       <scope>test</scope>
-    </dependency>
-    <dependency>
-       <groupId>com.jayway.restassured</groupId>
-       <artifactId>spring-mock-mvc</artifactId>
-       <version>2.5.0</version>
-       <scope>test</scope>
-    </dependency>
-</dependencies>
-
-
-
-

That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath -and modifies the imports accordingly.

-
-
-
-

Snapshot versions for Maven

-
-

For Snapshot and Milestone versions, you have to add the following section to your -pom.xml, as shown here:

-
-
-
-
-
-
-
-
-

Add stubs

-
-

By default, Spring Cloud Contract Verifier is looking for stubs in the -src/test/resources/contracts directory. The directory containing stub definitions is -treated as a class name, and each stub definition is treated as a single test. We assume -that it contains at least one directory to be used as test class name. If there is more -than one level of nested directories, all except the last one is used as package name. -For example, with following structure:

-
-
-
-
src/test/resources/contracts/myservice/shouldCreateUser.groovy
-src/test/resources/contracts/myservice/shouldReturnUser.groovy
-
-
-
-

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods

-
-
-
    -
  • -

    shouldCreateUser()

    -
  • -
  • -

    shouldReturnUser()

    -
  • -
-
-
-
-

Run plugin

-
-

The plugin goal generateTests is assigned to be invoked in the phase called -generate-test-sources. If you want it to be part of your build process, you need not do -anything. If you just want to generate tests, invoke the generateTests goal.

-
-
-
-

Configure plugin

-
-

To change the default configuration, just add a configuration section to the plugin -definition or the execution definition, as shown here:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <executions>
-        <execution>
-            <goals>
-                <goal>convert</goal>
-                <goal>generateStubs</goal>
-                <goal>generateTests</goal>
-            </goals>
-        </execution>
-    </executions>
-    <configuration>
-        <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
-        <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
-    </configuration>
-</plugin>
-
-
-
-
-

Configuration Options

-
-
    -
  • -

    testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.

    -
  • -
  • -

    basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.

    -
  • -
  • -

    ruleClassForTests: Specifies a rule that should be added to the generated test -classes.

    -
  • -
  • -

    baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.

    -
  • -
  • -

    contractsDirectory: Specifies a directory containing contracts written with the -GroovyDSL. The default directory is /src/test/resources/contracts.

    -
  • -
  • -

    generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.

    -
  • -
  • -

    generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated

    -
  • -
  • -

    testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and -JUnit 5 are supported with JUnit 4 being the default framework.

    -
  • -
  • -

    packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests. The convention is such that, if you -have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set -the value of the packageWithBaseClasses property to com.example.base, then Spring -Cloud Contract Verifier assumes that there is a BarBazBase class under the -com.example.base package. In other words, the system takes the last two parts of the -package, if they exist, and forms a class with a Base suffix.

    -
  • -
  • -

    baseClassMappings: Specifies a list of base class mappings that provide -contractPackageRegex, which is checked against the package where the contract is -located, and baseClassFQN, which maps to the fully qualified name of the base class for -the matched contract. For example, if you have a contract under -src/test/resources/contract/foo/bar/baz/ and map the property -.* → com.example.base.BaseClass, then the test class generated from these contracts -extends com.example.base.BaseClass. This setting takes precedence over -packageWithBaseClasses and baseClassForTests.

    -
  • -
  • -

    contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

    -
  • -
-
-
-

If you want to download your contract definitions from a Maven repository, you can use -the following options:

-
-
-
    -
  • -

    contractDependency: The contract dependency that contains all the packaged contracts.

    -
  • -
  • -

    contractsPath: The path to the concrete contracts in the JAR with packaged contracts. -Defaults to groupid/artifactid where gropuid is slash separated.

    -
  • -
  • -

    contractsMode: Picks the mode in which stubs will be found and registered

    -
  • -
  • -

    deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

    -
  • -
  • -

    contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, -use the current Maven ones.

    -
  • -
  • -

    contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryPassword: The password to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.

    -
  • -
  • -

    contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

    -
  • -
-
-
-

We cache only non-snapshot, explicitly provided versions (for example -+ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

-
-
-

Below you can find a list of experimental features you can turn on via the plugin:

-
-
-
    -
  • -

    convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.

    -
  • -
  • -

    assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

    -
  • -
-
-
-
-

Single Base Class for All Tests

-
-

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base -specification for all generated acceptance tests. In this class, you need to point to an -endpoint, which should be verified.

-
-
-
-
package org.mycompany.tests
-
-import org.mycompany.ExampleSpringController
-import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
-import spock.lang.Specification
-
-class MvcSpec extends Specification {
-  def setup() {
-   RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
-  }
-}
-
-
-
-

You can also setup the whole context if necessary.

-
-
-
-
import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.context.WebApplicationContext;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
-public abstract class BaseTestClass {
-
-	@Autowired
-	WebApplicationContext context;
-
-	@Before
-	public void setup() {
-		RestAssuredMockMvc.webAppContextSetup(this.context);
-	}
-}
-
-
-
-

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app -similarly, as you might find in regular integration tests.

-
-
-
-
import io.restassured.RestAssured;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.boot.web.server.LocalServerPort
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.context.WebApplicationContext;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
-public abstract class BaseTestClass {
-
-	@LocalServerPort
-	int port;
-
-	@Before
-	public void setup() {
-		RestAssured.baseURI = "http://localhost:" + this.port;
-	}
-}
-
-
-
-

If you use the JAXRSCLIENT mode, this base class should also contain a protected WebTarget webTarget field. Right -now, the only option to test the JAX-RS API is to start a web server.

-
-
-
-

Different base classes for contracts

-
-

If your base classes differ between contracts, you can tell the Spring Cloud Contract -plugin which class should get extended by the autogenerated tests. You have two options:

-
-
-
    -
  • -

    Follow a convention by providing the packageWithBaseClasses

    -
  • -
  • -

    provide explicit mapping via baseClassMappings

    -
  • -
-
-
-

By Convention

-
-
-

The convention is such that if you have a contract under (for example) -src/test/resources/contract/foo/bar/baz/ and set the value of the -packageWithBaseClasses property to com.example.base, then Spring Cloud Contract -Verifier assumes that there is a BarBazBase class under the com.example.base package. -In other words, the system takes the last two parts of the package, if they exist, and -forms a class with a Base suffix. This rule takes precedence over baseClassForTests. -Here is an example of how it works in the contracts closure:

-
-
-
-
-
-
-
-

By Mapping

-
-
-

You can manually map a regular expression of the contract’s package to fully qualified -name of the base class for the matched contract. You have to provide a list called -baseClassMappings that consists baseClassMapping objects that takes a -contractPackageRegex to baseClassFQN mapping. Consider the following example:

-
-
-
-
-
-
-
-

Assume that you have contracts under these two locations: -* src/test/resources/contract/com/ -* src/test/resources/contract/foo/

-
-
-

By providing the baseClassForTests, we have a fallback in case mapping did not succeed. -(You can also provide the packageWithBaseClasses as a fallback.) That way, the tests -generated from src/test/resources/contract/com/ contracts extend the -com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

-
-
-
-

Invoking generated tests

-
-

The Spring Cloud Contract Maven Plugin generates verification code in a directory called -/generated-test-sources/contractVerifier and attaches this directory to testCompile -goal.

-
-
-

For Groovy Spock code, use the following:

-
-
-
-
<plugin>
-	<groupId>org.codehaus.gmavenplus</groupId>
-	<artifactId>gmavenplus-plugin</artifactId>
-	<version>1.5</version>
-	<executions>
-		<execution>
-			<goals>
-				<goal>testCompile</goal>
-			</goals>
-		</execution>
-	</executions>
-	<configuration>
-		<testSources>
-			<testSource>
-				<directory>${project.basedir}/src/test/groovy</directory>
-				<includes>
-					<include>**/*.groovy</include>
-				</includes>
-			</testSource>
-			<testSource>
-				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
-				<includes>
-					<include>**/*.groovy</include>
-				</includes>
-			</testSource>
-		</testSources>
-	</configuration>
-</plugin>
-
-
-
-

To ensure that provider side is compliant with defined contracts, you need to invoke -mvn generateTest test.

-
-
-
-

Pushing stubs to SCM

-
-

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to add the pushStubsToScm -goal. Example:

-
-
-
-
<plugin>
-    <groupId>org.springframework.cloud</groupId>
-    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-    <version>${spring-cloud-contract.version}</version>
-    <extensions>true</extensions>
-    <configuration>
-        <!-- Base class mappings etc. -->
-
-        <!-- We want to pick contracts from a Git repository -->
-        <contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
-
-        <!-- We reuse the contract dependency section to set up the path
-        to the folder that contains the contract definitions. In our case the
-        path will be /groupId/artifactId/version/contracts -->
-        <contractDependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>${project.artifactId}</artifactId>
-            <version>${project.version}</version>
-        </contractDependency>
-
-        <!-- The contracts mode can't be classpath -->
-        <contractsMode>REMOTE</contractsMode>
-    </configuration>
-    <executions>
-        <execution>
-            <phase>package</phase>
-            <goals>
-                <!-- By default we will not push the stubs back to SCM,
-                you have to explicitly add it as a goal -->
-                <goal>pushStubsToScm</goal>
-            </goals>
-        </execution>
-    </executions>
-</plugin>
-
-
-
-

Under [scm-stub-downloader] you can find all possible -configuration options that you can pass either via -the <configuration><contractProperties> map, a system property -or an environment variable.

-
-
-
-

Maven Plugin and STS

-
-

If you see the following exception while using STS:

-
-
-

When you click on the error marker you should see something like this:

-
-
-
-
 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
- cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
- org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
-...
- org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
- org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
- org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
-
-
-
-

In order to fix this issue, provide the following section in your pom.xml:

-
-
-
-
<build>
-    <pluginManagement>
-        <plugins>
-            <!--This plugin's configuration is used to store Eclipse m2e settings
-                only. It has no influence on the Maven build itself. -->
-            <plugin>
-                <groupId>org.eclipse.m2e</groupId>
-                <artifactId>lifecycle-mapping</artifactId>
-                <version>1.0.0</version>
-                <configuration>
-                    <lifecycleMappingMetadata>
-                        <pluginExecutions>
-                             <pluginExecution>
-                                <pluginExecutionFilter>
-                                    <groupId>org.springframework.cloud</groupId>
-                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                    <versionRange>[1.0,)</versionRange>
-                                    <goals>
-                                        <goal>convert</goal>
-                                    </goals>
-                                </pluginExecutionFilter>
-                                <action>
-                                    <execute />
-                                </action>
-                             </pluginExecution>
-                        </pluginExecutions>
-                    </lifecycleMappingMetadata>
-                </configuration>
-            </plugin>
-        </plugins>
-    </pluginManagement>
-</build>
-
-
-
-
-

Maven Plugin with Spock Tests

-
-

You can select the Spock Framework for creating and executing the auto-generated contract -verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, -in Maven you will require some additional setup in order to make the tests compile and execute properly.

-
-
-

First of all, you will have to use a plugin, such as GMavenPlus plugin, -to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the -path where your base test classes are defined and the path were the generated contract tests are added. -Please refer to the example below:

-
-
-
-
-
-
-
-

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven -Surefire plugin setup, like in the following example:

-
-
-
-
-
-
-
-
-
-

Stubs and Transitive Dependencies

-
-

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One -problem that arises is that, when reusing the stubs, you can mistakenly import all of -that stub’s dependencies. When building a Maven artifact, even though you have a couple -of different jars, all of them share one pom:

-
-
-
-
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
-├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
-├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
-├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
-├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
-├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
-├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
-├── ...
-└── ...
-
-
-
-

There are three possibilities of working with those dependencies so as not to have any -issues with transitive dependencies:

-
-
-
    -
  • -

    Mark all application dependencies as optional

    -
  • -
  • -

    Create a separate artifactid for the stubs

    -
  • -
  • -

    Exclude dependencies on the consumer side

    -
  • -
-
-
-

Mark all application dependencies as optional

-
-
-

If, in the github-webhook application, you mark all of your dependencies as optional, -when you include the github-webhook stubs in another application (or when that -dependency gets downloaded by Stub Runner) then, since all of the dependencies are -optional, they will not get downloaded.

-
-
-

Create a separate artifactid for the stubs

-
-
-

If you create a separate artifactid, then you can set it up in whatever way you wish. -For example, you might decide to have no dependencies at all.

-
-
-

Exclude dependencies on the consumer side

-
-
-

As a consumer, if you add the stub dependency to your classpath, you can explicitly -exclude the unwanted dependencies.

-
-
-
-

Scenarios

-
-

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to -stick to the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This will work regardles - of whether you’re working with YAML or Groovy. Example:

-
-
-
-
my_contracts_dir\
-  scenario1\
-    1_login.groovy
-    2_showCart.groovy
-    3_logout.groovy
-
-
-
-

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a -name of scenario1 and the three following steps:

-
-
-
    -
  1. -

    login marked as Started pointing to…​

    -
  2. -
  3. -

    showCart marked as Step1 pointing to…​

    -
  4. -
  5. -

    logout marked as Step2 which will close the scenario.

    -
  6. -
-
-
-

More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/

-
-
-

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

-
-
-
-

Docker Project

-
-

We’re publishing a springcloud/spring-cloud-contract Docker image -that contains a project that will generate tests and execute them in EXPLICIT mode -against a running application.

-
-
- - - - - -
- - -The EXPLICIT mode means that the tests generated from contracts will send -real requests and not the mocked ones. -
-
-
-

Short intro to Maven, JARs and Binary storage

-
-

Since the Docker image can be used by non JVM projects, it’s good to -explain the basic terms behind Spring Cloud Contract packaging defaults.

-
-
-

Part of the following definitions were taken from the Maven Glossary

-
-
-
    -
  • -

    Project: Maven thinks in terms of projects. Everything that you -will build are projects. Those projects follow a well defined -“Project Object Model”. Projects can depend on other projects, -in which case the latter are called “dependencies”. A project may -consistent of several subprojects, however these subprojects are still -treated equally as projects.

    -
  • -
  • -

    Artifact: An artifact is something that is either produced or used -by a project. Examples of artifacts produced by Maven for a project -include: JARs, source and binary distributions. Each artifact -is uniquely identified by a group id and an artifact ID which is -unique within a group.

    -
  • -
  • -

    JAR: JAR stands for Java ARchive. It’s a format based on -the ZIP file format. Spring Cloud Contract packages the contracts and generated -stubs in a JAR file.

    -
  • -
  • -

    GroupId: A group ID is a universally unique identifier for a project. -While this is often just the project name (eg. commons-collections), -it is helpful to use a fully-qualified package name to distinguish it -from other projects with a similar name (eg. org.apache.maven). -Typically, when published to the Artifact Manager, the GroupId will get -slash separated and form part of the URL. E.g. for group id com.example -and artifact id application would be /com/example/application/.

    -
  • -
  • -

    Classifier: The Maven dependency notation looks as follows: -groupId:artifactId:version:classifier. The classifier is additional suffix -passed to the dependency. E.g. stubs, sources. The same dependency -e.g. com.example:application can produce multiple artifacts that -differ from each other with the classifier.

    -
  • -
  • -

    Artifact manager: When you generate binaries / sources / packages, you would -like them to be available for others to download / reference or reuse. In case -of the JVM world those artifacts would be JARs, for Ruby these are gems -and for Docker those would be Docker images. You can store those artifacts -in a manager. Examples of such managers can be Artifactory -or Nexus.

    -
  • -
-
-
-
-

How it works

-
-

The image searches for contracts under the /contracts folder. -The output from running the tests will be available under -/spring-cloud-contract/build folder (it’s useful for debugging -purposes).

-
-
-

It’s enough for you to mount your contracts, pass the environment variables - and the image will:

-
-
-
    -
  • -

    generate the contract tests

    -
  • -
  • -

    execute the tests against the provided URL

    -
  • -
  • -

    generate the WireMock stubs

    -
  • -
  • -

    (optional - turned on by default) publish the stubs to a Artifact Manager

    -
  • -
-
-
-
Environment Variables
-
-

The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance etc.

-
-
-
    -
  • -

    PROJECT_GROUP - your project’s group id. Defaults to com.example

    -
  • -
  • -

    PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT

    -
  • -
  • -

    PROJECT_NAME - artifact id. Defaults to example

    -
  • -
  • -

    PRODUCER_STUBS_CLASSIFIER - archive classifier used for generated producer stubs, defaults to stubs.

    -
  • -
  • -

    REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally

    -
  • -
  • -

    REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured, defaults to admin.

    -
  • -
  • -

    REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured, defaults to password.

    -
  • -
  • -

    PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

    -
  • -
-
-
-

These environment variables are used when contracts lay in an external repository. To enable -this feature you must set the EXTERNAL_CONTRACTS_ARTIFACT_ID environment variable.

-
-
-
    -
  • -

    EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example

    -
  • -
  • -

    EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default

    -
  • -
  • -

    EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. -If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME - (optional) username if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication, defaults to REPO_WITH_BINARIES_USERNAME. If that’s not set defaults to admin.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD - (optional) password if the EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL -requires authentication, defaults to REPO_WITH_BINARIES_PASSWORD. If that’s not set defaults to password.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. -Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. -for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.

    -
  • -
  • -

    EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts -from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. -You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

    -
  • -
-
-
-

These environment variables are used when tests are executed:

-
-
-
    -
  • -

    APPLICATION_BASE_URL - url against which tests should be executed. -Remember that it has to be accessible from the Docker container (e.g. localhost -will not work)

    -
  • -
  • -

    APPLICATION_USERNAME - (optional) username for basic authentication to your application

    -
  • -
  • -

    APPLICATION_PASSWORD - (optional) password for basic authentication to your application

    -
  • -
-
-
-
-
-

Example of usage

-
-

Let’s take a look at a simple MVC application

-
-
-
-
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
-$ cd bookstore
-
-
-
-

The contracts are available under /contracts folder.

-
-
-
-

Server side (nodejs)

-
-

Since we want to run tests, we could just execute:

-
-
-
-
$ npm test
-
-
-
-

however, for learning purposes, let’s split it into pieces:

-
-
-
-
# Stop docker infra (nodejs, artifactory)
-$ ./stop_infra.sh
-# Start docker infra (nodejs, artifactory)
-$ ./setup_infra.sh
-
-# Kill & Run app
-$ pkill -f "node app"
-$ nohup node app &
-
-# Prepare environment variables
-$ SC_CONTRACT_DOCKER_VERSION="..."
-$ APP_IP="192.168.0.100"
-$ APP_PORT="3000"
-$ ARTIFACTORY_PORT="8081"
-$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
-$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
-$ CURRENT_DIR="$( pwd )"
-$ CURRENT_FOLDER_NAME=${PWD##*/}
-$ PROJECT_VERSION="0.0.1.RELEASE"
-
-# Execute contract tests
-$ docker run  --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
-
-# Kill app
-$ pkill -f "node app"
-
-
-
-

What will happen is that via bash scripts:

-
-
-
    -
  • -

    infrastructure will be set up (MongoDb, Artifactory). -In real life scenario you would just run the NodeJS application -with mocked database. In this example we want to show how we can -benefit from Spring Cloud Contract in no time.

    -
  • -
  • -

    due to those constraints the contracts also represent the -stateful situation

    -
    -
      -
    • -

      first request is a POST that causes data to get inserted to the database

      -
    • -
    • -

      second request is a GET that returns a list of data with 1 previously inserted element

      -
    • -
    -
    -
  • -
  • -

    the NodeJS application will be started (on port 3000)

    -
  • -
  • -

    contract tests will be generated via Docker and tests -will be executed against the running application

    -
    -
      -
    • -

      the contracts will be taken from /contracts folder.

      -
    • -
    • -

      the output of the test execution is available under -node_modules/spring-cloud-contract/output.

      -
    • -
    -
    -
  • -
  • -

    the stubs will be uploaded to Artifactory. You can check them out -under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    -
  • -
-
-
-

To see how the client side looks like check out the [stubrunner-docker] section.

-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_stubrunner.html b/reference/html/verifier_stubrunner.html index 33efa3d1b1..9990b6e5bb 100644 --- a/reference/html/verifier_stubrunner.html +++ b/reference/html/verifier_stubrunner.html @@ -1,431 +1,12 @@ - - - + + - - - -Spring Cloud Contract Stub Runner - - + - - - - - - -
-
-

Spring Cloud Contract Stub Runner

-
-
-

One of the issues that you might encounter while using Spring Cloud Contract Verifier is -passing the generated WireMock JSON stubs from the server side to the client side (or to -various clients). The same takes place in terms of client-side generation for messaging.

-
-
-

Copying the JSON files and setting the client side for messaging manually is out of the -question. That is why we introduced Spring Cloud Contract Stub Runner. It can -automatically download and run the stubs for you.

-
-
-

Snapshot versions

-
-

Add the additional snapshot repository to your build.gradle file to use snapshot -versions, which are automatically uploaded after every successful build:

-
-
-
Maven
-
-
-
-
-
-
Gradle
-
-
-
-
-
-
-

Publishing Stubs as JARs

-
-

The easiest approach would be to centralize the way stubs are kept. For example, you can -keep them as jars in a Maven repository.

-
-
- - - - - -
- - -For both Maven and Gradle, the setup comes ready to work. However, you can customize -it if you want to. -
-
-
-
Maven
-
-
<!-- First disable the default jar setup in the properties section -->
+Page Redirection
 
-<!-- Next add the assembly plugin to your build -->
-
-<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
-
-
-
-
Gradle
-
-
-
-
-
-
-

Common

-
-

This section briefly describes common properties, including:

-
- -
-

Common Properties for JUnit and Spring

-
-

You can set repetitive properties by using system properties or Spring configuration -properties. Here are their names with their default values:

-
- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

Array of Ivy notation stubs to download.

stubrunner.username

Optional username to access the tool that stores the JARs with -stubs.

stubrunner.password

Optional password to access the tool that stores the JARs with -stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for -each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

If you want to use a stub for each consumer and want to -override the consumer name just change this value.

-
-
-

Stub Runner Stubs IDs

-
-

You can provide the stubs to download via the stubrunner.ids system property. They -follow this pattern:

-
-
-
-
groupId:artifactId:version:classifier:port
-
-
-
-

Note that version, classifier and port are optional.

-
-
-
    -
  • -

    If you do not provide the port, a random one will be picked.

    -
  • -
  • -

    If you do not provide the classifier, the default is used. (Note that you can -pass an empty classifier this way: groupId:artifactId:version:).

    -
  • -
  • -

    If you do not provide the version, then the + will be passed and the latest one is -downloaded.

    -
  • -
-
-
-

port means the port of the WireMock server.

-
-
- - - - - -
- - -Starting with version 1.0.4, you can provide a range of versions that you -would like the Stub Runner to take into consideration. You can read more about the -Aether versioning -ranges here. -
-
-
-
-
-

Stub Runner Docker

-
-

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image -that will start the standalone version of Stub Runner.

-
-
-

If you want to learn more about the basics of Maven, artifact ids, -group ids, classifiers and Artifact Managers, just click here [docker-project].

-
-
-

How to use it

-
-

Just execute the docker image. You can pass any of the Common Properties for JUnit and Spring -as environment variables. The convention is that all the -letters should be upper case. The camel case notation should -and the dot (.) should be separated via underscore (_). E.g. - the stubrunner.repositoryRoot property should be represented - as a STUBRUNNER_REPOSITORY_ROOT environment variable.

-
-
-
-

Example of client side usage in a non JVM project

-
-

We’d like to use the stubs created in this [docker-server-side] step. -Let’s assume that we want to run the stubs on port 9876. The NodeJS code -is available here:

-
-
-
-
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
-$ cd bookstore
-
-
-
-

Let’s run the Stub Runner Boot application with the stubs.

-
-
-
-
# Provide the Spring Cloud Contract Docker version
-$ SC_CONTRACT_DOCKER_VERSION="..."
-# The IP at which the app is running and Docker container can reach it
-$ APP_IP="192.168.0.100"
-# Spring Cloud Contract Stub Runner properties
-$ STUBRUNNER_PORT="8083"
-# Stub coordinates 'groupId:artifactId:version:classifier:port'
-$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
-$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
-# Run the docker with Stub Runner Boot
-$ docker run  --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
-
-
-
-

What’s happening is that

-
-
-
    -
  • -

    a standalone Stub Runner application got started

    -
  • -
  • -

    it downloaded the stub with coordinates com.example:bookstore:0.0.1.RELEASE:stubs on port 9876

    -
  • -
  • -

    it got downloaded from Artifactory running at http://192.168.0.100:8081/artifactory/libs-release-local

    -
  • -
  • -

    after a while Stub Runner will be running on port 8083

    -
  • -
  • -

    and the stubs will be running at port 9876

    -
  • -
-
-
-

On the server side we built a stateful stub. Let’s use curl to assert -that the stubs are setup properly.

-
-
-
-
# let's execute the first request (no response is returned)
-$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
-# Now time for the second request
-$ curl -X GET http://localhost:9876/api/books
-# You will receive contents of the JSON
-
-
-
- - - - - -
- - -If you want use the stubs that you have built locally, on your host, -then you should pass the environment variable -e STUBRUNNER_STUBS_MODE=LOCAL and mount -the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro" -
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/verifier_stubrunner_msg.html b/reference/html/verifier_stubrunner_msg.html index 103d889f7d..9990b6e5bb 100644 --- a/reference/html/verifier_stubrunner_msg.html +++ b/reference/html/verifier_stubrunner_msg.html @@ -1,223 +1,12 @@ - - - + + - - - -Stub Runner for Messaging - - + - - - - - - -
-
-

Stub Runner for Messaging

-
-
-

Stub Runner can run the published stubs in memory. It can integrate with the following -frameworks:

-
-
-
    -
  • -

    Spring Integration

    -
  • -
  • -

    Spring Cloud Stream

    -
  • -
  • -

    Apache Camel

    -
  • -
  • -

    Spring AMQP

    -
  • -
-
-
-

It also provides entry points to integrate with any other solution on the market.

-
-
- - - - - -
- - -If you have multiple frameworks on the classpath Stub Runner will need to -define which one should be used. Let’s assume that you have both AMQP, Spring Cloud Stream and Spring Integration -on the classpath. Then you need to set stubrunner.stream.enabled=false and stubrunner.integration.enabled=false. -That way the only remaining framework is Spring AMQP. -
-
-
-

Stub triggering

-
-

To trigger a message, use the StubTrigger interface:

-
-
-
-
-
-
-
-

For convenience, the StubFinder interface extends StubTrigger, so you only need one -or the other in your tests.

-
-
-

StubTrigger gives you the following options to trigger a message:

-
- -
-

Trigger by Label

-
-
-
-
-
-
- - -
-

Trigger All Messages

-
-
-
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/reference/html/yml-schema.html b/reference/html/yml-schema.html index fd045d53f0..9990b6e5bb 100644 --- a/reference/html/yml-schema.html +++ b/reference/html/yml-schema.html @@ -1,592 +1,12 @@ - - - + + - - - -YML Schema - - - - - - - - - -
-
-

YML Schema

-
-
-

Below you can find a JSON schema definition of a YAML contract.

-
-
-
-
-
-
{
-  "type" : "object",
-  "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract",
-  "properties" : {
-    "request" : {
-      "type" : "object",
-      "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:Request",
-      "properties" : {
-        "method" : {
-          "type" : "string"
-        },
-        "url" : {
-          "type" : "string"
-        },
-        "urlPath" : {
-          "type" : "string"
-        },
-        "queryParameters" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "headers" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "cookies" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "body" : {
-          "type" : "any"
-        },
-        "bodyFromFile" : {
-          "type" : "string"
-        },
-        "bodyFromFileAsBytes" : {
-          "type" : "string"
-        },
-        "matchers" : {
-          "type" : "object",
-          "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:StubMatchers",
-          "properties" : {
-            "url" : {
-              "type" : "object",
-              "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:KeyValueMatcher",
-              "properties" : {
-                "key" : {
-                  "type" : "string"
-                },
-                "regex" : {
-                  "type" : "string"
-                },
-                "predefined" : {
-                  "type" : "string",
-                  "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                },
-                "command" : {
-                  "type" : "string"
-                },
-                "regexType" : {
-                  "type" : "string",
-                  "enum" : [ "as_integer", "as_double", "as_float", "as_long", "as_short", "as_boolean", "as_string" ]
-                }
-              }
-            },
-            "body" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:BodyStubMatcher",
-                "properties" : {
-                  "path" : {
-                    "type" : "string"
-                  },
-                  "type" : {
-                    "type" : "string",
-                    "enum" : [ "by_date", "by_time", "by_timestamp", "by_regex", "by_equality", "by_type", "by_null" ]
-                  },
-                  "value" : {
-                    "type" : "string"
-                  },
-                  "predefined" : {
-                    "type" : "string",
-                    "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                  },
-                  "minOccurrence" : {
-                    "type" : "integer"
-                  },
-                  "maxOccurrence" : {
-                    "type" : "integer"
-                  },
-                  "regexType" : {
-                    "type" : "string",
-                    "enum" : [ "as_integer", "as_double", "as_float", "as_long", "as_short", "as_boolean", "as_string" ]
-                  }
-                }
-              }
-            },
-            "headers" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:KeyValueMatcher"
-              }
-            },
-            "queryParameters" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:QueryParameterMatcher",
-                "properties" : {
-                  "key" : {
-                    "type" : "string"
-                  },
-                  "type" : {
-                    "type" : "string",
-                    "enum" : [ "equal_to", "containing", "matching", "not_matching", "equal_to_json", "equal_to_xml", "absent", "binary_equal_to" ]
-                  },
-                  "value" : {
-                    "type" : "any"
-                  }
-                }
-              }
-            },
-            "cookies" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:KeyValueMatcher"
-              }
-            },
-            "multipart" : {
-              "type" : "object",
-              "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:MultipartStubMatcher",
-              "properties" : {
-                "params" : {
-                  "type" : "array",
-                  "items" : {
-                    "type" : "object",
-                    "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:KeyValueMatcher"
-                  }
-                },
-                "named" : {
-                  "type" : "array",
-                  "items" : {
-                    "type" : "object",
-                    "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:MultipartNamedStubMatcher",
-                    "properties" : {
-                      "paramName" : {
-                        "type" : "string"
-                      },
-                      "fileName" : {
-                        "type" : "object",
-                        "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:ValueMatcher",
-                        "properties" : {
-                          "regex" : {
-                            "type" : "string"
-                          },
-                          "predefined" : {
-                            "type" : "string",
-                            "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                          }
-                        }
-                      },
-                      "fileContent" : {
-                        "type" : "object",
-                        "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:ValueMatcher"
-                      },
-                      "contentType" : {
-                        "type" : "object",
-                        "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:ValueMatcher"
-                      }
-                    }
-                  }
-                }
-              }
-            }
-          }
-        },
-        "multipart" : {
-          "type" : "object",
-          "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:Multipart",
-          "properties" : {
-            "params" : {
-              "type" : "object",
-              "additionalProperties" : {
-                "type" : "string"
-              }
-            },
-            "named" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:Named",
-                "properties" : {
-                  "paramName" : {
-                    "type" : "string"
-                  },
-                  "fileName" : {
-                    "type" : "string"
-                  },
-                  "fileContent" : {
-                    "type" : "string"
-                  },
-                  "fileContentAsBytes" : {
-                    "type" : "string"
-                  },
-                  "fileContentFromFileAsBytes" : {
-                    "type" : "string"
-                  },
-                  "contentType" : {
-                    "type" : "string"
-                  },
-                  "fileNameCommand" : {
-                    "type" : "string"
-                  },
-                  "fileContentCommand" : {
-                    "type" : "string"
-                  },
-                  "contentTypeCommand" : {
-                    "type" : "string"
-                  }
-                }
-              }
-            }
-          }
-        }
-      }
-    },
-    "response" : {
-      "type" : "object",
-      "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:Response",
-      "properties" : {
-        "status" : {
-          "type" : "integer"
-        },
-        "headers" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "cookies" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "body" : {
-          "type" : "any"
-        },
-        "bodyFromFile" : {
-          "type" : "string"
-        },
-        "bodyFromFileAsBytes" : {
-          "type" : "string"
-        },
-        "matchers" : {
-          "type" : "object",
-          "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:TestMatchers",
-          "properties" : {
-            "body" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:BodyTestMatcher",
-                "properties" : {
-                  "path" : {
-                    "type" : "string"
-                  },
-                  "type" : {
-                    "type" : "string",
-                    "enum" : [ "by_date", "by_time", "by_timestamp", "by_regex", "by_equality", "by_type", "by_command", "by_null" ]
-                  },
-                  "value" : {
-                    "type" : "string"
-                  },
-                  "minOccurrence" : {
-                    "type" : "integer"
-                  },
-                  "maxOccurrence" : {
-                    "type" : "integer"
-                  },
-                  "predefined" : {
-                    "type" : "string",
-                    "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                  },
-                  "regexType" : {
-                    "type" : "string",
-                    "enum" : [ "as_integer", "as_double", "as_float", "as_long", "as_short", "as_boolean", "as_string" ]
-                  }
-                }
-              }
-            },
-            "headers" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:TestHeaderMatcher",
-                "properties" : {
-                  "key" : {
-                    "type" : "string"
-                  },
-                  "regex" : {
-                    "type" : "string"
-                  },
-                  "command" : {
-                    "type" : "string"
-                  },
-                  "predefined" : {
-                    "type" : "string",
-                    "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                  },
-                  "regexType" : {
-                    "type" : "string",
-                    "enum" : [ "as_integer", "as_double", "as_float", "as_long", "as_short", "as_boolean", "as_string" ]
-                  }
-                }
-              }
-            },
-            "cookies" : {
-              "type" : "array",
-              "items" : {
-                "type" : "object",
-                "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:TestCookieMatcher",
-                "properties" : {
-                  "key" : {
-                    "type" : "string"
-                  },
-                  "regex" : {
-                    "type" : "string"
-                  },
-                  "command" : {
-                    "type" : "string"
-                  },
-                  "predefined" : {
-                    "type" : "string",
-                    "enum" : [ "only_alpha_unicode", "number", "any_double", "any_boolean", "ip_address", "hostname", "email", "url", "uuid", "iso_date", "iso_date_time", "iso_time", "iso_8601_with_offset", "non_empty", "non_blank" ]
-                  },
-                  "regexType" : {
-                    "type" : "string",
-                    "enum" : [ "as_integer", "as_double", "as_float", "as_long", "as_short", "as_boolean", "as_string" ]
-                  }
-                }
-              }
-            }
-          }
-        },
-        "async" : {
-          "type" : "boolean"
-        },
-        "fixedDelayMilliseconds" : {
-          "type" : "integer"
-        }
-      }
-    },
-    "input" : {
-      "type" : "object",
-      "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:Input",
-      "properties" : {
-        "messageFrom" : {
-          "type" : "string"
-        },
-        "triggeredBy" : {
-          "type" : "string"
-        },
-        "messageHeaders" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "messageBody" : {
-          "type" : "any"
-        },
-        "messageBodyFromFile" : {
-          "type" : "string"
-        },
-        "messageBodyFromFileAsBytes" : {
-          "type" : "string"
-        },
-        "assertThat" : {
-          "type" : "string"
-        },
-        "matchers" : {
-          "type" : "object",
-          "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:StubMatchers"
-        }
-      }
-    },
-    "outputMessage" : {
-      "type" : "object",
-      "id" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:OutputMessage",
-      "properties" : {
-        "sentTo" : {
-          "type" : "string"
-        },
-        "headers" : {
-          "type" : "object",
-          "additionalProperties" : {
-            "type" : "any"
-          }
-        },
-        "body" : {
-          "type" : "any"
-        },
-        "bodyFromFile" : {
-          "type" : "string"
-        },
-        "bodyFromFileAsBytes" : {
-          "type" : "string"
-        },
-        "assertThat" : {
-          "type" : "string"
-        },
-        "matchers" : {
-          "type" : "object",
-          "$ref" : "urn:jsonschema:org:springframework:cloud:contract:verifier:converter:YamlContract:TestMatchers"
-        }
-      }
-    },
-    "description" : {
-      "type" : "string"
-    },
-    "label" : {
-      "type" : "string"
-    },
-    "name" : {
-      "type" : "string"
-    },
-    "priority" : {
-      "type" : "integer"
-    },
-    "ignored" : {
-      "type" : "boolean"
-    },
-    "inProgress" : {
-      "type" : "boolean"
-    }
-  }
-}
-
-
-
-
-
-
-
- - - - - - - \ No newline at end of file +Page Redirection + +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/checkstyle.html b/spring-cloud-contract-maven-plugin/checkstyle.html index 493a85fc81..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/checkstyle.html +++ b/spring-cloud-contract-maven-plugin/checkstyle.html @@ -1,3862 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Checkstyle Results - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Checkstyle Results

-

The following document contains the results of Checkstyle 8.29 with sun_checks.xml ruleset. 

rss feed

-

Summary

- - - - - - - - - - -
Files
 Info
 Warnings
 Errors
1400547
-

Files

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
File
 I
 W
 E
org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java0026
org/springframework/cloud/contract/maven/verifier/ChangeDetector.java009
org/springframework/cloud/contract/maven/verifier/ConvertMojo.java0095
org/springframework/cloud/contract/maven/verifier/CopyContracts.java0037
org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java0047
org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java00110
org/springframework/cloud/contract/maven/verifier/LeftOverPrevention.java0011
org/springframework/cloud/contract/maven/verifier/ManifestCreator.java0016
org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java0084
org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java0025
org/springframework/cloud/contract/maven/verifier/RunMojo.java0032
org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java0028
org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java008
org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java0019
-

Rules

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CategoryRuleViolationsSeverity
blocksRightCurly13
 Error
codingHiddenField36
 Error
MagicNumber1
 Error
designDesignForExtension23
 Error
javadocJavadocPackage2
 Error
JavadocVariable80
 Error
MissingJavadocMethod18
 Error
miscFinalParameters70
 Error
namingConstantName4
 Error
sizesLineLength -
    -
  • fileExtensions: "java"
284
 Error
ParameterNumber1
 Error
whitespaceFileTabCharacter14
 Error
NoWhitespaceAfter1
 Error
-

Details

-

org/springframework/cloud/contract/maven/verifier/BaseClassMapping.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
sizesLineLengthLine is longer than 80 characters (found 87).20
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).28
 Error
javadocJavadocVariableMissing a Javadoc comment.28
 Error
javadocJavadocVariableMissing a Javadoc comment.30
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'getContractPackageRegex' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'getContractPackageRegex' static/final/abstract/empty, or adding allowed annotation for the method.32
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.32
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'setContractPackageRegex' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'setContractPackageRegex' static/final/abstract/empty, or adding allowed annotation for the method.36
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.36
 Error
miscFinalParametersParameter contractPackageRegex should be final.36
 Error
codingHiddenField'contractPackageRegex' hides a field.36
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'getBaseClassFQN' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'getBaseClassFQN' static/final/abstract/empty, or adding allowed annotation for the method.40
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.40
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'setBaseClassFQN' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'setBaseClassFQN' static/final/abstract/empty, or adding allowed annotation for the method.44
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.44
 Error
miscFinalParametersParameter baseClassFQN should be final.44
 Error
codingHiddenField'baseClassFQN' hides a field.44
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'equals' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'equals' static/final/abstract/empty, or adding allowed annotation for the method.48
 Error
miscFinalParametersParameter o should be final.49
 Error
sizesLineLengthLine is longer than 80 characters (found 94).58
 Error
sizesLineLengthLine is longer than 80 characters (found 94).62
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'hashCode' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'hashCode' static/final/abstract/empty, or adding allowed annotation for the method.67
 Error
codingMagicNumber'31' is a magic number.71
 Error
sizesLineLengthLine is longer than 80 characters (found 97).72
 Error
designDesignForExtensionClass 'BaseClassMapping' looks like designed for extension (can be subclassed), but the method 'toString' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'BaseClassMapping' final or making the method 'toString' static/final/abstract/empty, or adding allowed annotation for the method.76
 Error
sizesLineLengthLine is longer than 80 characters (found 97).78
 Error
sizesLineLengthLine is longer than 80 characters (found 93).79
-

org/springframework/cloud/contract/maven/verifier/ChangeDetector.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).29
 Error
miscFinalParametersParameter contractsDirectory should be final.32
 Error
miscFinalParametersParameter mojoExecution should be final.33
 Error
miscFinalParametersParameter session should be final.33
 Error
sizesLineLengthLine is longer than 80 characters (found 91).36
 Error
sizesLineLengthLine is longer than 80 characters (found 88).39
 Error
sizesLineLengthLine is longer than 80 characters (found 94).42
 Error
sizesLineLengthLine is longer than 80 characters (found 91).44
 Error
sizesLineLengthLine is longer than 80 characters (found 102).45
-

org/springframework/cloud/contract/maven/verifier/ConvertMojo.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
sizesLineLengthLine is longer than 80 characters (found 86).46
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).52
 Error
sizesLineLengthLine is longer than 80 characters (found 84).55
 Error
javadocJavadocVariableMissing a Javadoc comment.55
 Error
javadocJavadocVariableMissing a Javadoc comment.56
 Error
javadocJavadocVariableMissing a Javadoc comment.57
 Error
javadocJavadocVariableMissing a Javadoc comment.58
 Error
javadocJavadocVariableMissing a Javadoc comment.60
 Error
sizesLineLengthLine is longer than 80 characters (found 90).64
 Error
sizesLineLengthLine is longer than 80 characters (found 82).67
 Error
sizesLineLengthLine is longer than 80 characters (found 89).68
 Error
sizesLineLengthLine is longer than 80 characters (found 93).72
 Error
sizesLineLengthLine is longer than 80 characters (found 86).81
 Error
javadocJavadocVariableMissing a Javadoc comment.86
 Error
sizesLineLengthLine is longer than 80 characters (found 92).89
 Error
javadocJavadocVariableMissing a Javadoc comment.89
 Error
javadocJavadocVariableMissing a Javadoc comment.92
 Error
javadocJavadocVariableMissing a Javadoc comment.95
 Error
sizesLineLengthLine is longer than 80 characters (found 90).99
 Error
sizesLineLengthLine is longer than 80 characters (found 87).100
 Error
javadocJavadocVariableMissing a Javadoc comment.106
 Error
sizesLineLengthLine is longer than 80 characters (found 89).110
 Error
sizesLineLengthLine is longer than 80 characters (found 87).111
 Error
sizesLineLengthLine is longer than 80 characters (found 87).112
 Error
sizesLineLengthLine is longer than 80 characters (found 89).113
 Error
sizesLineLengthLine is longer than 80 characters (found 88).125
 Error
sizesLineLengthLine is longer than 80 characters (found 92).156
 Error
sizesLineLengthLine is longer than 80 characters (found 83).160
 Error
sizesLineLengthLine is longer than 80 characters (found 94).165
 Error
sizesLineLengthLine is longer than 80 characters (found 87).173
 Error
javadocJavadocVariableMissing a Javadoc comment.184
 Error
sizesLineLengthLine is longer than 80 characters (found 94).188
 Error
sizesLineLengthLine is longer than 80 characters (found 92).195
 Error
sizesLineLengthLine is longer than 80 characters (found 87).201
 Error
javadocJavadocVariableMissing a Javadoc comment.201
 Error
sizesLineLengthLine is longer than 80 characters (found 81).204
 Error
javadocJavadocVariableMissing a Javadoc comment.204
 Error
designDesignForExtensionClass 'ConvertMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'ConvertMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.207
 Error
sizesLineLengthLine is longer than 80 characters (found 132).211
 Error
sizesLineLengthLine is longer than 80 characters (found 91).218
 Error
sizesLineLengthLine is longer than 80 characters (found 97).220
 Error
codingHiddenField'contractsDirectory' hides a field.222
 Error
sizesLineLengthLine is longer than 80 characters (found 84).223
 Error
sizesLineLengthLine is longer than 80 characters (found 98).225
 Error
sizesLineLengthLine is longer than 80 characters (found 88).227
 Error
sizesLineLengthLine is longer than 80 characters (found 91).235
 Error
sizesLineLengthLine is longer than 80 characters (found 87).238
 Error
sizesLineLengthLine is longer than 80 characters (found 88).245
 Error
sizesLineLengthLine is longer than 80 characters (found 89).246
 Error
miscFinalParametersParameter rootPath should be final.252
 Error
sizesLineLengthLine is longer than 80 characters (found 89).253
 Error
miscFinalParametersParameter config should be final.253
 Error
miscFinalParametersParameter contractsDirectory should be final.253
 Error
codingHiddenField'contractsDirectory' hides a field.253
 Error
miscFinalParametersParameter contractsDslDir should be final.254
 Error
sizesLineLengthLine is longer than 80 characters (found 86).257
 Error
sizesLineLengthLine is longer than 80 characters (found 92).261
 Error
miscFinalParametersParameter rootPath should be final.261
 Error
miscFinalParametersParameter config should be final.261
 Error
miscFinalParametersParameter contractsDirectory should be final.262
 Error
codingHiddenField'contractsDirectory' hides a field.262
 Error
sizesLineLengthLine is longer than 80 characters (found 96).265
 Error
sizesLineLengthLine is longer than 80 characters (found 92).266
 Error
sizesLineLengthLine is longer than 80 characters (found 92).270
 Error
miscFinalParametersParameter rootPath should be final.270
 Error
miscFinalParametersParameter config should be final.270
 Error
miscFinalParametersParameter contractsDirectory should be final.271
 Error
codingHiddenField'contractsDirectory' hides a field.271
 Error
sizesLineLengthLine is longer than 80 characters (found 107).274
 Error
sizesLineLengthLine is longer than 80 characters (found 96).275
 Error
sizesLineLengthLine is longer than 80 characters (found 92).276
 Error
sizesLineLengthLine is longer than 80 characters (found 94).280
 Error
miscFinalParametersParameter config should be final.280
 Error
miscFinalParametersParameter contractsDslDir should be final.280
 Error
sizesLineLengthLine is longer than 80 characters (found 93).282
 Error
sizesLineLengthLine is longer than 80 characters (found 119).285
 Error
sizesLineLengthLine is longer than 80 characters (found 94).287
 Error
sizesLineLengthLine is longer than 80 characters (found 87).289
 Error
miscFinalParametersParameter contractsDirectory should be final.293
 Error
codingHiddenField'contractsDirectory' hides a field.293
 Error
sizesLineLengthLine is longer than 80 characters (found 84).294
 Error
sizesLineLengthLine is longer than 80 characters (found 123).298
 Error
sizesLineLengthLine is longer than 80 characters (found 83).305
 Error
miscFinalParametersParameter config should be final.305
 Error
sizesLineLengthLine is longer than 80 characters (found 90).306
 Error
sizesLineLengthLine is longer than 80 characters (found 100).307
 Error
sizesLineLengthLine is longer than 80 characters (found 100).309
 Error
sizesLineLengthLine is longer than 80 characters (found 93).310
 Error
sizesLineLengthLine is longer than 80 characters (found 81).311
 Error
sizesLineLengthLine is longer than 80 characters (found 93).312
 Error
sizesLineLengthLine is longer than 80 characters (found 89).313
 Error
miscFinalParametersParameter rootPath should be final.316
 Error
sizesLineLengthLine is longer than 80 characters (found 98).317
 Error
miscFinalParametersParameter contractsDirectory should be final.321
 Error
codingHiddenField'contractsDirectory' hides a field.321
-

org/springframework/cloud/contract/maven/verifier/CopyContracts.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).36
 Error
javadocJavadocVariableMissing a Javadoc comment.36
 Error
namingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.36
 Error
javadocJavadocVariableMissing a Javadoc comment.38
 Error
javadocJavadocVariableMissing a Javadoc comment.40
 Error
javadocJavadocVariableMissing a Javadoc comment.42
 Error
javadocJavadocVariableMissing a Javadoc comment.44
 Error
miscFinalParametersParameter project should be final.46
 Error
codingHiddenField'project' hides a field.46
 Error
miscFinalParametersParameter mavenSession should be final.46
 Error
codingHiddenField'mavenSession' hides a field.46
 Error
miscFinalParametersParameter mavenResourcesFiltering should be final.47
 Error
codingHiddenField'mavenResourcesFiltering' hides a field.47
 Error
miscFinalParametersParameter config should be final.48
 Error
codingHiddenField'config' hides a field.48
 Error
miscFinalParametersParameter contractsDirectory should be final.55
 Error
miscFinalParametersParameter outputDirectory should be final.55
 Error
sizesLineLengthLine is longer than 80 characters (found 98).57
 Error
sizesLineLengthLine is longer than 80 characters (found 102).58
 Error
sizesLineLengthLine is longer than 80 characters (found 93).59
 Error
sizesLineLengthLine is longer than 80 characters (found 89).63
 Error
sizesLineLengthLine is longer than 80 characters (found 85).65
 Error
sizesLineLengthLine is longer than 80 characters (found 93).69
 Error
sizesLineLengthLine is longer than 80 characters (found 82).80
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).93
 Error
sizesLineLengthLine is longer than 80 characters (found 93).99
 Error
miscFinalParametersParameter includedRootFolderAntPattern should be final.99
 Error
sizesLineLengthLine is longer than 80 characters (found 85).100
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).102
 Error
sizesLineLengthLine is longer than 80 characters (found 88).103
 Error
sizesLineLengthLine is longer than 80 characters (found 90).104
 Error
sizesLineLengthLine is longer than 80 characters (found 91).110
 Error
miscFinalParametersParameter includedRootFolderAntPattern should be final.110
 Error
sizesLineLengthLine is longer than 80 characters (found 83).111
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).113
 Error
sizesLineLengthLine is longer than 80 characters (found 90).114
 Error
sizesLineLengthLine is longer than 80 characters (found 92).115
-

org/springframework/cloud/contract/maven/verifier/GenerateStubsMojo.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
sizesLineLengthLine is longer than 80 characters (found 85).41
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).47
 Error
javadocJavadocVariableMissing a Javadoc comment.50
 Error
javadocJavadocVariableMissing a Javadoc comment.54
 Error
javadocJavadocVariableMissing a Javadoc comment.58
 Error
sizesLineLengthLine is longer than 80 characters (found 92).65
 Error
javadocJavadocVariableMissing a Javadoc comment.75
 Error
javadocJavadocVariableMissing a Javadoc comment.84
 Error
javadocJavadocVariableMissing a Javadoc comment.87
 Error
javadocJavadocVariableMissing a Javadoc comment.90
 Error
sizesLineLengthLine is longer than 80 characters (found 91).94
 Error
sizesLineLengthLine is longer than 80 characters (found 83).97
 Error
sizesLineLengthLine is longer than 80 characters (found 87).100
 Error
javadocJavadocVariableMissing a Javadoc comment.100
 Error
sizesLineLengthLine is longer than 80 characters (found 81).103
 Error
javadocJavadocVariableMissing a Javadoc comment.103
 Error
sizesLineLengthLine is longer than 80 characters (found 94).107
 Error
sizesLineLengthLine is longer than 80 characters (found 83).113
 Error
designDesignForExtensionClass 'GenerateStubsMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateStubsMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.113
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.113
 Error
sizesLineLengthLine is longer than 80 characters (found 129).116
 Error
sizesLineLengthLine is longer than 80 characters (found 114).117
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).120
 Error
sizesLineLengthLine is longer than 80 characters (found 95).121
 Error
sizesLineLengthLine is longer than 80 characters (found 164).123
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).125
 Error
sizesLineLengthLine is longer than 80 characters (found 94).126
 Error
sizesLineLengthLine is longer than 80 characters (found 86).127
 Error
sizesLineLengthLine is longer than 80 characters (found 114).129
 Error
sizesLineLengthLine is longer than 80 characters (found 104).132
 Error
sizesLineLengthLine is longer than 80 characters (found 87).133
 Error
sizesLineLengthLine is longer than 80 characters (found 87).137
 Error
miscFinalParametersParameter stubsOutputDir should be final.141
 Error
sizesLineLengthLine is longer than 80 characters (found 86).144
 Error
sizesLineLengthLine is longer than 80 characters (found 114).146
 Error
sizesLineLengthLine is longer than 80 characters (found 96).148
 Error
sizesLineLengthLine is longer than 80 characters (found 90).149
 Error
sizesLineLengthLine is longer than 80 characters (found 82).151
 Error
sizesLineLengthLine is longer than 80 characters (found 83).152
 Error
sizesLineLengthLine is longer than 80 characters (found 93).154
 Error
whitespaceNoWhitespaceAfter'{' is followed by whitespace.154
 Error
sizesLineLengthLine is longer than 80 characters (found 99).155
 Error
sizesLineLengthLine is longer than 80 characters (found 109).159
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).161
 Error
sizesLineLengthLine is longer than 80 characters (found 101).164
 Error
miscFinalParametersParameter stubsOutputDir should be final.169
 Error
sizesLineLengthLine is longer than 80 characters (found 84).184
-

org/springframework/cloud/contract/maven/verifier/GenerateTestsMojo.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
javadocJavadocPackageMissing package-info.java file.1
 Error
sizesLineLengthLine is longer than 80 characters (found 83).46
 Error
sizesLineLengthLine is longer than 80 characters (found 82).51
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).52
 Error
javadocJavadocVariableMissing a Javadoc comment.55
 Error
sizesLineLengthLine is longer than 80 characters (found 82).58
 Error
javadocJavadocVariableMissing a Javadoc comment.58
 Error
sizesLineLengthLine is longer than 80 characters (found 89).59
 Error
javadocJavadocVariableMissing a Javadoc comment.62
 Error
sizesLineLengthLine is longer than 80 characters (found 101).63
 Error
javadocJavadocVariableMissing a Javadoc comment.66
 Error
sizesLineLengthLine is longer than 80 characters (found 103).67
 Error
javadocJavadocVariableMissing a Javadoc comment.70
 Error
javadocJavadocVariableMissing a Javadoc comment.73
 Error
javadocJavadocVariableMissing a Javadoc comment.76
 Error
javadocJavadocVariableMissing a Javadoc comment.79
 Error
javadocJavadocVariableMissing a Javadoc comment.82
 Error
javadocJavadocVariableMissing a Javadoc comment.85
 Error
sizesLineLengthLine is longer than 80 characters (found 86).113
 Error
sizesLineLengthLine is longer than 80 characters (found 92).121
 Error
javadocJavadocVariableMissing a Javadoc comment.126
 Error
sizesLineLengthLine is longer than 80 characters (found 92).129
 Error
javadocJavadocVariableMissing a Javadoc comment.129
 Error
javadocJavadocVariableMissing a Javadoc comment.132
 Error
javadocJavadocVariableMissing a Javadoc comment.135
 Error
sizesLineLengthLine is longer than 80 characters (found 84).139
 Error
sizesLineLengthLine is longer than 80 characters (found 88).140
 Error
javadocJavadocVariableMissing a Javadoc comment.146
 Error
sizesLineLengthLine is longer than 80 characters (found 89).150
 Error
sizesLineLengthLine is longer than 80 characters (found 87).151
 Error
sizesLineLengthLine is longer than 80 characters (found 87).152
 Error
sizesLineLengthLine is longer than 80 characters (found 89).153
 Error
sizesLineLengthLine is longer than 80 characters (found 92).165
 Error
sizesLineLengthLine is longer than 80 characters (found 93).166
 Error
sizesLineLengthLine is longer than 80 characters (found 93).168
 Error
sizesLineLengthLine is longer than 80 characters (found 89).170
 Error
sizesLineLengthLine is longer than 80 characters (found 93).177
 Error
sizesLineLengthLine is longer than 80 characters (found 89).178
 Error
sizesLineLengthLine is longer than 80 characters (found 91).180
 Error
sizesLineLengthLine is longer than 80 characters (found 91).181
 Error
sizesLineLengthLine is longer than 80 characters (found 92).212
 Error
sizesLineLengthLine is longer than 80 characters (found 83).216
 Error
sizesLineLengthLine is longer than 80 characters (found 94).221
 Error
sizesLineLengthLine is longer than 80 characters (found 87).229
 Error
sizesLineLengthLine is longer than 80 characters (found 94).235
 Error
sizesLineLengthLine is longer than 80 characters (found 94).242
 Error
sizesLineLengthLine is longer than 80 characters (found 91).243
 Error
sizesLineLengthLine is longer than 80 characters (found 92).244
 Error
sizesLineLengthLine is longer than 80 characters (found 92).251
 Error
sizesLineLengthLine is longer than 80 characters (found 87).257
 Error
javadocJavadocVariableMissing a Javadoc comment.257
 Error
sizesLineLengthLine is longer than 80 characters (found 81).260
 Error
javadocJavadocVariableMissing a Javadoc comment.260
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.263
 Error
sizesLineLengthLine is longer than 80 characters (found 83).264
 Error
sizesLineLengthLine is longer than 80 characters (found 137).268
 Error
sizesLineLengthLine is longer than 80 characters (found 117).273
 Error
sizesLineLengthLine is longer than 80 characters (found 86).274
 Error
sizesLineLengthLine is longer than 80 characters (found 110).278
 Error
sizesLineLengthLine is longer than 80 characters (found 82).279
 Error
sizesLineLengthLine is longer than 80 characters (found 128).284
 Error
sizesLineLengthLine is longer than 80 characters (found 103).285
 Error
sizesLineLengthLine is longer than 80 characters (found 84).288
 Error
codingHiddenField'contractsDirectory' hides a field.288
 Error
sizesLineLengthLine is longer than 80 characters (found 105).289
 Error
sizesLineLengthLine is longer than 80 characters (found 95).290
 Error
sizesLineLengthLine is longer than 80 characters (found 100).291
 Error
sizesLineLengthLine is longer than 80 characters (found 93).292
 Error
sizesLineLengthLine is longer than 80 characters (found 81).293
 Error
sizesLineLengthLine is longer than 80 characters (found 93).294
 Error
sizesLineLengthLine is longer than 80 characters (found 89).295
 Error
sizesLineLengthLine is longer than 80 characters (found 102).297
 Error
sizesLineLengthLine is longer than 80 characters (found 104).300
 Error
sizesLineLengthLine is longer than 80 characters (found 90).301
 Error
sizesLineLengthLine is longer than 80 characters (found 106).307
 Error
sizesLineLengthLine is longer than 80 characters (found 88).309
 Error
sizesLineLengthLine is longer than 80 characters (found 102).313
 Error
sizesLineLengthLine is longer than 80 characters (found 88).316
 Error
sizesLineLengthLine is longer than 80 characters (found 101).317
 Error
sizesLineLengthLine is longer than 80 characters (found 101).318
 Error
sizesLineLengthLine is longer than 80 characters (found 87).322
 Error
sizesLineLengthLine is longer than 80 characters (found 94).323
 Error
sizesLineLengthLine is longer than 80 characters (found 90).326
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).328
 Error
sizesLineLengthLine is longer than 80 characters (found 108).331
 Error
miscFinalParametersParameter config should be final.337
 Error
miscFinalParametersParameter contractsDirectory should be final.338
 Error
codingHiddenField'contractsDirectory' hides a field.338
 Error
sizesLineLengthLine is longer than 80 characters (found 84).341
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'mappingsToMap' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'mappingsToMap' static/final/abstract/empty, or adding allowed annotation for the method.360
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.360
 Error
sizesLineLengthLine is longer than 80 characters (found 94).366
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'getExcludedFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'getExcludedFiles' static/final/abstract/empty, or adding allowed annotation for the method.371
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.371
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setExcludedFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setExcludedFiles' static/final/abstract/empty, or adding allowed annotation for the method.375
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.375
 Error
miscFinalParametersParameter excludedFiles should be final.375
 Error
codingHiddenField'excludedFiles' hides a field.375
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'getIgnoredFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'getIgnoredFiles' static/final/abstract/empty, or adding allowed annotation for the method.379
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.379
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setIgnoredFiles' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setIgnoredFiles' static/final/abstract/empty, or adding allowed annotation for the method.383
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.383
 Error
miscFinalParametersParameter ignoredFiles should be final.383
 Error
codingHiddenField'ignoredFiles' hides a field.383
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'isAssertJsonSize' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'isAssertJsonSize' static/final/abstract/empty, or adding allowed annotation for the method.387
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.387
 Error
designDesignForExtensionClass 'GenerateTestsMojo' looks like designed for extension (can be subclassed), but the method 'setAssertJsonSize' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'GenerateTestsMojo' final or making the method 'setAssertJsonSize' static/final/abstract/empty, or adding allowed annotation for the method.391
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.391
 Error
miscFinalParametersParameter assertJsonSize should be final.391
 Error
codingHiddenField'assertJsonSize' hides a field.391
-

org/springframework/cloud/contract/maven/verifier/LeftOverPrevention.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).40
 Error
javadocJavadocVariableMissing a Javadoc comment.40
 Error
javadocJavadocVariableMissing a Javadoc comment.42
 Error
miscFinalParametersParameter generatedDirectory should be final.44
 Error
codingHiddenField'generatedDirectory' hides a field.44
 Error
miscFinalParametersParameter mojoExecution should be final.44
 Error
miscFinalParametersParameter session should be final.45
 Error
sizesLineLengthLine is longer than 80 characters (found 97).47
 Error
sizesLineLengthLine is longer than 80 characters (found 105).49
 Error
sizesLineLengthLine is longer than 80 characters (found 98).55
 Error
sizesLineLengthLine is longer than 80 characters (found 94).56
-

org/springframework/cloud/contract/maven/verifier/ManifestCreator.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).29
 Error
sizesLineLengthLine is longer than 80 characters (found 85).30
 Error
sizesLineLengthLine is longer than 80 characters (found 94).33
 Error
miscFinalParametersParameter project should be final.33
 Error
sizesLineLengthLine is longer than 80 characters (found 88).35
 Error
sizesLineLengthLine is longer than 80 characters (found 108).38
 Error
sizesLineLengthLine is longer than 80 characters (found 91).39
 Error
sizesLineLengthLine is longer than 80 characters (found 86).42
 Error
sizesLineLengthLine is longer than 80 characters (found 89).46
 Error
sizesLineLengthLine is longer than 80 characters (found 87).47
 Error
sizesLineLengthLine is longer than 80 characters (found 108).48
 Error
miscFinalParametersParameter plugins should be final.54
 Error
sizesLineLengthLine is longer than 80 characters (found 98).56
 Error
sizesLineLengthLine is longer than 80 characters (found 81).63
 Error
miscFinalParametersParameter deps should be final.63
 Error
sizesLineLengthLine is longer than 80 characters (found 91).65
-

org/springframework/cloud/contract/maven/verifier/MavenContractsDownloader.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).44
 Error
javadocJavadocVariableMissing a Javadoc comment.44
 Error
sizesLineLengthLine is longer than 80 characters (found 85).46
 Error
javadocJavadocVariableMissing a Javadoc comment.46
 Error
javadocJavadocVariableMissing a Javadoc comment.48
 Error
javadocJavadocVariableMissing a Javadoc comment.50
 Error
javadocJavadocVariableMissing a Javadoc comment.52
 Error
javadocJavadocVariableMissing a Javadoc comment.54
 Error
javadocJavadocVariableMissing a Javadoc comment.56
 Error
javadocJavadocVariableMissing a Javadoc comment.58
 Error
sizesLineLengthLine is longer than 80 characters (found 82).60
 Error
javadocJavadocVariableMissing a Javadoc comment.60
 Error
javadocJavadocVariableMissing a Javadoc comment.62
 Error
javadocJavadocVariableMissing a Javadoc comment.64
 Error
javadocJavadocVariableMissing a Javadoc comment.66
 Error
javadocJavadocVariableMissing a Javadoc comment.68
 Error
javadocJavadocVariableMissing a Javadoc comment.70
 Error
javadocJavadocVariableMissing a Javadoc comment.72
 Error
javadocJavadocVariableMissing a Javadoc comment.74
 Error
sizesLineLengthLine is longer than 80 characters (found 85).76
 Error
sizesParameterNumberMore than 7 parameters (found 13).76
 Error
miscFinalParametersParameter project should be final.76
 Error
codingHiddenField'project' hides a field.76
 Error
miscFinalParametersParameter contractDependency should be final.76
 Error
codingHiddenField'contractDependency' hides a field.76
 Error
miscFinalParametersParameter contractsPath should be final.77
 Error
codingHiddenField'contractsPath' hides a field.77
 Error
miscFinalParametersParameter contractsRepositoryUrl should be final.77
 Error
codingHiddenField'contractsRepositoryUrl' hides a field.77
 Error
sizesLineLengthLine is longer than 80 characters (found 101).78
 Error
miscFinalParametersParameter stubsMode should be final.78
 Error
codingHiddenField'stubsMode' hides a field.78
 Error
miscFinalParametersParameter log should be final.78
 Error
codingHiddenField'log' hides a field.78
 Error
miscFinalParametersParameter repositoryUsername should be final.78
 Error
codingHiddenField'repositoryUsername' hides a field.78
 Error
miscFinalParametersParameter repositoryPassword should be final.79
 Error
codingHiddenField'repositoryPassword' hides a field.79
 Error
miscFinalParametersParameter repositoryProxyHost should be final.79
 Error
codingHiddenField'repositoryProxyHost' hides a field.79
 Error
sizesLineLengthLine is longer than 80 characters (found 82).80
 Error
miscFinalParametersParameter repositoryProxyPort should be final.80
 Error
codingHiddenField'repositoryProxyPort' hides a field.80
 Error
miscFinalParametersParameter deleteStubsAfterTest should be final.80
 Error
codingHiddenField'deleteStubsAfterTest' hides a field.80
 Error
sizesLineLengthLine is longer than 80 characters (found 93).81
 Error
miscFinalParametersParameter contractsProperties should be final.81
 Error
codingHiddenField'contractsProperties' hides a field.81
 Error
miscFinalParametersParameter failOnNoContracts should be final.81
 Error
sizesLineLengthLine is longer than 80 characters (found 89).92
 Error
sizesLineLengthLine is longer than 80 characters (found 90).98
 Error
miscFinalParametersParameter config should be final.98
 Error
miscFinalParametersParameter defaultContractsDir should be final.99
 Error
sizesLineLengthLine is longer than 80 characters (found 87).102
 Error
sizesLineLengthLine is longer than 80 characters (found 88).105
 Error
sizesLineLengthLine is longer than 80 characters (found 108).107
 Error
sizesLineLengthLine is longer than 80 characters (found 88).108
 Error
sizesLineLengthLine is longer than 80 characters (found 111).109
 Error
sizesLineLengthLine is longer than 80 characters (found 94).110
 Error
sizesLineLengthLine is longer than 80 characters (found 96).111
 Error
sizesLineLengthLine is longer than 80 characters (found 95).113
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).115
 Error
sizesLineLengthLine is longer than 80 characters (found 124).118
 Error
sizesLineLengthLine is longer than 80 characters (found 91).119
 Error
sizesLineLengthLine is longer than 80 characters (found 109).122
 Error
sizesLineLengthLine is longer than 80 characters (found 91).123
 Error
sizesLineLengthLine is longer than 80 characters (found 96).124
 Error
sizesLineLengthLine is longer than 80 characters (found 95).126
 Error
sizesLineLengthLine is longer than 80 characters (found 90).127
 Error
sizesLineLengthLine is longer than 80 characters (found 97).131
 Error
sizesLineLengthLine is longer than 80 characters (found 95).138
 Error
sizesLineLengthLine is longer than 80 characters (found 84).139
 Error
sizesLineLengthLine is longer than 80 characters (found 84).143
 Error
sizesLineLengthLine is longer than 80 characters (found 89).145
 Error
sizesLineLengthLine is longer than 80 characters (found 81).150
 Error
sizesLineLengthLine is longer than 80 characters (found 81).154
 Error
sizesLineLengthLine is longer than 80 characters (found 81).155
 Error
sizesLineLengthLine is longer than 80 characters (found 100).156
 Error
sizesLineLengthLine is longer than 80 characters (found 84).158
 Error
sizesLineLengthLine is longer than 80 characters (found 84).162
 Error
sizesLineLengthLine is longer than 80 characters (found 94).165
 Error
sizesLineLengthLine is longer than 80 characters (found 90).173
 Error
sizesLineLengthLine is longer than 80 characters (found 88).174
 Error
sizesLineLengthLine is longer than 80 characters (found 87).176
-

org/springframework/cloud/contract/maven/verifier/PushStubsToScmMojo.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).43
 Error
javadocJavadocVariableMissing a Javadoc comment.43
 Error
javadocJavadocVariableMissing a Javadoc comment.47
 Error
sizesLineLengthLine is longer than 80 characters (found 92).54
 Error
sizesLineLengthLine is longer than 80 characters (found 89).60
 Error
javadocJavadocVariableMissing a Javadoc comment.64
 Error
sizesLineLengthLine is longer than 80 characters (found 84).80
 Error
sizesLineLengthLine is longer than 80 characters (found 88).81
 Error
sizesLineLengthLine is longer than 80 characters (found 94).94
 Error
sizesLineLengthLine is longer than 80 characters (found 87).102
 Error
designDesignForExtensionClass 'PushStubsToScmMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'PushStubsToScmMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.107
 Error
sizesLineLengthLine is longer than 80 characters (found 129).111
 Error
sizesLineLengthLine is longer than 80 characters (found 119).113
 Error
sizesLineLengthLine is longer than 80 characters (found 97).117
 Error
sizesLineLengthLine is longer than 80 characters (found 83).118
 Error
sizesLineLengthLine is longer than 80 characters (found 81).119
 Error
sizesLineLengthLine is longer than 80 characters (found 123).120
 Error
sizesLineLengthLine is longer than 80 characters (found 97).124
 Error
sizesLineLengthLine is longer than 80 characters (found 88).125
 Error
sizesLineLengthLine is longer than 80 characters (found 93).126
 Error
designDesignForExtensionClass 'PushStubsToScmMojo' looks like designed for extension (can be subclassed), but the method 'buildOptions' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'PushStubsToScmMojo' final or making the method 'buildOptions' static/final/abstract/empty, or adding allowed annotation for the method.130
 Error
sizesLineLengthLine is longer than 80 characters (found 81).131
 Error
sizesLineLengthLine is longer than 80 characters (found 81).132
 Error
sizesLineLengthLine is longer than 80 characters (found 84).133
 Error
sizesLineLengthLine is longer than 80 characters (found 84).137
-

org/springframework/cloud/contract/maven/verifier/RunMojo.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).49
 Error
javadocJavadocVariableMissing a Javadoc comment.52
 Error
javadocJavadocVariableMissing a Javadoc comment.54
 Error
javadocJavadocVariableMissing a Javadoc comment.56
 Error
javadocJavadocVariableMissing a Javadoc comment.59
 Error
javadocJavadocVariableMissing a Javadoc comment.62
 Error
sizesLineLengthLine is longer than 80 characters (found 92).75
 Error
sizesLineLengthLine is longer than 80 characters (found 84).86
 Error
sizesLineLengthLine is longer than 80 characters (found 89).106
 Error
sizesLineLengthLine is longer than 80 characters (found 84).108
 Error
javadocJavadocVariableMissing a Javadoc comment.118
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.127
 Error
sizesLineLengthLine is longer than 80 characters (found 92).128
 Error
miscFinalParametersParameter localStubRunner should be final.128
 Error
codingHiddenField'localStubRunner' hides a field.128
 Error
miscFinalParametersParameter remoteStubRunner should be final.128
 Error
codingHiddenField'remoteStubRunner' hides a field.128
 Error
designDesignForExtensionClass 'RunMojo' looks like designed for extension (can be subclassed), but the method 'execute' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'RunMojo' final or making the method 'execute' static/final/abstract/empty, or adding allowed annotation for the method.133
 Error
sizesLineLengthLine is longer than 80 characters (found 83).134
 Error
sizesLineLengthLine is longer than 80 characters (found 107).137
 Error
sizesLineLengthLine is longer than 80 characters (found 88).142
 Error
sizesLineLengthLine is longer than 80 characters (found 94).146
 Error
sizesLineLengthLine is longer than 80 characters (found 97).148
 Error
sizesLineLengthLine is longer than 80 characters (found 97).149
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).150
 Error
sizesLineLengthLine is longer than 80 characters (found 88).152
 Error
sizesLineLengthLine is longer than 80 characters (found 83).153
 Error
sizesLineLengthLine is longer than 80 characters (found 95).155
 Error
blocksRightCurly'}' at column 4 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).161
 Error
sizesLineLengthLine is longer than 80 characters (found 103).163
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).171
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).184
-

org/springframework/cloud/contract/maven/verifier/stubrunner/AetherStubDownloaderFactory.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
sizesLineLengthLine is longer than 80 characters (found 92).47
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).47
 Error
javadocJavadocVariableMissing a Javadoc comment.47
 Error
namingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.47
 Error
javadocJavadocVariableMissing a Javadoc comment.49
 Error
javadocJavadocVariableMissing a Javadoc comment.51
 Error
javadocJavadocVariableMissing a Javadoc comment.53
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.55
 Error
sizesLineLengthLine is longer than 80 characters (found 93).56
 Error
miscFinalParametersParameter repoSystem should be final.56
 Error
codingHiddenField'repoSystem' hides a field.56
 Error
miscFinalParametersParameter project should be final.56
 Error
codingHiddenField'project' hides a field.56
 Error
miscFinalParametersParameter settings should be final.57
 Error
codingHiddenField'settings' hides a field.57
 Error
sizesLineLengthLine is longer than 80 characters (found 87).63
 Error
designDesignForExtensionClass 'AetherStubDownloaderFactory' looks like designed for extension (can be subclassed), but the method 'build' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'AetherStubDownloaderFactory' final or making the method 'build' static/final/abstract/empty, or adding allowed annotation for the method.63
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.63
 Error
sizesLineLengthLine is longer than 80 characters (found 90).66
 Error
miscFinalParametersParameter stubRunnerOptions should be final.66
 Error
sizesLineLengthLine is longer than 80 characters (found 120).68
 Error
sizesLineLengthLine is longer than 80 characters (found 92).70
 Error
sizesLineLengthLine is longer than 80 characters (found 88).71
 Error
sizesLineLengthLine is longer than 80 characters (found 96).72
 Error
sizesLineLengthLine is longer than 80 characters (found 104).73
 Error
sizesLineLengthLine is longer than 80 characters (found 97).77
 Error
miscFinalParametersParameter location should be final.77
 Error
miscFinalParametersParameter resourceLoader should be final.77
-

org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).36
 Error
javadocJavadocVariableMissing a Javadoc comment.36
 Error
namingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.36
 Error
sizesLineLengthLine is longer than 80 characters (found 85).38
 Error
designDesignForExtensionClass 'LocalStubRunner' looks like designed for extension (can be subclassed), but the method 'run' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'LocalStubRunner' final or making the method 'run' static/final/abstract/empty, or adding allowed annotation for the method.38
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.38
 Error
miscFinalParametersParameter options should be final.38
 Error
sizesLineLengthLine is longer than 80 characters (found 85).39
-

org/springframework/cloud/contract/maven/verifier/stubrunner/RemoteStubRunner.java

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityCategoryRuleMessageLine
 Error
javadocJavadocPackageMissing package-info.java file.1
 Error
sizesLineLengthLine is longer than 80 characters (found 81).40
 Error
whitespaceFileTabCharacterFile contains tab characters (this is the first instance).40
 Error
javadocJavadocVariableMissing a Javadoc comment.40
 Error
namingConstantNameName 'log' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.40
 Error
javadocJavadocVariableMissing a Javadoc comment.42
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.44
 Error
sizesLineLengthLine is longer than 80 characters (found 90).45
 Error
miscFinalParametersParameter aetherStubDownloaderFactory should be final.45
 Error
codingHiddenField'aetherStubDownloaderFactory' hides a field.45
 Error
designDesignForExtensionClass 'RemoteStubRunner' looks like designed for extension (can be subclassed), but the method 'run' does not have javadoc that explains how to do that safely. If class is not designed for extension consider making the class 'RemoteStubRunner' final or making the method 'run' static/final/abstract/empty, or adding allowed annotation for the method.49
 Error
javadocMissingJavadocMethodMissing a Javadoc comment.49
 Error
miscFinalParametersParameter options should be final.49
 Error
miscFinalParametersParameter repositorySystemSession should be final.50
 Error
sizesLineLengthLine is longer than 80 characters (found 88).55
 Error
sizesLineLengthLine is longer than 80 characters (found 88).57
 Error
sizesLineLengthLine is longer than 80 characters (found 82).59
 Error
blocksRightCurly'}' at column 3 should be on the same line as the next part of a multi-block statement (one that directly contains multiple blocks: if/else-if/else, do/while or try/catch/finally).62
 Error
sizesLineLengthLine is longer than 80 characters (found 93).64
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/ci-management.html b/spring-cloud-contract-maven-plugin/ci-management.html index 422bc9e869..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/ci-management.html +++ b/spring-cloud-contract-maven-plugin/ci-management.html @@ -1,351 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – CI Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses Continuous Integration System.

-

Access

-

The following is a link to the continuous integration system used by the project:

-
-

Notifiers

-

No notifiers are defined. Please check back at a later date.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/complex-content.html b/spring-cloud-contract-maven-plugin/complex-content.html index 184f17b583..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/complex-content.html +++ b/spring-cloud-contract-maven-plugin/complex-content.html @@ -1,331 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

More Complex Plugin Configuration

-
-
-

Sample more complex configuration for Java Project with JUnit tests.

-
-
-

Project configuration for Spring Cloud Contract Verifier with JUnit tests and stub publishing

-
-
-
Unresolved directive in <stdin> - include::{root_folder}/src/test/projects/complex-configuration/pom.xml[tags=plugin]
-
-
-
-
-

Base Test class

-
-
-
Unresolved directive in <stdin> - include::{root_folder}/src/test/projects/complex-configuration/src/test/java/com/blogspot/toomuchcoding/frauddetection/BaseAccurest.java[]
-
-
-
-
-

Sample additional matcher

-
-
-
Unresolved directive in <stdin> - include::{root_folder}/src/test/projects/complex-configuration/src/test/java/com/blogspot/toomuchcoding/frauddetection/matchers/CustomMatchers.java[]
-
-
-
-
-

Sample contract using matcher

-
-
-
Unresolved directive in <stdin> - include::{root_folder}/src/test/projects/complex-configuration/src/test/contracts/shouldMarkClientAsNotFraud.groovy[]
-
-
-
- -
-

More samples

-
-

You can check out the Spring Cloud Contract Samples project for -more examples of Maven plugin setup.

-
-
-
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/complex.html b/spring-cloud-contract-maven-plugin/complex.html index 23e6bbf124..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/complex.html +++ b/spring-cloud-contract-maven-plugin/complex.html @@ -1,471 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

More Complex Plugin Configuration

-
-
-

Sample more complex configuration for Java Project with JUnit tests.

-
-
-

Project configuration for Spring Cloud Contract Verifier with JUnit tests and stub publishing

-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <version>${spring-cloud-verifier-plugin.version}</version>
-                                <executions>
-                                        <execution>
-                                                <goals>
-                                                        <goal>convert</goal>
-                                                        <goal>generateStubs</goal>
-                                                        <goal>generateTests</goal>
-                                                </goals>
-                                                <configuration>
-                                                        <contractsDirectory>src/test/contracts</contractsDirectory>
-                                                        <basePackageForTests>
-                                                                com.blogspot.toomuchcoding.frauddetection
-                                                        </basePackageForTests>
-                                                        <testMode>MOCKMVC</testMode>
-                                                        <testFramework>JUNIT</testFramework>
-                                                        <classifier>stubs</classifier>
-                                                        <nameSuffixForTests>Test</nameSuffixForTests>
-                                                        <ruleClassForTests>org.junit.rules.ErrorCollector
-                                                        </ruleClassForTests>
-                                                        <staticImports>
-                                                                <staticImport>
-                                                                        com.blogspot.toomuchcoding.frauddetection.matchers.CustomMatchers.*
-                                                                </staticImport>
-                                                        </staticImports>
-                                                        <imports>
-                                                                <import>
-                                                                        com.blogspot.toomuchcoding.frauddetection.matchers.CustomMatchers
-                                                                </import>
-                                                        </imports>
-                                                        <ignoredFiles>
-                                                                <ignoredFile>broken**</ignoredFile>
-                                                        </ignoredFiles>
-                                                        <excludedFiles>
-                                                                <param>shouldMarkClientAsFraud.groovy</param>
-                                                        </excludedFiles>
-                                                </configuration>
-                                        </execution>
-                                </executions>
-                                <configuration>
-                                        <baseClassForTests>
-                                                com.blogspot.toomuchcoding.frauddetection.BaseAccurest
-                                        </baseClassForTests>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Base Test class

-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */package com.blogspot.toomuchcoding.frauddetection;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-
-public class BaseAccurest {
-
-        @Before
-        public void setup() {
-                RestAssuredMockMvc.standaloneSetup(new FraudDetectionController());
-        }
-
-}
-
-
-
-
-

Sample additional matcher

-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */package com.blogspot.toomuchcoding.frauddetection.matchers;
-
-import org.junit.Assert;
-
-public class CustomMatchers {
-
-        public static void assertThatRejectionReasonIsNull(String rejectionReason) {
-                Assert.assertNull(rejectionReason);
-        }
-
-}
-
-
-
-
-

Sample contract using matcher

-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */ org.springframework.cloud.contract.spec.Contract.make {
-        request {
-                method 'PUT'
-                url '/fraudcheck'
-                body("""
-                                                {
-                                                "clientPesel":"${
-                        value(consumer(regex('[0-9]{10}')), producer('1234567890'))
-                }",
-                                                "loanAmount":123.123
-                                                }
-                                        """
-                )
-                headers {
-                        header('Content-Type', 'application/vnd.fraud.v1+json')
-                }
-
-        }
-        response {
-                status OK()
-                body(
-                                fraudCheckStatus: "OK",
-                                rejectionReason: $(consumer(null),
-                                                producer(execute('assertThatRejectionReasonIsNull($it)')))
-                )
-                headers {
-                        header('Content-Type': 'application/vnd.fraud.v1+json')
-                }
-        }
-
-}
-
-
-
- -
-

More samples

-
-

You can check out the Spring Cloud Contract Samples project for -more examples of Maven plugin setup.

-
-
-
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/configs.html b/spring-cloud-contract-maven-plugin/configs.html index f30e5588b2..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/configs.html +++ b/spring-cloud-contract-maven-plugin/configs.html @@ -1,366 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Configuration snippets

-
-
-

Here you’ll be able to see different Spring Cloud Contract Maven plugin configuration

-
-
-

Base class from mappings

-
-

Define regular expression mappings to map a contract to its base class.

-
-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <configuration>
-                                        <baseClassForTests>com.example.FooBase</baseClassForTests>
-                                        <baseClassMappings>
-                                                <baseClassMapping>
-                                                        <contractPackageRegex>.*com.*</contractPackageRegex>
-                                                        <baseClassFQN>com.example.TestBase</baseClassFQN>
-                                                </baseClassMapping>
-                                        </baseClassMappings>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Convention based mappings

-
-

Define a package in which base classes are placed. In this case we define -a package called hello. If there’s a contract under /contracts/hello/V1/Contract.groovy` then -we’ll search for a HelloV1Base base class. We’re taking two last folders -from the path and combine them into a class name.

-
-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <configuration>
-                                        <packageWithBaseClasses>hello</packageWithBaseClasses>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Remote contracts

-
-

Here you can see a setup where we point to a repository where the JAR with the -contracts got deployed.

-
-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <configuration>
-                                        <contractsMode>REMOTE</contractsMode>
-                                        <contractsRepositoryUrl>
-                                                https://link/to/your/nexus/or/artifactory/or/sth
-                                        </contractsRepositoryUrl>
-                                        <contractDependency>
-                                                <groupId>com.example.standalone</groupId>
-                                                <artifactId>contracts</artifactId>
-                                        </contractDependency>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Setting up repo with common contracts

-
-

A setup of a repo that contains all common contracts. It can exclude the target / build -folder that gets created when you’re installing stubs locally as a consumer.

-
-
-
-
-
-
-
-
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/convert-mojo.html b/spring-cloud-contract-maven-plugin/convert-mojo.html index 8dd2b62b5f..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/convert-mojo.html +++ b/spring-cloud-contract-maven-plugin/convert-mojo.html @@ -1,854 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:convert - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:convert

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:convert

- -

Description:

- -
Convert Spring Cloud Contract Verifier contracts into stubs -mappings. - -

This goal allows you to generate `stubs-jar` or execute -`spring-cloud-contract:run` with generated mappings.

- -

Attributes:

- - -
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<contractDependency>Dependency-(no description)
User property is: contractDependency.
<contractsDirectory>File-Directory containing Spring Cloud Contract Verifier contracts -written using the GroovyDSL.
Default value is: ${project.basedir}/src/test/resources/contracts.
User property is: spring.cloud.contract.verifier.contractsDirectory.
<contractsMode>StubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
<contractsPath>String-The path in the JAR with all the contracts where contracts for this -particular service lay. If not provided will be resolved to -groupid/artifactid. Example: If groupid -is com.example and artifactid is -service then the resolved path will be -/com/example/artifactid
User property is: contractsPath.
<contractsProperties>Map-Map of properties that can be passed to custom -StubDownloaderBuilder.
User property is: contractsProperties.
<contractsRepositoryPassword>String-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
<contractsRepositoryProxyHost>String-The proxy host to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyHost.
<contractsRepositoryProxyPort>Integer-The proxy port to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyPort.
<contractsRepositoryUrl>String-The URL from which a JAR containing the contracts should get -downloaded. If not provided but artifactid / coordinates notation -was provided then the current Maven's build repositories will be -taken into consideration
User property is: contractsRepositoryUrl.
<contractsRepositoryUsername>String-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
<contractsSnapshotCheckSkip>boolean-Deprecated. - with 2.1.0 this option is redundant
Default value is: false.
User property is: contractsSnapshotCheckSkip.
<convertToYaml>boolean-If true then will convert contracts to a YAML -representation.
Default value is: false.
User property is: convertToYaml.
<deleteStubsAfterTest>boolean-If set to false will NOT delete stubs from a temporary -folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
<destination>File-(no description)
Default value is: ${basedir}.
User property is: stubsDirectory.
<excludeBuildFolders>boolean-If true then any file laying in a path that contains -build or target will get excluded in -further processing.
Default value is: false.
User property is: excludeBuildFolders.
<failOnNoContracts>boolean-When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
Default value is: true.
User property is: failOnNoContracts.
<incrementalContractStubs>boolean-If set to true then stubs are created only when contracts have -changed since last build.
Default value is: true.
User property is: incrementalContractStubs.
<skip>boolean-(no description)
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
<source>File-Directory containing contracts written using the GroovyDSL - -

This parameter is only used when goal is executed outside of -maven project.


Default value is: ${basedir}.
User property is: contractsDirectory.
<stubsDirectory>File-Directory where the generated WireMock stubs from Groovy DSL should -be placed. You can then mention them in your packaging task to -create jar with stubs
Default value is: ${project.build.directory}/stubs/.
-
-
-

Parameter Details

-
-

<contractDependency>

- -
(no description)
- -
    - -
  • Type: org.apache.maven.model.Dependency
  • - -
  • Required: No
  • - -
  • User Property: contractDependency
  • -

-

<contractsDirectory>

- -
Directory containing Spring Cloud Contract Verifier contracts -written using the GroovyDSL.
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.contractsDirectory
  • - -
  • Default: ${project.basedir}/src/test/resources/contracts
  • -

-

<contractsMode>

- -
Picks the mode in which stubs will be found and registered.
- -
    - -
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • - -
  • Required: No
  • - -
  • User Property: contractsMode
  • - -
  • Default: CLASSPATH
  • -

-

<contractsPath>

- -
The path in the JAR with all the contracts where contracts for this -particular service lay. If not provided will be resolved to -groupid/artifactid. Example: If groupid -is com.example and artifactid is -service then the resolved path will be -/com/example/artifactid
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsPath
  • -

-

<contractsProperties>

- -
Map of properties that can be passed to custom -StubDownloaderBuilder.
- -
    - -
  • Type: java.util.Map
  • - -
  • Required: No
  • - -
  • User Property: contractsProperties
  • -

-

<contractsRepositoryPassword>

- -
The password to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryPassword
  • -

-

<contractsRepositoryProxyHost>

- -
The proxy host to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryProxyHost
  • -

-

<contractsRepositoryProxyPort>

- -
The proxy port to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.Integer
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryProxyPort
  • -

-

<contractsRepositoryUrl>

- -
The URL from which a JAR containing the contracts should get -downloaded. If not provided but artifactid / coordinates notation -was provided then the current Maven's build repositories will be -taken into consideration
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUrl
  • -

-

<contractsRepositoryUsername>

- -
The user name to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUsername
  • -

-

<contractsSnapshotCheckSkip>

- -
Deprecated. - with 2.1.0 this option is redundant
- -
If true then will not assert whether a stub / contract -JAR was downloaded from local or remote location.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: contractsSnapshotCheckSkip
  • - -
  • Default: false
  • -

-

<convertToYaml>

- -
If true then will convert contracts to a YAML -representation.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: convertToYaml
  • - -
  • Default: false
  • -

-

<deleteStubsAfterTest>

- -
If set to false will NOT delete stubs from a temporary -folder after running tests.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: deleteStubsAfterTest
  • - -
  • Default: true
  • -

-

<destination>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: stubsDirectory
  • - -
  • Default: ${basedir}
  • -

-

<excludeBuildFolders>

- -
If true then any file laying in a path that contains -build or target will get excluded in -further processing.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: excludeBuildFolders
  • - -
  • Default: false
  • -

-

<failOnNoContracts>

- -
When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: failOnNoContracts
  • - -
  • Default: true
  • -

-

<incrementalContractStubs>

- -
If set to true then stubs are created only when contracts have -changed since last build.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: incrementalContractStubs
  • - -
  • Default: true
  • -

-

<skip>

- -
(no description)
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skip
  • - -
  • Default: false
  • -

-

<source>

- -
Directory containing contracts written using the GroovyDSL - -

This parameter is only used when goal is executed outside of -maven project.

- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: contractsDirectory
  • - -
  • Default: ${basedir}
  • -

-

<stubsDirectory>

- -
Directory where the generated WireMock stubs from Groovy DSL should -be placed. You can then mention them in your packaging task to -create jar with stubs
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • Default: ${project.build.directory}/stubs/
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/dependencies.html b/spring-cloud-contract-maven-plugin/dependencies.html index 5be7517425..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/dependencies.html +++ b/spring-cloud-contract-maven-plugin/dependencies.html @@ -1,2733 +1,12 @@ - - - - - - - - - Spring Cloud Contract Verifier Maven Plugin – Project Dependencies - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - - - - - -
- - - - - -
-
- -
- - -
- - -
-

Project Dependencies

-
-

compile

-

The following is a list of compile dependencies for this project. These dependencies are required to compile and run the application:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicenses
ch.qos.logbacklogback-core1.1.7jarEclipse Public License - v 1.0-GNU Lesser General Public License
org.apache.mavenmaven-archiver3.0.0jarApache License, Version 2.0
org.apache.maven.sharedmaven-filtering3.1.0jarApache License, Version 2.0
org.codehaus.plexusplexus-archiver3.1jarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-contract-converters1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-verifier1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
-
-

test

-

The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicenses
io.takari.maven.pluginstakari-plugin-integration-testing2.9.0pomThe Eclipse Public License, Version 1.0
io.takari.maven.pluginstakari-plugin-testing2.9.0jarThe Eclipse Public License, Version 1.0
junitjunit4.12jarEclipse Public License 1.0
org.apache.mavenmaven-compat3.2.5jarApache License, Version 2.0
org.assertjassertj-core2.4.1jarApache License, Version 2.0
org.slf4jslf4j-simple1.7.21jarMIT License
-
-

provided

-

The following is a list of provided dependencies for this project. These dependencies are required to compile the application, but should be provided by default when using the library:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicenses
javax.injectjavax.inject1jarThe Apache Software License, Version 2.0
org.apache.mavenmaven-core3.2.5jarApache License, Version 2.0
org.apache.mavenmaven-plugin-api3.2.5jarApache License, Version 2.0
org.apache.maven.plugin-toolsmaven-plugin-annotations3.4jarApache License, Version 2.0
org.eclipse.aetheraether-api1.1.0jarEclipse Public License, Version 1.0
-
-

Project Transitive Dependencies

-

The following is a list of transitive dependencies for this project. Transitive dependencies are the dependencies of the project dependencies.

-
-

compile

-

The following is a list of compile dependencies for this project. These dependencies are required to compile and run the application:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicenses
args4jargs4j2.32jarMIT License
com.fasterxml.jackson.corejackson-annotations2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.corejackson-core2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.corejackson-databind2.8.0jarThe Apache Software License, Version 2.0
com.flipkart.zjsonpatchzjsonpatch0.2.1jarThe Apache Software License, Version 2.0
com.github.tomakehurstwiremock2.1.7jarThe Apache Software License, Version 2.0
com.google.code.findbugsjsr3052.0.1jarThe Apache Software License, Version 2.0
com.google.guavaguava18.0jarThe Apache Software License, Version 2.0
com.jayway.jsonpathjson-path2.2.0jarThe Apache Software License, Version 2.0
com.toomuchcoding.jsonassertjsonassert0.4.7jarThe Apache License, Version 2.0
commons-codeccommons-codec1.10jarApache License, Version 2.0
commons-iocommons-io2.4jarThe Apache Software License, Version 2.0
dk.brics.automatonautomaton1.11-8jarBSD
net.minidevhttp://accessors-smart/1.1jarThe Apache Software License, Version 2.0
net.minidevjson-smart2.2.1jarThe Apache Software License, Version 2.0
org.apache.commonscommons-collections44.0jarThe Apache Software License, Version 2.0
org.apache.commonscommons-compress1.10jarApache License, Version 2.0
org.apache.commonscommons-lang33.4jarApache License, Version 2.0
org.apache.httpcomponentshttpclient4.5.2jarApache License, Version 2.0
org.apache.httpcomponentshttpcore4.4.5jarApache License, Version 2.0
org.apache.mavenmaven-aether-provider3.3.9jarApache License, Version 2.0
org.apache.mavenmaven-artifact3.2.5jarApache License, Version 2.0
org.apache.mavenmaven-model3.2.5jarApache License, Version 2.0
org.apache.mavenmaven-model-builder3.2.5jarApache License, Version 2.0
org.apache.mavenmaven-repository-metadata3.2.5jarApache License, Version 2.0
org.apache.maven.sharedmaven-shared-utils3.0.0jarApache License, Version 2.0
org.codehaus.groovygroovy2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-json2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-nio2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-xml2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.plexusplexus-component-annotations1.5.5jarThe Apache Software License, Version 2.0
org.codehaus.plexusplexus-interpolation1.21jarThe Apache Software License, Version 2.0
org.codehaus.plexusplexus-io2.7.1jarThe Apache Software License, Version 2.0
org.codehaus.plexusplexus-utils3.0.22jarThe Apache Software License, Version 2.0
org.eclipse.aetheraether-connector-basic1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-impl1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-spi1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-transport-file1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-transport-http1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-util1.0.0.v20140518jarEclipse Public License, Version 1.0
org.iq80.snappysnappy0.4jarApache License 2.0
org.jsonjson20140107jarThe JSON License
org.ow2.asmasm5.0.3jarBSD
org.skyscreamerjsonassert1.2.3jarThe Apache Software License, Version 2.0
org.slf4jjcl-over-slf4j1.7.21jarMIT License
org.slf4jslf4j-api1.7.21jarMIT License
org.sonatype.plexusplexus-build-api0.0.7jarApache Public License 2.0
org.springframeworkspring-aop4.3.2.BUILD-20160721.124751-21jarThe Apache Software License, Version 2.0
org.springframeworkspring-beans4.3.2.BUILD-20160721.124751-21jarThe Apache Software License, Version 2.0
org.springframeworkspring-context4.3.2.BUILD-20160721.124751-21jarThe Apache Software License, Version 2.0
org.springframeworkspring-core4.3.1.BUILD-20160702.134746-59jarThe Apache Software License, Version 2.0
org.springframeworkspring-expression4.3.2.BUILD-20160721.124751-21jarThe Apache Software License, Version 2.0
org.springframework.bootspring-boot1.4.0.BUILD-20160721.162741-570jarApache License, Version 2.0
org.springframework.bootspring-boot-autoconfigure1.4.0.BUILD-20160721.162741-571jarApache License, Version 2.0
org.springframework.bootspring-boot-test1.4.0.BUILD-20160721.162741-507jarApache License, Version 2.0
org.springframework.bootspring-boot-test-autoconfigure1.4.0.BUILD-20160721.162741-414jarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-spec1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.xmlunitxmlunit-core2.1.1jarThe Apache Software License, Version 2.0
org.xmlunitxmlunit-legacy2.1.1jarThe BSD 3-Clause License
-
-

test

-

The following is a list of test dependencies for this project. These dependencies are only required to compile and run unit tests for the application:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicenses
io.takari.m2e.workspaceorg.eclipse.m2e.workspace.cli0.4.0jarEclipse Public License - v 1.0
org.apache.commonscommons-exec1.2jarThe Apache Software License, Version 2.0
org.apache.maven.wagonwagon-provider-api2.8jarApache License, Version 2.0
org.hamcresthamcrest-core1.3jarNew BSD License
-
-

provided

-

The following is a list of provided dependencies for this project. These dependencies are required to compile the application, but should be provided by default when using the library:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionClassifierTypeLicenses
aopallianceaopalliance1.0-jarPublic Domain
javax.annotationjsr250-api1.0-jarCOMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
javax.enterprisecdi-api1.0-jarApache License, Version 2.0
org.apache.mavenmaven-settings3.2.5-jarApache License, Version 2.0
org.apache.mavenmaven-settings-builder3.2.5-jarApache License, Version 2.0
org.codehaus.plexusplexus-classworlds2.5.2-jarThe Apache Software License, Version 2.0
org.eclipse.sisuorg.eclipse.sisu.inject0.3.0.M1-jarEclipse Public License, Version 1.0
org.eclipse.sisuorg.eclipse.sisu.plexus0.3.0.M1-jarEclipse Public License, Version 1.0
org.sonatype.plexusplexus-cipher1.4-jarApache Public License 2.0
org.sonatype.plexusplexus-sec-dispatcher1.3-jarApache Public License 2.0
org.sonatype.sisusisu-guice3.2.3no_aopjarThe Apache Software License, Version 2.0
-
-

Project Dependency Graph

- - -
-

Dependency Tree

-
-
-

Licenses

-

Apache Public License 2.0: Plexus Cipher: encryption/decryption Component, Plexus Security Dispatcher Component, plexus-build-api

-

The Apache License, Version 2.0: jsonassert

-

Eclipse Public License 1.0: JUnit

-

The Eclipse Public License, Version 1.0: takari-plugin-integration-testing, takari-plugin-testing

-

MIT License: JCL 1.1.1 implemented over SLF4J, SLF4J API Module, SLF4J Simple Binding, args4j

-

The JSON License: JSON in Java

-

Public Domain: AOP alliance

-

GNU Lesser General Public License: Logback Core Module

-

New BSD License: Hamcrest Core

-

Eclipse Public License, Version 1.0: Aether API, Aether Connector Basic, Aether Implementation, Aether SPI, Aether Transport File, Aether Transport HTTP, Aether Utilities, org.eclipse.sisu.inject, org.eclipse.sisu.plexus

-

BSD: ASM Core, Automaton

-

The BSD 3-Clause License: org.xmlunit:xmlunit-legacy

-

Apache License 2.0: snappy

-

Apache License, Version 2.0: Apache Commons Codec, Apache Commons Compress, Apache Commons Lang, Apache HttpClient, Apache HttpCore, Apache Maven Archiver, Apache Maven Filtering, Apache Maven Shared Utils, Apache Maven Wagon :: API, AssertJ fluent assertions, CDI APIs, Maven Aether Provider, Maven Artifact, Maven Compat, Maven Core, Maven Model, Maven Model Builder, Maven Plugin API, Maven Plugin Tools Java 5 Annotations, Maven Repository Metadata Model, Maven Settings, Maven Settings Builder, Spring Boot, Spring Boot AutoConfigure, Spring Boot Test, Spring Boot Test Auto-Configure, Spring Cloud Contract Converters, Spring Cloud Contract Maven Plugin, Spring Cloud Contract Spec, Spring Cloud Contract Stub Runner, Spring Cloud Contract Verifier

-

COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0: JSR-250 Common Annotations for the JavaTM Platform

-

The Apache Software License, Version 2.0: ASM based accessors helper used by json-smart, Apache Commons Collections, Apache Commons Exec, Apache Groovy, Commons IO, FindBugs-jsr305, Guava: Google Core Libraries for Java, JSON Small and Fast Parser, JSONassert, Jackson-annotations, Jackson-core, Json Path, Plexus :: Component Annotations, Plexus Archiver Component, Plexus Classworlds, Plexus Common Utilities, Plexus IO Components, Plexus Interpolation API, Sisu Guice - Core Library, Spring AOP, Spring Beans, Spring Context, Spring Core, Spring Expression Language (SpEL), WireMock, jackson-databind, javax.inject, org.xmlunit:xmlunit-core, zjsonpatch

-

Eclipse Public License - v 1.0: Logback Core Module, m2e-workspace

-
-

Dependency File Details

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FilenameSizeEntriesClassesPackagesJava VersionDebug Information
aopalliance-1.0.jar4.5 kB15921.3Yes
args4j-2.32.jar153.9 kB1637221.5Yes
logback-core-1.1.7.jar470.8 kB418372361.6Yes
jackson-annotations-2.8.0.jar55.8 kB746211.6Yes
jackson-core-2.8.0.jar280 kB1179491.6Yes
jackson-databind-2.8.0.jar1.2 MB615581201.7Yes
zjsonpatch-0.2.1.jar18.7 kB201011.6Yes
wiremock-2.1.7.jar323.6 kB292271151.7Yes
jsr305-2.0.1.jar31.9 kB703431.5Yes
guava-18.0.jar2.3 MB17191690171.6Yes
json-path-2.2.0.jar207.1 kB176160111.6Yes
jsonassert-0.4.7.jar13.2 kB171211.7Yes
commons-codec-1.10.jar284.2 kB2389261.6Yes
commons-io-2.4.jar185.1 kB12811061.6Yes
automaton-1.11-8.jar176.3 kB2062511.5No
org.eclipse.m2e.workspace.cli-0.4.0.jar17.9 kB25521.7Yes
takari-plugin-integration-testing-2.9.0.pom1.6 kB-----
takari-plugin-testing-2.9.0.jar80.8 kB554131.7Yes
jsr250-api-1.0.jar5.8 kB161121.5Yes
cdi-api-1.0.jar44.9 kB927571.5Yes
javax.inject-1.jar2.5 kB8611.5No
junit-4.12.jar314.9 kB323286301.5Yes
accessors-smart-1.1.jar80.7 kB533841.6Yes
json-smart-2.2.1.jar120.5 kB1079351.6Yes
commons-collections4-4.0.jar610.3 kB459431161.5Yes
commons-compress-1.10.jar409.5 kB256221231.5Yes
commons-exec-1.2.jar53.9 kB523641.3Yes
commons-lang3-3.4.jar434.7 kB248224121.6Yes
httpclient-4.5.2.jar736.7 kB504463241.6Yes
httpcore-4.4.5.jar327.4 kB283253171.6Yes
maven-aether-provider-3.3.9.jar66.9 kB432611.7Yes
maven-archiver-3.0.0.jar22.5 kB19511.6Yes
maven-artifact-3.2.5.jar55.1 kB5732111.6Yes
maven-compat-3.2.5.jar286.7 kB211159291.6Yes
maven-core-3.2.5.jar608.2 kB463372511.6Yes
maven-model-3.2.5.jar160.8 kB675031.6Yes
maven-model-builder-3.2.5.jar170.2 kB148115161.6Yes
maven-plugin-api-3.2.5.jar46.1 kB462561.6Yes
maven-repository-metadata-3.2.5.jar26 kB25721.6Yes
maven-settings-3.2.5.jar43 kB331721.6Yes
maven-settings-builder-3.2.5.jar43.7 kB533251.6Yes
maven-plugin-annotations-3.4.jar14.2 kB22711.5Yes
maven-filtering-3.1.0.jar50.7 kB392211.6Yes
maven-shared-utils-3.0.0.jar154.7 kB1017791.6Yes
wagon-provider-api-2.8.jar52.6 kB603981.5Yes
assertj-core-2.4.1.jar900.7 kB730692271.7Yes
groovy-2.4.7.jar4.6 MB32573123851.6Yes
groovy-json-2.4.7.jar128 kB706221.6Yes
groovy-nio-2.4.7.jar19.3 kB13211.7Yes
groovy-xml-2.4.7.jar215.5 kB14412571.6Yes
plexus-archiver-3.1.jar178.2 kB152121161.6Yes
plexus-classworlds-2.5.2.jar52.7 kB523751.6Yes
plexus-component-annotations-1.5.5.jar4.2 kB15311.5No
plexus-interpolation-1.21.jar62.5 kB604461.5Yes
plexus-io-2.7.1.jar85.8 kB927171.5Yes
plexus-utils-3.0.22.jar244.9 kB12910491.5Yes
aether-api-1.1.0.jar136.4 kB149128111.5Yes
aether-connector-basic-1.1.0.jar36.7 kB341911.5Yes
aether-impl-1.1.0.jar172.8 kB1149641.5Yes
aether-spi-1.1.0.jar30.7 kB543481.5Yes
aether-transport-file-1.1.0.jar8.9 kB19411.5Yes
aether-transport-http-1.1.0.jar36.7 kB352011.5Yes
aether-util-1.0.0.v20140518.jar145.8 kB125100131.5Yes
org.eclipse.sisu.inject-0.3.0.M1.jar340.2 kB27325681.5Yes
org.eclipse.sisu.plexus-0.3.0.M1.jar200.6 kB197165201.5Yes
hamcrest-core-1.3.jar45 kB524531.5Yes
snappy-0.4.jar58 kB342411.6Yes
json-20140107.jar65 kB443421.2Yes
asm-5.0.3.jar53.2 kB302521.2No
jsonassert-1.2.3.jar27.7 kB301921.6Yes
jcl-over-slf4j-1.7.21.jar16.4 kB23921.5Yes
slf4j-api-1.7.21.jar41.1 kB463441.5Yes
slf4j-simple-1.7.21.jar10.9 kB16611.5Yes
plexus-build-api-0.0.7.jar8.5 kB19411.4Yes
plexus-cipher-1.4.jar13.5 kB20611.4Yes
plexus-sec-dispatcher-1.3.jar28.6 kB311331.4Yes
sisu-guice-3.2.3-no_aop.jar397.8 kB32931481.6Yes
spring-aop-4.3.2.BUILD-SNAPSHOT.jar379.8 kB306269171.6Yes
spring-beans-4.3.2.BUILD-SNAPSHOT.jar756.8 kB460405151.6Yes
spring-context-4.3.2.BUILD-SNAPSHOT.jar1.1 MB889767661.6Yes
spring-core-4.3.1.BUILD-SNAPSHOT.jar1.1 MB831784401.6Yes
spring-expression-4.3.2.BUILD-SNAPSHOT.jar263.7 kB15614261.6Yes
spring-boot-1.4.0.BUILD-SNAPSHOT.jar635.9 kB517442411.6Yes
spring-boot-autoconfigure-1.4.0.BUILD-SNAPSHOT.jar930.8 kB848759731.6Yes
spring-boot-test-1.4.0.BUILD-SNAPSHOT.jar140.2 kB126102111.6Yes
spring-boot-test-autoconfigure-1.4.0.BUILD-SNAPSHOT.jar90.2 kB997691.6Yes
spring-cloud-contract-converters-1.0.0.BUILD-SNAPSHOT.jar37.7 kB331921.8Yes
spring-cloud-contract-spec-1.0.0.BUILD-SNAPSHOT.jar113.8 kB715341.7Yes
spring-cloud-contract-stub-runner-1.0.0.BUILD-SNAPSHOT.jar112.1 kB10177101.7Yes
spring-cloud-contract-verifier-1.0.0.BUILD-SNAPSHOT.jar314 kB176149141.7Yes
xmlunit-core-2.1.1.jar153.7 kB16014481.6Yes
xmlunit-legacy-2.1.1.jar124.8 kB1008651.6Yes
TotalSizeEntriesClassesPackagesJava VersionDebug Information
9225.3 MB193971677510111.887
compile: 66compile: 21.6 MBcompile: 16074compile: 13993compile: 771-compile: 63
test: 10test: 1.8 MBtest: 1524test: 1309test: 107-test: 9
provided: 16provided: 2 MBprovided: 1799provided: 1473provided: 133-provided: 15
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/dependency-info.html b/spring-cloud-contract-maven-plugin/dependency-info.html index dd99f66291..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/dependency-info.html +++ b/spring-cloud-contract-maven-plugin/dependency-info.html @@ -1,397 +1,12 @@ - - - - - - - - - Spring Cloud Contract Verifier Maven Plugin – Dependency Information - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Dependency Information

-
-

Apache Maven

-
<dependency>
-  <groupId>org.springframework.cloud</groupId>
-  <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-  <version>1.0.0.BUILD-SNAPSHOT</version>
-  <type>maven-plugin</type>
-</dependency>
-
-

Apache Buildr

-
'org.springframework.cloud:spring-cloud-contract-maven-plugin:maven-plugin:1.0.0.BUILD-SNAPSHOT'
-
-

Apache Ivy

-
<dependency org="org.springframework.cloud" name="spring-cloud-contract-maven-plugin" rev="1.0.0.BUILD-SNAPSHOT">
-  <artifact name="spring-cloud-contract-maven-plugin" type="maven-plugin" />
-</dependency>
-
-

Groovy Grape

-
@Grapes(
-@Grab(group='org.springframework.cloud', module='spring-cloud-contract-maven-plugin', version='1.0.0.BUILD-SNAPSHOT')
-)
-
-

Gradle/Grails

-
compile 'org.springframework.cloud:spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT'
-
-

Scala SBT

-
libraryDependencies += "org.springframework.cloud" % "spring-cloud-contract-maven-plugin" % "1.0.0.BUILD-SNAPSHOT"
-
-

Leiningen

-
[org.springframework.cloud/spring-cloud-contract-maven-plugin "1.0.0.BUILD-SNAPSHOT"]
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/dependency-management.html b/spring-cloud-contract-maven-plugin/dependency-management.html index cff133890e..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/dependency-management.html +++ b/spring-cloud-contract-maven-plugin/dependency-management.html @@ -1,3994 +1,12 @@ - - - - - - - - - Spring Cloud Contract Verifier Maven Plugin – Project Dependency Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Dependency Management

-
-

compile

-

The following is a list of compile dependencies in the DependencyManagement of this project. These dependencies can be included in the submodules to compile and run the submodule:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicense
antlrantlr2.7.7jarBSD License
args4jargs4j2.32jarMIT License
cglibcglib3.2.4jarASF 2.0
ch.qos.logbacklogback-access1.1.7jarEclipse Public License - v 1.0, GNU Lesser General Public License
ch.qos.logbacklogback-classic1.1.7jarEclipse Public License - v 1.0, GNU Lesser General Public License
ch.qos.logbacklogback-core1.1.7jarEclipse Public License - v 1.0, GNU Lesser General Public License
com.atomikostransactions-jdbc3.9.3jarAtomikos Multiple Licensing Scheme
com.atomikostransactions-jms3.9.3jarAtomikos Multiple Licensing Scheme
com.atomikostransactions-jta3.9.3jarAtomikos Multiple Licensing Scheme
com.couchbase.clientcouchbase-spring-cache2.0.0jarThe Apache Software License, Version 2.0
com.couchbase.clientjava-client2.2.8jarThe Apache Software License, Version 2.0
com.datastax.cassandracassandra-driver-core2.1.9jarApache 2
com.datastax.cassandracassandra-driver-dse2.1.9jarApache 2
com.datastax.cassandracassandra-driver-mapping2.1.9jarApache 2
com.esotericsoftwarekryo-shaded3.0.3jarNew BSD License
com.fasterxmlclassmate1.3.1jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.corejackson-annotations2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.corejackson-core2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.corejackson-databind2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.dataformatjackson-dataformat-cbor2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.dataformatjackson-dataformat-csv2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.dataformatjackson-dataformat-smile2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.dataformatjackson-dataformat-xml2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.dataformatjackson-dataformat-yaml2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-guava2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-hibernate42.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-hibernate52.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-jaxrs2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-jdk82.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-joda2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-json-org2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.datatypejackson-datatype-jsr3102.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.jaxrsjackson-jaxrs-base2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.jaxrsjackson-jaxrs-json-provider2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.modulejackson-module-jaxb-annotations2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.modulejackson-module-kotlin2.8.0jarThe Apache Software License, Version 2.0
com.fasterxml.jackson.modulejackson-module-parameter-names2.8.0jarThe Apache Software License, Version 2.0
com.gemstone.gemfiregemfire8.2.0jar-
com.github.ben-manes.caffeinecaffeine2.3.1jarThe Apache Software License, Version 2.0
com.github.mxab.thymeleaf.extrasthymeleaf-extras-data-attribute1.3jarThe Apache Software License, Version 2.0
com.github.tomakehurstwiremock2.1.7jarThe Apache Software License, Version 2.0
com.google.appengineappengine-api-1.0-sdk1.9.38jarGoogle App Engine Terms of Service
com.google.code.gsongson2.7jarApache 2.0
com.google.guavaguava18.0jarThe Apache Software License, Version 2.0
com.googlecode.json-simplejson-simple1.1.1jarThe Apache Software License, Version 2.0
com.h2databaseh21.4.192jarMPL 2.0 or EPL 1.0
com.hazelcasthazelcast3.6.4jarThe Apache Software License, Version 2.0
com.hazelcasthazelcast-hibernate43.6.4jarThe Apache Software License, Version 2.0
com.hazelcasthazelcast-spring3.6.4jarThe Apache Software License, Version 2.0
com.jayway.jsonpathjson-path2.2.0jarThe Apache Software License, Version 2.0
com.jayway.jsonpathjson-path-assert2.2.0jarThe Apache Software License, Version 2.0
com.jayway.restassuredspring-mock-mvc2.9.0jarApache 2.0
com.netflix.archaiusarchaius-core0.7.4jarThe Apache Software License, Version 2.0
com.netflix.eurekaeureka-client1.4.10jarThe Apache Software License, Version 2.0
com.netflix.eurekaeureka-core1.4.10jarThe Apache Software License, Version 2.0
com.netflix.feignfeign-core8.16.2jarThe Apache Software License, Version 2.0
com.netflix.feignfeign-httpclient8.16.2jarThe Apache Software License, Version 2.0
com.netflix.feignfeign-hystrix8.16.2jarThe Apache Software License, Version 2.0
com.netflix.feignfeign-okhttp8.16.2jarThe Apache Software License, Version 2.0
com.netflix.feignfeign-slf4j8.16.2jarThe Apache Software License, Version 2.0
com.netflix.hystrixhystrix-core1.5.3jarThe Apache Software License, Version 2.0
com.netflix.hystrixhystrix-javanica1.5.3jarThe Apache Software License, Version 2.0
com.netflix.hystrixhystrix-metrics-event-stream1.5.3jarThe Apache Software License, Version 2.0
com.netflix.netflix-commonsnetflix-commons-util0.1.1jarThe Apache Software License, Version 2.0
com.netflix.ribbonribbon2.2.0jarThe Apache Software License, Version 2.0
com.netflix.ribbonribbon-core2.2.0jarThe Apache Software License, Version 2.0
com.netflix.ribbonribbon-eureka2.2.0jarThe Apache Software License, Version 2.0
com.netflix.ribbonribbon-httpclient2.2.0jarThe Apache Software License, Version 2.0
com.netflix.ribbonribbon-loadbalancer2.2.0jarThe Apache Software License, Version 2.0
com.netflix.servoservo-core0.10.1jarThe Apache Software License, Version 2.0
com.netflix.zuulzuul-core1.1.0jarThe Apache Software License, Version 2.0
com.samskivertjmustache1.12jarThe (New) BSD License
com.sendgridsendgrid-java2.2.2jarMIT License
com.squareup.okhttpokhttp2.5.0jarApache 2.0
com.sun.jerseyjersey-client1.19.1jarCDDL 1.1, GPL2 w/ CPE
com.sun.jerseyjersey-core1.19.1jarCDDL 1.1, GPL2 w/ CPE
com.sun.jerseyjersey-server1.19.1jarCDDL 1.1, GPL2 w/ CPE
com.sun.jerseyjersey-servlet1.19.1jarCDDL 1.1, GPL2 w/ CPE
com.sun.jersey.contribsjersey-apache-client41.19.1jarCDDL 1.1, GPL2 w/ CPE
com.sun.mailjavax.mail1.5.5jarCDDL/GPLv2+CE
com.thoughtworks.xstreamxstream1.4.2jarBSD style
com.timgroupjava-statsd-client3.1.0jarThe MIT License (MIT)
com.toomuchcoding.jsonassertjsonassert0.4.7jarThe Apache License, Version 2.0
com.zaxxerHikariCP2.4.7jarThe Apache Software License, Version 2.0
com.zaxxerHikariCP-java62.3.13jarThe Apache Software License, Version 2.0
commons-beanutilscommons-beanutils1.9.2jarThe Apache Software License, Version 2.0
commons-codeccommons-codec1.10jarApache License, Version 2.0
commons-collectionscommons-collections3.2.2jarApache License, Version 2.0
commons-configurationcommons-configuration1.8jarThe Apache Software License, Version 2.0
commons-dbcpcommons-dbcp1.4jarThe Apache Software License, Version 2.0
commons-digestercommons-digester2.1jarThe Apache Software License, Version 2.0
commons-poolcommons-pool1.6jarThe Apache Software License, Version 2.0
de.flapdoodle.embedde.flapdoodle.embed.mongo1.50.5jarThe Apache Software License, Version 2.0
dom4jdom4j1.6.1jar-
info.solidsoft.spockspock-global-unroll0.5.0jarThe Apache Software License, Version 2.0
io.dropwizard.metricsmetrics-core3.1.2jarApache License 2.0
io.dropwizard.metricsmetrics-ganglia3.1.2jarApache License 2.0
io.dropwizard.metricsmetrics-graphite3.1.2jarApache License 2.0
io.dropwizard.metricsmetrics-servlets3.1.2jarApache License 2.0
io.projectreactorreactor-bus2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-core2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-groovy2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-groovy-extensions2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-logback2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-net2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactorreactor-stream2.0.8.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactor.springreactor-spring-context2.0.7.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactor.springreactor-spring-core2.0.7.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactor.springreactor-spring-messaging2.0.7.RELEASEjarThe Apache Software License, Version 2.0
io.projectreactor.springreactor-spring-webmvc2.0.7.RELEASEjarThe Apache Software License, Version 2.0
io.reactivexrxjava1.1.5jarThe Apache Software License, Version 2.0
io.searchboxjest2.0.3jarThe Apache Software License, Version 2.0
io.undertowundertow-core1.3.23.FinaljarApache License Version 2.0
io.undertowundertow-servlet1.3.23.FinaljarApache License Version 2.0
io.undertowundertow-websockets-jsr1.3.23.FinaljarApache License Version 2.0
javax-injectjavax-inject1jar-
javax.cachecache-api1.0.0jarJSR-000107 JCACHE 2.9 Public Review - Updated Specification - License
javax.injectjavax.inject1jarThe Apache Software License, Version 2.0
javax.jmsjms-api1.1-rev-1jarCDDL + GPLv2 with classpath exception
javax.mailjavax.mail-api1.5.5jarCDDL/GPLv2+CE
javax.servletjavax.servlet-api3.1.0jarCDDL + GPLv2 with classpath exception
javax.servletjstl1.2jar-
javax.transactionjavax.transaction-api1.2jarCDDL + GPLv2 with classpath exception
jaxenjaxen1.1.6jarnull
joda-timejoda-time2.9.4jarApache 2
junitjunit4.12jarEclipse Public License 1.0
mysqlmysql-connector-java5.1.39jarThe GNU General Public License, Version 2
net.java.dev.jnajna4.2.2jarLGPL, version 2.1, ASL, version 2
net.sf.ehcacheehcache2.10.2.2.21jarsrc/assemble/EHCACHE-CORE-LICENSE.txt
net.sourceforge.htmlunithtmlunit2.21jarApache License, Version 2.0
net.sourceforge.jtdsjtds1.3.1jarLGPL
net.sourceforge.nekohtmlnekohtml1.9.22jarThe Apache Software License, Version 2.0
nz.net.ultraq.thymeleafthymeleaf-layout-dialect1.4.0jarThe Apache Software License, Version 2.0
org.apache.activemqactivemq-amqp5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-blueprint5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-broker5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-camel5.12.1jarApache License, Version 2.0
org.apache.activemqactivemq-client5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-console5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-http5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-jaas5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-jdbc-store5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-jms-pool5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-kahadb-store5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-karaf5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-leveldb-store5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-log4j-appender5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-mqtt5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-openwire-generator5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-openwire-legacy5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-osgi5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-partition5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-pool5.12.1jarApache License, Version 2.0
org.apache.activemqactivemq-ra5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-run5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-runtime-config5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-shiro5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-spring5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-stomp5.13.3jarApache License, Version 2.0
org.apache.activemqactivemq-web5.13.3jarApache License, Version 2.0
org.apache.activemqartemis-amqp-protocol1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-commons1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-core-client1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-jms-client1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-jms-server1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-journal1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-native1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-selector1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-server1.3.0jarApache License, Version 2.0
org.apache.activemqartemis-service-extensions1.3.0jarApache License, Version 2.0
org.apache.camelcamel-jackson2.17.0jarApache License, Version 2.0
org.apache.camelcamel-jms2.17.0jarApache License, Version 2.0
org.apache.camelcamel-spring2.17.0jarApache License, Version 2.0
org.apache.camelcamel-spring-boot-starter2.17.0jarApache License, Version 2.0
org.apache.commonscommons-dbcp22.1.1jarThe Apache Software License, Version 2.0
org.apache.commonscommons-pool22.4.2jarThe Apache Software License, Version 2.0
org.apache.curatorcurator-framework2.10.0jarThe Apache Software License, Version 2.0
org.apache.curatorcurator-recipes2.10.0jarThe Apache Software License, Version 2.0
org.apache.curatorcurator-x-discovery2.10.0jarThe Apache Software License, Version 2.0
org.apache.derbyderby10.12.1.1jarApache 2
org.apache.httpcomponentshttpasyncclient4.1.2jarLICENSE.txt
org.apache.httpcomponentshttpclient4.5.2jarApache License, Version 2.0
org.apache.httpcomponentshttpcore4.4.5jarApache License, Version 2.0
org.apache.httpcomponentshttpmime4.5.2jarApache License, Version 2.0
org.apache.logging.log4jlog4j-api2.6.1jarThe Apache Software License, Version 2.0
org.apache.logging.log4jlog4j-core2.6.1jarThe Apache Software License, Version 2.0
org.apache.logging.log4jlog4j-slf4j-impl2.6.1jarThe Apache Software License, Version 2.0
org.apache.mavenmaven-aether-provider3.3.9jarApache License, Version 2.0
org.apache.solrsolr-solrj5.5.2jarApache 2
org.apache.tomcattomcat-jdbc8.5.4jarApache License, Version 2.0
org.apache.tomcattomcat-jsp-api8.5.4jarApache License, Version 2.0
org.apache.tomcat.embedtomcat-embed-core8.5.4jarApache License, Version 2.0
org.apache.tomcat.embedtomcat-embed-el8.5.4jarApache License, Version 2.0
org.apache.tomcat.embedtomcat-embed-jasper8.5.4jarApache License, Version 2.0
org.apache.tomcat.embedtomcat-embed-websocket8.5.4jarApache License, Version 2.0
org.apache.velocityvelocity1.7jarThe Apache Software License, Version 2.0
org.apache.velocityvelocity-tools2.0jarThe Apache Software License, Version 2.0
org.aspectjaspectjrt1.8.9jarEclipse Public License - v 1.0
org.aspectjaspectjtools1.8.9jarEclipse Public License - v 1.0
org.aspectjaspectjweaver1.8.9jarEclipse Public License - v 1.0
org.codehaus.btmbtm2.1.4jarGNU Lesser General Public License v3.0
org.codehaus.groovygroovy2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-all2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-ant2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-bsf2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-console2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-docgenerator2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-groovydoc2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-groovysh2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-jmx2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-json2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-jsr2232.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-nio2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-servlet2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-sql2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-swing2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-templates2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-test2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-testng2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.groovygroovy-xml2.4.7jarThe Apache Software License, Version 2.0
org.codehaus.janinojanino2.7.8jarNew BSD License
org.crashubcrash.cli1.3.2jarLGPL, version 2.1
org.crashubcrash.connectors.ssh1.3.2jarLGPL, version 2.1
org.crashubcrash.connectors.telnet1.3.2jarLGPL, version 2.1
org.crashubcrash.embed.spring1.3.2jarLGPL, version 2.1
org.crashubcrash.plugins.cron1.3.2jarLGPL, version 2.1
org.crashubcrash.plugins.mail1.3.2jarLGPL, version 2.1
org.crashubcrash.shell1.3.2jarLGPL, version 2.1
org.eclipse.aetheraether-api1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-connector-basic1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-impl1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-transport-file1.1.0jarEclipse Public License, Version 1.0
org.eclipse.aetheraether-transport-http1.1.0jarEclipse Public License, Version 1.0
org.eclipse.jettyapache-jsp9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyapache-jstl9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-annotations9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-client9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-continuation9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-deploy9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-http9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-io9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-jmx9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-plus9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-security9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-server9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-servlet9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-servlets9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-util9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-webapp9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jettyjetty-xml9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jetty.orbitjavax.servlet.jsp2.2.0.v201112011158jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jetty.websocketjavax-websocket-server-impl9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jetty.websocketwebsocket-client9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jetty.websocketwebsocket-server9.3.10.v20160621jarApache Software License - Version 2.0, Eclipse Public License - Version 1.0
org.eclipse.jgitorg.eclipse.jgit3.5.3.201412180710-rjarEclipse Distribution License (New BSD License)
org.ehcacheehcache3.1.1jarThe Apache Software License, Version 2.0
org.ehcacheehcache-clustered3.1.1jarThe Apache Software License, Version 2.0
org.ehcacheehcache-transactions3.1.1jarThe Apache Software License, Version 2.0
org.elasticsearchelasticsearch2.3.3jarThe Apache Software License, Version 2.0
org.firebirdsql.jdbcjaybird-jdk162.2.10jarGNU Lesser General Public License, Modified BSD (3-clause) License
org.firebirdsql.jdbcjaybird-jdk172.2.10jarGNU Lesser General Public License, Modified BSD (3-clause) License
org.firebirdsql.jdbcjaybird-jdk182.2.10jarGNU Lesser General Public License, Modified BSD (3-clause) License
org.flywaydbflyway-core3.2.1jarApache License, Version 2.0
org.freemarkerfreemarker2.3.24-incubatingjarApache License, Version 2.0
org.glassfishjavax.el3.0.0jarCDDL + GPLv2 with classpath exception
org.glassfish.jersey.containersjersey-container-servlet2.23.1jarCDDL+GPL License
org.glassfish.jersey.containersjersey-container-servlet-core2.23.1jarCDDL+GPL License
org.glassfish.jersey.corejersey-server2.23.1jarCDDL+GPL License
org.glassfish.jersey.extjersey-bean-validation2.23.1jarCDDL+GPL License
org.glassfish.jersey.extjersey-spring32.23.1jarCDDL+GPL License
org.glassfish.jersey.mediajersey-media-json-jackson2.23.1jarCDDL+GPL License
org.hamcresthamcrest-core1.3jarNew BSD License
org.hamcresthamcrest-library1.3jarNew BSD License
org.hibernatehibernate-core5.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-ehcache5.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-entitymanager5.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-envers5.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-java85.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-jpamodelgen5.0.9.FinaljarGNU Lesser General Public License
org.hibernatehibernate-validator5.2.4.FinaljarApache License, Version 2.0
org.hibernatehibernate-validator-annotation-processor5.2.4.FinaljarApache License, Version 2.0
org.hornetqhornetq-jms-client2.4.7.FinaljarASL 2.0
org.hornetqhornetq-jms-server2.4.7.FinaljarASL 2.0
org.hsqldbhsqldb2.3.3jarHSQLDB License, a BSD open source license
org.infinispaninfinispan-jcache8.2.2.FinaljarApache License
org.infinispaninfinispan-spring4-common8.2.2.FinaljarApache License
org.infinispaninfinispan-spring4-embedded8.2.2.FinaljarApache License
org.javassistjavassist3.20.0-GAjarMPL 1.1, LGPL 2.1, Apache License 2.0
org.jbossjboss-transaction-spi7.3.2.FinaljarPublic Domain
org.jboss.loggingjboss-logging3.3.0.FinaljarApache License, version 2.0
org.jboss.narayana.jtajdbc5.3.3.FinaljarLGPL 2.1
org.jboss.narayana.jtajms5.3.3.FinaljarLGPL 2.1
org.jboss.narayana.jtajta5.3.3.FinaljarLGPL 2.1
org.jboss.narayana.jtsnarayana-jts-integration5.3.3.FinaljarLGPL 2.1
org.jdomjdom22.0.6jarSimilar to Apache License but with the acknowledgment clause removed
org.jolokiajolokia-core1.3.3jarApache 2
org.jooqjooq3.8.2jarApache License, Version 2.0
org.jooqjooq-codegen3.8.2jarApache License, Version 2.0
org.jooqjooq-meta3.8.2jarApache License, Version 2.0
org.jsonjson20140107jarThe JSON License
org.liquibaseliquibase-core3.5.1jarApache License, Version 2.0
org.mariadb.jdbcmariadb-java-client1.4.6jarLGPL-2.1
org.mockitomockito-core1.10.19jarThe MIT License
org.mongodbmongo-java-driver3.2.2jarThe Apache Software License, Version 2.0
org.mongodbmongodb-driver3.2.2jarThe Apache Software License, Version 2.0
org.neo4jneo4j-ogm-api2.0.3jarThe Apache Software License, Version 2.0
org.neo4jneo4j-ogm-compiler2.0.3jarThe Apache Software License, Version 2.0
org.neo4jneo4j-ogm-core2.0.3jarThe Apache Software License, Version 2.0
org.neo4jneo4j-ogm-http-driver2.0.3jarThe Apache Software License, Version 2.0
org.objenesisobjenesis2.1jarApache 2
org.postgresqlpostgresql9.4.1208.jre7jarThe PostgreSQL License
org.projectlomboklombok1.16.6jarThe MIT License
org.seleniumhq.seleniumhtmlunit-driver2.21jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-api2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-chrome-driver2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-firefox-driver2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-ie-driver2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-java2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-remote-driver2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-safari-driver2.53.0jarThe Apache Software License, Version 2.0
org.seleniumhq.seleniumselenium-support2.53.0jarThe Apache Software License, Version 2.0
org.skyscreamerjsonassert1.2.3jarThe Apache Software License, Version 2.0
org.slf4jjcl-over-slf4j1.7.21jarMIT License
org.slf4jjul-to-slf4j1.7.21jarMIT License
org.slf4jlog4j-over-slf4j1.7.21jarApache Software Licenses
org.slf4jslf4j-api1.7.21jarMIT License
org.slf4jslf4j-jdk141.7.21jarMIT License
org.slf4jslf4j-log4j121.7.21jarMIT License
org.slf4jslf4j-simple1.7.21jarMIT License
org.spockframeworkspock-core1.0-groovy-2.4jarThe Apache Software License, Version 2.0
org.spockframeworkspock-spring1.0-groovy-2.4jarThe Apache Software License, Version 2.0
org.springframeworkspring-aop4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-aspects4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-beans4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-context4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-context-support4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-core4.3.1.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-expression4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-instrument4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-instrument-tomcat4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-jdbc4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-jms4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-messaging4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-orm4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-oxm4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-test4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-tuple1.0.0.RELEASEjarApache License, Version 2.0
org.springframeworkspring-tx4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-web4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-webmvc4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-webmvc-portlet4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspring-websocket4.3.2.BUILD-SNAPSHOTjarThe Apache Software License, Version 2.0
org.springframeworkspringloaded1.2.6.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.amqpspring-amqp1.6.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.amqpspring-rabbit1.6.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.batchspring-batch-core3.0.7.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.batchspring-batch-infrastructure3.0.7.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.batchspring-batch-integration3.0.7.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.batchspring-batch-test3.0.7.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.bootspring-boot1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot1.4.0.BUILD-SNAPSHOTtest-jarApache License, Version 2.0
org.springframework.bootspring-boot-actuator1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-actuator-docs1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-autoconfigure1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-configuration-metadata1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-configuration-processor1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-devtools1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-loader1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-loader-tools1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-activemq1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-actuator1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-amqp1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-aop1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-artemis1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-batch1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-cache1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-cloud-connectors1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-cassandra1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-couchbase1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-elasticsearch1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-gemfire1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-jpa1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-mongodb1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-neo4j1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-redis1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-rest1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-data-solr1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-freemarker1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-groovy-templates1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-hateoas1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-hornetq1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-integration1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jdbc1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jersey1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jetty1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jooq1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jta-atomikos1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jta-bitronix1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-jta-narayana1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-log4j21.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-logging1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-mail1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-mobile1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-mustache1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-redis1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-remote-shell1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-security1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-social-facebook1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-social-linkedin1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-social-twitter1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-test1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-thymeleaf1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-tomcat1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-undertow1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-validation1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-velocity1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-web1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-web-services1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-websocket1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-starter-ws1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-test1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.bootspring-boot-test1.4.0.BUILD-SNAPSHOTtest-jarApache License, Version 2.0
org.springframework.bootspring-boot-test-autoconfigure1.4.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-cloudfoundry-connector1.2.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-commons1.1.2.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-config-client1.1.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-config-monitor1.1.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-config-server1.1.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-context1.1.2.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-converters1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-spec1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner-boot1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner-camel1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner-integration1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner-jetty1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-stub-runner-stream1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-verifier1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-contract-wiremock1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-core1.2.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-heroku-connector1.2.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-localconfig-connector1.2.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-netflix-core1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-eureka-client1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-eureka-server1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-hystrix-amqp1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-hystrix-dashboard1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-hystrix-stream1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-sidecar1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-spectator1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-turbine1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-netflix-turbine-stream1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-spring-service-connector1.2.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.cloudspring-cloud-starter1.1.2.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-archaius1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-atlas1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-config1.1.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-contract-stub-runner1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-contract-stub-runner-jetty1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-contract-verifier1.0.0.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-eureka1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-eureka-server1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-feign1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-hystrix1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-hystrix-dashboard1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-ribbon1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-spectator1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-stream-kafka1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-stream-rabbit1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-turbine1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-turbine-amqp1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-turbine-stream1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-zookeeper1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-zookeeper-all1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-zookeeper-config1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-zookeeper-discovery1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-starter-zuul1.1.5.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-binder-kafka1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-binder-rabbit1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-binder-test1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-codec1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-rxjava1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-test-support1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-stream-test-support-internal1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-zookeeper-config1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-zookeeper-core1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.cloudspring-cloud-zookeeper-discovery1.0.3.BUILD-SNAPSHOTjarApache License, Version 2.0
org.springframework.dataspring-cql1.4.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-cassandra1.4.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-commons1.12.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-couchbase2.1.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-elasticsearch2.0.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-envers1.0.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-gemfire1.8.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-jpa1.10.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-keyvalue1.1.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-mongodb1.9.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-mongodb-cross-store1.9.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-mongodb-log4j1.9.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-neo4j4.1.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-redis1.7.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-rest-core2.5.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-rest-hal-browser2.5.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-rest-webmvc2.5.2.RELEASEjarApache License, Version 2.0
org.springframework.dataspring-data-solr2.0.2.RELEASEjarApache License, Version 2.0
org.springframework.hateoasspring-hateoas0.20.0.RELEASEjarApache License, Version 2.0
org.springframework.integrationspring-integration-amqp4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-core4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-event4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-feed4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-file4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-ftp4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-gemfire4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-groovy4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-http4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-ip4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-java-dsl1.1.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-jdbc4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-jms4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-jmx4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-jpa4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-mail4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-mongodb4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-mqtt4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-redis4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-rmi4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-scripting4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-security4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-sftp4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-stomp4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-stream4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-syslog4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-test4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-tuple1.0.0.RELEASEjarApache License, Version 2.0
org.springframework.integrationspring-integration-twitter4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-websocket4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-ws4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-xml4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-xmpp4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.integrationspring-integration-zookeeper4.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.mobilespring-mobile-device1.1.5.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.pluginspring-plugin-core1.2.0.RELEASEjarApache License, Version 2.0
org.springframework.restdocsspring-restdocs-core1.1.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.restdocsspring-restdocs-mockmvc1.1.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.restdocsspring-restdocs-restassured1.1.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.retryspring-retry1.1.3.RELEASEjarApache 2.0
org.springframework.securityspring-security-acl4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-aspects4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-cas4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-config4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-core4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-crypto4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-data4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-jwt1.0.4.RELEASEjarApache 2.0
org.springframework.securityspring-security-ldap4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-messaging4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-openid4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-remoting4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-rsa1.0.1.RELEASEjarApache 2.0
org.springframework.securityspring-security-taglibs4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-test4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.securityspring-security-web4.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.security.oauthspring-security-oauth2.0.10.RELEASEjarApache 2.0
org.springframework.security.oauthspring-security-oauth22.0.10.RELEASEjarApache 2.0
org.springframework.sessionspring-session1.2.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.sessionspring-session-data-gemfire1.2.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.sessionspring-session-data-mongo1.2.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.sessionspring-session-data-redis1.2.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.sessionspring-session-jdbc1.2.1.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-config1.1.4.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-core1.1.4.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-facebook2.0.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-facebook-web2.0.3.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-linkedin1.0.2.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-security1.1.4.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-twitter1.1.2.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.socialspring-social-web1.1.4.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.wsspring-ws-core2.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.wsspring-ws-security2.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.wsspring-ws-support2.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.springframework.wsspring-ws-test2.3.0.RELEASEjarThe Apache Software License, Version 2.0
org.thymeleafthymeleaf2.1.5.RELEASEjarThe Apache Software License, Version 2.0
org.thymeleafthymeleaf-spring42.1.5.RELEASEjarThe Apache Software License, Version 2.0
org.thymeleaf.extrasthymeleaf-extras-conditionalcomments2.1.1.RELEASEjarThe Apache Software License, Version 2.0
org.thymeleaf.extrasthymeleaf-extras-java8time2.1.0.RELEASEjarThe Apache Software License, Version 2.0
org.thymeleaf.extrasthymeleaf-extras-springsecurity42.1.2.RELEASEjarThe Apache Software License, Version 2.0
org.tmatesoft.svnkitsvnkit1.8.7jarTMate Open Source License (with dual licensing option)
org.webjarsbootstrap3.2.0jarApache License, Version 2.0
org.webjarsd3js3.4.11jarThe BSD 3-Clause License
org.webjarshal-browser9f96c74jarMIT License
org.webjarsjquery2.1.1jarMIT License
org.webjarswebjars-locator0.32jarMIT
org.xerialsqlite-jdbc3.8.11.2jarThe Apache Software License, Version 2.0
org.yamlsnakeyaml1.17jarApache License, Version 2.0
redis.clientsjedis2.8.1jarMIT
wsdl4jwsdl4j1.6.3jarCPL
xml-apisxml-apis1.4.01jarThe Apache Software License, Version 2.0, The SAX License, The W3C License
-
-

test

-

The following is a list of test dependencies in the DependencyManagement of this project. These dependencies can be included in the submodules to compile and run unit tests for the submodule:

- - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersionTypeLicense
org.apache.curatorcurator-test2.10.0jarThe Apache Software License, Version 2.0
org.assertjassertj-core2.4.1jarApache License, Version 2.0
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/distribution-management.html b/spring-cloud-contract-maven-plugin/distribution-management.html index 97d6bb1457..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/distribution-management.html +++ b/spring-cloud-contract-maven-plugin/distribution-management.html @@ -1,377 +1,12 @@ - - - - - - - - - Spring Cloud Contract Verifier Maven Plugin – Project Distribution Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

The following is the distribution management information used by this project.

- - -
-

Snapshot Repository - repo.spring.io

https://repo.spring.io/plugins-snapshot-local
-
-

Site - github

-

scm:git:git@github.com:spring-cloud/spring-cloud-contract.git

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/generateStubs-mojo.html b/spring-cloud-contract-maven-plugin/generateStubs-mojo.html index 60e8fe9d29..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/generateStubs-mojo.html +++ b/spring-cloud-contract-maven-plugin/generateStubs-mojo.html @@ -1,499 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:generateStubs - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:generateStubs

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:generateStubs

- -

Description:

- -
Picks the converted .json files and creates a jar. Requires convert -to be executed first.
- -

Attributes:

- -
    - -
  • Requires a Maven project to be executed.
  • - -
  • Binds by default to the lifecycle phase: package.
  • -
-
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<classifier>String-(no description)
Default value is: stubs.
<excludedFiles>String[]-Patterns that should not be taken into account for processing.
<failOnNoContracts>boolean-When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
Default value is: true.
User property is: failOnNoContracts.
<incrementalContractStubsJar>boolean-If set to true then stubs jar is created only when stubs have -changed since last build.
Default value is: true.
User property is: incrementalContractStubsJar.
<jarSkip>boolean-Set this to "true" to bypass only JAR creation.
Default value is: false.
User property is: spring.cloud.contract.verifier.jar.skip.
<outputDirectory>File-(no description)
Default value is: ${project.build.directory}/stubs.
User property is: stubsDirectory.
<skip>boolean-Set this to "true" to bypass the whole Verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
-
-
-

Parameter Details

-
-

<classifier>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • Default: stubs
  • -

-

<excludedFiles>

- -
Patterns that should not be taken into account for processing.
- -
    - -
  • Type: java.lang.String[]
  • - -
  • Required: No
  • -

-

<failOnNoContracts>

- -
When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: failOnNoContracts
  • - -
  • Default: true
  • -

-

<incrementalContractStubsJar>

- -
If set to true then stubs jar is created only when stubs have -changed since last build.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: incrementalContractStubsJar
  • - -
  • Default: true
  • -

-

<jarSkip>

- -
Set this to "true" to bypass only JAR creation.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.jar.skip
  • - -
  • Default: false
  • -

-

<outputDirectory>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: stubsDirectory
  • - -
  • Default: ${project.build.directory}/stubs
  • -

-

<skip>

- -
Set this to "true" to bypass the whole Verifier execution.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skip
  • - -
  • Default: false
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/generateTests-mojo.html b/spring-cloud-contract-maven-plugin/generateTests-mojo.html index 68a4809253..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/generateTests-mojo.html +++ b/spring-cloud-contract-maven-plugin/generateTests-mojo.html @@ -1,1185 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:generateTests - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:generateTests

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:generateTests

- -

Description:

- -
From the provided directory with contracts generates the acceptance -tests on the producer side.
- -

Attributes:

- -
    - -
  • Requires a Maven project to be executed.
  • - -
  • Requires dependency resolution of artifacts in scope: test.
  • - -
  • Binds by default to the lifecycle phase: generate-test-sources.
  • -
-
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<assertJsonSize>boolean-Incubating feature. You can check the size of JSON arrays. If not -turned on explicitly will be disabled.
Default value is: false.
User property is: spring.cloud.contract.verifier.assert.size.
<baseClassForTests>String-(no description)
<baseClassMappings>List-A way to override any base class mappings. The keys are regular -expressions on the package name of the contract and the values FQN -to a base class for that given expression. Example of a mapping -.*.com.example.v1..* -> -com.example.SomeBaseClass When a contract's package -matches the provided regular expression then extending class will -be the one provided in the map - in this case -com.example.SomeBaseClass.
User property is: baseClassMappings.
<basePackageForTests>String-(no description)
<contractDependency>Dependency-(no description)
User property is: contractDependency.
<contractsDirectory>File-(no description)
Default value is: ${project.basedir}/src/test/resources/contracts.
User property is: spring.cloud.contract.verifier.contractsDirectory.
<contractsMode>StubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
<contractsPath>String-The path in the JAR with all the contracts where contracts for this -particular service lay. If not provided will be resolved to -groupid/artifactid. Example: If groupid -is com.example and artifactid is -service then the resolved path will be -/com/example/artifactid
User property is: contractsPath.
<contractsProperties>Map-Map of properties that can be passed to custom -StubDownloaderBuilder.
User property is: contractsProperties.
<contractsRepositoryPassword>String-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
<contractsRepositoryProxyHost>String-The proxy host to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyHost.
<contractsRepositoryProxyPort>Integer-The proxy port to be used to connect to the repo with contracts.
User property is: contractsRepositoryProxyPort.
<contractsRepositoryUrl>String-The URL from which a contracts should get downloaded. If not -provided but artifactid / coordinates notation was provided then -the current Maven's build repositories will be taken into -consideration.
User property is: contractsRepositoryUrl.
<contractsRepositoryUsername>String-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
<contractsSnapshotCheckSkip>boolean-Deprecated. - with 2.1.0 this option is redundant
Default value is: false.
User property is: contractsSnapshotCheckSkip.
<deleteStubsAfterTest>boolean-If set to false will NOT delete stubs from a temporary -folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
<excludedFiles>List-Patterns that should not be taken into account for processing.
<failOnInProgress>boolean-If set to true then if any contracts that are in progress are -found, will break the build. On the producer side you need to be -explicit about the fact that you have contracts in progress and -take into consideration that you might be causing false positive -test execution results on the consumer side.
Default value is: true.
User property is: failOnInProgress.
<failOnNoContracts>boolean-When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
Default value is: true.
User property is: failOnNoContracts.
<generatedTestResourcesDir>File-(no description)
Default value is: ${project.build.directory}/generated-test-resources/contracts.
<generatedTestSourcesDir>File-(no description)
Default value is: ${project.build.directory}/generated-test-sources/contracts.
<ignoredFiles>List-Patterns for which Spring Cloud Contract Verifier should generate -@Ignored tests.
<imports>String[]-Imports that should be added to generated tests.
<includedFiles>List-Patterns that should be taken into account for processing.
User property is: includedFiles.
<incrementalContractTests>boolean-If set to true then tests are created only when contracts have -changed since last build.
Default value is: true.
User property is: incrementalContractTests.
<mavenTestSkip>boolean-(no description)
Default value is: false.
User property is: maven.test.skip.
<nameSuffixForTests>String-(no description)
<packageWithBaseClasses>String-A package that contains all the base clases for generated tests. If -your contract resides in a location -src/test/resources/contracts/com/example/v1/ and you -provide the packageWithBaseClasses value to -com.example.contracts.base then we will search for a -test source file that will have the package -com.example.contracts.base and name -ExampleV1Base. As you can see it will take the two -last folders to and attach Base to its name.
User property is: packageWithBaseClasses.
<ruleClassForTests>String-(no description)
<skip>boolean-(no description)
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
<skipTests>boolean-(no description)
Default value is: false.
User property is: skipTests.
<staticImports>String[]-Static imports that should be added to generated tests.
<testFramework>TestFramework-(no description)
Default value is: JUNIT5.
<testMode>TestMode-(no description)
Default value is: MOCKMVC.
-
-
-

Parameter Details

-
-

<assertJsonSize>

- -
Incubating feature. You can check the size of JSON arrays. If not -turned on explicitly will be disabled.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.assert.size
  • - -
  • Default: false
  • -

-

<baseClassForTests>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • -

-

<baseClassMappings>

- -
A way to override any base class mappings. The keys are regular -expressions on the package name of the contract and the values FQN -to a base class for that given expression. Example of a mapping -.*.com.example.v1..* -> -com.example.SomeBaseClass When a contract's package -matches the provided regular expression then extending class will -be the one provided in the map - in this case -com.example.SomeBaseClass.
- -
    - -
  • Type: java.util.List
  • - -
  • Required: No
  • - -
  • User Property: baseClassMappings
  • -

-

<basePackageForTests>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • -

-

<contractDependency>

- -
(no description)
- -
    - -
  • Type: org.apache.maven.model.Dependency
  • - -
  • Required: No
  • - -
  • User Property: contractDependency
  • -

-

<contractsDirectory>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.contractsDirectory
  • - -
  • Default: ${project.basedir}/src/test/resources/contracts
  • -

-

<contractsMode>

- -
Picks the mode in which stubs will be found and registered.
- -
    - -
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • - -
  • Required: No
  • - -
  • User Property: contractsMode
  • - -
  • Default: CLASSPATH
  • -

-

<contractsPath>

- -
The path in the JAR with all the contracts where contracts for this -particular service lay. If not provided will be resolved to -groupid/artifactid. Example: If groupid -is com.example and artifactid is -service then the resolved path will be -/com/example/artifactid
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsPath
  • -

-

<contractsProperties>

- -
Map of properties that can be passed to custom -StubDownloaderBuilder.
- -
    - -
  • Type: java.util.Map
  • - -
  • Required: No
  • - -
  • User Property: contractsProperties
  • -

-

<contractsRepositoryPassword>

- -
The password to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryPassword
  • -

-

<contractsRepositoryProxyHost>

- -
The proxy host to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryProxyHost
  • -

-

<contractsRepositoryProxyPort>

- -
The proxy port to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.Integer
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryProxyPort
  • -

-

<contractsRepositoryUrl>

- -
The URL from which a contracts should get downloaded. If not -provided but artifactid / coordinates notation was provided then -the current Maven's build repositories will be taken into -consideration.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUrl
  • -

-

<contractsRepositoryUsername>

- -
The user name to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUsername
  • -

-

<contractsSnapshotCheckSkip>

- -
Deprecated. - with 2.1.0 this option is redundant
- -
If true then will not assert whether a stub / contract -JAR was downloaded from local or remote location.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: contractsSnapshotCheckSkip
  • - -
  • Default: false
  • -

-

<deleteStubsAfterTest>

- -
If set to false will NOT delete stubs from a temporary -folder after running tests.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: deleteStubsAfterTest
  • - -
  • Default: true
  • -

-

<excludedFiles>

- -
Patterns that should not be taken into account for processing.
- -
    - -
  • Type: java.util.List
  • - -
  • Required: No
  • -

-

<failOnInProgress>

- -
If set to true then if any contracts that are in progress are -found, will break the build. On the producer side you need to be -explicit about the fact that you have contracts in progress and -take into consideration that you might be causing false positive -test execution results on the consumer side.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: failOnInProgress
  • - -
  • Default: true
  • -

-

<failOnNoContracts>

- -
When enabled, this flag will tell stub runner to throw an exception -when no stubs / contracts were found.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: failOnNoContracts
  • - -
  • Default: true
  • -

-

<generatedTestResourcesDir>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • Default: ${project.build.directory}/generated-test-resources/contracts
  • -

-

<generatedTestSourcesDir>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • Default: ${project.build.directory}/generated-test-sources/contracts
  • -

-

<ignoredFiles>

- -
Patterns for which Spring Cloud Contract Verifier should generate -@Ignored tests.
- -
    - -
  • Type: java.util.List
  • - -
  • Required: No
  • -

-

<imports>

- -
Imports that should be added to generated tests.
- -
    - -
  • Type: java.lang.String[]
  • - -
  • Required: No
  • -

-

<includedFiles>

- -
Patterns that should be taken into account for processing.
- -
    - -
  • Type: java.util.List
  • - -
  • Required: No
  • - -
  • User Property: includedFiles
  • -

-

<incrementalContractTests>

- -
If set to true then tests are created only when contracts have -changed since last build.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: incrementalContractTests
  • - -
  • Default: true
  • -

-

<mavenTestSkip>

- -
(no description)
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: maven.test.skip
  • - -
  • Default: false
  • -

-

<nameSuffixForTests>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • -

-

<packageWithBaseClasses>

- -
A package that contains all the base clases for generated tests. If -your contract resides in a location -src/test/resources/contracts/com/example/v1/ and you -provide the packageWithBaseClasses value to -com.example.contracts.base then we will search for a -test source file that will have the package -com.example.contracts.base and name -ExampleV1Base. As you can see it will take the two -last folders to and attach Base to its name.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: packageWithBaseClasses
  • -

-

<ruleClassForTests>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • -

-

<skip>

- -
(no description)
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skip
  • - -
  • Default: false
  • -

-

<skipTests>

- -
(no description)
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: skipTests
  • - -
  • Default: false
  • -

-

<staticImports>

- -
Static imports that should be added to generated tests.
- -
    - -
  • Type: java.lang.String[]
  • - -
  • Required: No
  • -

-

<testFramework>

- -
(no description)
- -
    - -
  • Type: org.springframework.cloud.contract.verifier.config.TestFramework
  • - -
  • Required: No
  • - -
  • Default: JUNIT5
  • -

-

<testMode>

- -
(no description)
- -
    - -
  • Type: org.springframework.cloud.contract.verifier.config.TestMode
  • - -
  • Required: No
  • - -
  • Default: MOCKMVC
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/help-mojo.html b/spring-cloud-contract-maven-plugin/help-mojo.html index c6048ffd6e..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/help-mojo.html +++ b/spring-cloud-contract-maven-plugin/help-mojo.html @@ -1,423 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:help - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:help

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:help

- -

Description:

- -
Display help information on -spring-cloud-contract-maven-plugin.
-Call mvn spring-cloud-contract:help -Ddetail=true --Dgoal=<goal-name> to display parameter details.
- -

Attributes:

-
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<detail>boolean-If true, display all settable properties for each -goal.
Default value is: false.
User property is: detail.
<goal>String-The name of the goal for which to show help. If unspecified, all -goals will be displayed.
User property is: goal.
<indentSize>int-The number of spaces per indentation level, should be positive.
Default value is: 2.
User property is: indentSize.
<lineLength>int-The maximum length of a display line, should be positive.
Default value is: 80.
User property is: lineLength.
-
-
-

Parameter Details

-
-

<detail>

- -
If true, display all settable properties for each -goal.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: detail
  • - -
  • Default: false
  • -

-

<goal>

- -
The name of the goal for which to show help. If unspecified, all -goals will be displayed.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: goal
  • -

-

<indentSize>

- -
The number of spaces per indentation level, should be positive.
- -
    - -
  • Type: int
  • - -
  • Required: No
  • - -
  • User Property: indentSize
  • - -
  • Default: 2
  • -

-

<lineLength>

- -
The maximum length of a display line, should be positive.
- -
    - -
  • Type: int
  • - -
  • Required: No
  • - -
  • User Property: lineLength
  • - -
  • Default: 80
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/index.html b/spring-cloud-contract-maven-plugin/index.html index 86e09ab9a0..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/index.html +++ b/spring-cloud-contract-maven-plugin/index.html @@ -1,394 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -

Spring Cloud Contract Maven Plugin

-
-
-
-

Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications.

-
-
-
    -
  • -

    Stubs mappings to be used by WireMock when doing integration testing on the client code (client tests).

    -
  • -
  • -

    Acceptance tests used to verify if server-side implementation of the API is compliant with the contract (server tests).

    -
  • -
-
-
-

Spring Cloud Contract Verifier moves TDD to the level of software architecture.

-
-
-

This plugin allows you to:

-
-
-
    -
  • -

    generate tests from the provided contracts

    -
  • -
  • -

    run the stubs from the stubs

    -
  • -
-
-
-
- -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/integration.html b/spring-cloud-contract-maven-plugin/integration.html index 6e4583b082..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/integration.html +++ b/spring-cloud-contract-maven-plugin/integration.html @@ -1,351 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – CI Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses Continuous Integration System.

-
-

Access

-

The following is a link to the continuous integration system used by the project:

-
-
-

Notifiers

-

No notifiers are defined. Please check back at a later date.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/issue-management.html b/spring-cloud-contract-maven-plugin/issue-management.html index e4a5494dd4..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/issue-management.html +++ b/spring-cloud-contract-maven-plugin/issue-management.html @@ -1,349 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Issue Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses GitHub to manage its issues.

-

Issue Management

-

Issues, bugs, and feature requests should be submitted to the following issue management system for this project.

-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/issue-tracking.html b/spring-cloud-contract-maven-plugin/issue-tracking.html index 096bcfa56b..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/issue-tracking.html +++ b/spring-cloud-contract-maven-plugin/issue-tracking.html @@ -1,348 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Issue Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses GitHub to manage its issues.

-
-

Issue Management

-

Issues, bugs, and feature requests should be submitted to the following issue management system for this project.

-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/junit.html b/spring-cloud-contract-maven-plugin/junit.html index 3bb9531962..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/junit.html +++ b/spring-cloud-contract-maven-plugin/junit.html @@ -1,355 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Java Project with JUnit Tests

-
-
-

Sample minimal configuration for Java Project with JUnit tests.

-
-
-

Test dependencies for generated contract verification tests

-
-
-
                <dependency>
-                        <groupId>org.springframework.cloud</groupId>
-                        <artifactId>spring-cloud-starter-contract-verifier</artifactId>
-                        <version>${it-plugin.version}</version>
-                        <scope>test</scope>
-                </dependency>
-
-
-
-
-

Project configuration for Spring Cloud Contract Verifier with JUnit tests and stub publishing

-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <version>${spring-cloud-verifier-plugin.version}</version>
-                                <extensions>true</extensions>
-                                <configuration>
-                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Base Test class

-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */package hello;
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc;
-import org.junit.Before;
-
-public class BaseAccurest {
-
-        @Before
-        public void setup() {
-                RestAssuredMockMvc.standaloneSetup(new GreetingController());
-        }
-
-}
-
-
-
- -
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/license.html b/spring-cloud-contract-maven-plugin/license.html index 1ffebb6b8f..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/license.html +++ b/spring-cloud-contract-maven-plugin/license.html @@ -1,745 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Licenses - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - - - - - -
- - - - - -
-
- -
- - -
- -
-

Overview

-

Typically the licenses listed for the project are that of the project itself, and not of dependencies.

-
-

Project Licenses

-
-

Apache License, Version 2.0

-

Copyright 2014-2015 the original author or authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -implied. - -See the License for the specific language governing permissions and -limitations under the License.

[Original text] -

Copy of the license follows:

- -
- -
- -
-
-
- Apache Logo -
-
- - - -
-
-
- - -
- The Apache Way - Contribute - ASF Sponsors -
-
-
-
-

Apache License

Version 2.0, January 2004

-https://www.apache.org/licenses/

-

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

-

1. Definitions.

-

"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document.

-

"Licensor" shall mean the copyright owner or entity authorized by the -copyright owner that is granting the License.

-

"Legal Entity" shall mean the union of the acting entity and all other -entities that control, are controlled by, or are under common control with -that entity. For the purposes of this definition, "control" means (i) the -power, direct or indirect, to cause the direction or management of such -entity, whether by contract or otherwise, or (ii) ownership of fifty -percent (50%) or more of the outstanding shares, or (iii) beneficial -ownership of such entity.

-

"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License.

-

"Source" form shall mean the preferred form for making modifications, -including but not limited to software source code, documentation source, -and configuration files.

-

"Object" form shall mean any form resulting from mechanical transformation -or translation of a Source form, including but not limited to compiled -object code, generated documentation, and conversions to other media types.

-

"Work" shall mean the work of authorship, whether in Source or Object form, -made available under the License, as indicated by a copyright notice that -is included in or attached to the work (an example is provided in the -Appendix below).

-

"Derivative Works" shall mean any work, whether in Source or Object form, -that is based on (or derived from) the Work and for which the editorial -revisions, annotations, elaborations, or other modifications represent, as -a whole, an original work of authorship. For the purposes of this License, -Derivative Works shall not include works that remain separable from, or -merely link (or bind by name) to the interfaces of, the Work and Derivative -Works thereof.

-

"Contribution" shall mean any work of authorship, including the original -version of the Work and any modifications or additions to that Work or -Derivative Works thereof, that is intentionally submitted to Licensor for -inclusion in the Work by the copyright owner or by an individual or Legal -Entity authorized to submit on behalf of the copyright owner. For the -purposes of this definition, "submitted" means any form of electronic, -verbal, or written communication sent to the Licensor or its -representatives, including but not limited to communication on electronic -mailing lists, source code control systems, and issue tracking systems that -are managed by, or on behalf of, the Licensor for the purpose of discussing -and improving the Work, but excluding communication that is conspicuously -marked or otherwise designated in writing by the copyright owner as "Not a -Contribution."

-

"Contributor" shall mean Licensor and any individual or Legal Entity on -behalf of whom a Contribution has been received by Licensor and -subsequently incorporated within the Work.

-

2. Grant of Copyright License. Subject to the -terms and conditions of this License, each Contributor hereby grants to You -a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -copyright license to reproduce, prepare Derivative Works of, publicly -display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form.

-

3. Grant of Patent License. Subject to the terms -and conditions of this License, each Contributor hereby grants to You a -perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except as stated in this section) patent license to make, have made, use, -offer to sell, sell, import, and otherwise transfer the Work, where such -license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by -combination of their Contribution(s) with the Work to which such -Contribution(s) was submitted. If You institute patent litigation against -any entity (including a cross-claim or counterclaim in a lawsuit) alleging -that the Work or a Contribution incorporated within the Work constitutes -direct or contributory patent infringement, then any patent licenses -granted to You under this License for that Work shall terminate as of the -date such litigation is filed.

-

4. Redistribution. You may reproduce and -distribute copies of the Work or Derivative Works thereof in any medium, -with or without modifications, and in Source or Object form, provided that -You meet the following conditions:

-
    -
  1. You must give any other recipients of the Work or Derivative Works a -copy of this License; and
  2. -
  3. You must cause any modified files to carry prominent notices stating -that You changed the files; and
  4. +Page Redirection -
  5. You must retain, in the Source form of any Derivative Works that You -distribute, all copyright, patent, trademark, and attribution notices from -the Source form of the Work, excluding those notices that do not pertain to -any part of the Derivative Works; and
  6. - -
  7. If the Work includes a "NOTICE" text file as part of its distribution, -then any Derivative Works that You distribute must include a readable copy -of the attribution notices contained within such NOTICE file, excluding -those notices that do not pertain to any part of the Derivative Works, in -at least one of the following places: within a NOTICE text file distributed -as part of the Derivative Works; within the Source form or documentation, -if provided along with the Derivative Works; or, within a display generated -by the Derivative Works, if and wherever such third-party notices normally -appear. The contents of the NOTICE file are for informational purposes only -and do not modify the License. You may add Your own attribution notices -within Derivative Works that You distribute, alongside or as an addendum to -the NOTICE text from the Work, provided that such additional attribution -notices cannot be construed as modifying the License. -
    -
    -You may add Your own copyright statement to Your modifications and may -provide additional or different license terms and conditions for use, -reproduction, or distribution of Your modifications, or for any such -Derivative Works as a whole, provided Your use, reproduction, and -distribution of the Work otherwise complies with the conditions stated in -this License. -
  8. - -
- -

5. Submission of Contributions. Unless You -explicitly state otherwise, any Contribution intentionally submitted for -inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the -terms of any separate license agreement you may have executed with Licensor -regarding such Contributions.

-

6. Trademarks. This License does not grant -permission to use the trade names, trademarks, service marks, or product -names of the Licensor, except as required for reasonable and customary use -in describing the origin of the Work and reproducing the content of the -NOTICE file.

-

7. Disclaimer of Warranty. Unless required by -applicable law or agreed to in writing, Licensor provides the Work (and -each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, -without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You -are solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise -of permissions under this License.

-

8. Limitation of Liability. In no event and -under no legal theory, whether in tort (including negligence), contract, or -otherwise, unless required by applicable law (such as deliberate and -grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, -incidental, or consequential damages of any character arising as a result -of this License or out of the use or inability to use the Work (including -but not limited to damages for loss of goodwill, work stoppage, computer -failure or malfunction, or any and all other commercial damages or losses), -even if such Contributor has been advised of the possibility of such -damages.

-

9. Accepting Warranty or Additional Liability. -While redistributing the Work or Derivative Works thereof, You may choose -to offer, and charge a fee for, acceptance of support, warranty, indemnity, -or other liability obligations and/or rights consistent with this License. -However, in accepting such obligations, You may act only on Your own behalf -and on Your sole responsibility, not on behalf of any other Contributor, -and only if You agree to indemnify, defend, and hold each Contributor -harmless for any liability incurred by, or claims asserted against, such -Contributor by reason of your accepting any such warranty or additional -liability.

-

END OF TERMS AND CONDITIONS

-

APPENDIX: How to apply the Apache License to your work

-

To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included -on the same "printed page" as the copyright notice for easier -identification within third-party archives.

-
Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    https://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
- - - - - - - - - -
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/licenses.html b/spring-cloud-contract-maven-plugin/licenses.html index 202690cb5c..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/licenses.html +++ b/spring-cloud-contract-maven-plugin/licenses.html @@ -1,973 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Licenses - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

Typically the licenses listed for the project are that of the project itself, and not of dependencies.

-

Project Licenses

-

Apache License, Version 2.0

-

Copyright 2014-2015 the original author or authors. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied. - - See the License for the specific language governing permissions and - limitations under the License.

[Original text] -

Copy of the license follows:

- -
- -
- -
-
- ApacheCon is Coming 9-12 Sept. 2019 - Las Vegas - The Apache Software Foundation -
- -
- Apache Support Logo -
-
-
-

Apache License, Version 2.0

- -

The 2.0 version of the Apache License, approved by the ASF in 2004, helps us achieve our goal of providing -reliable and long-lived software products through collaborative open source software development.

-

All packages produced by the ASF are implicitly licensed under the Apache -License, Version 2.0, unless otherwise explicitly stated.

-
- -

-Apache License

Version 2.0, January 2004

-http://www.apache.org/licenses/ -

- -

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

- -

1. Definitions.

- -
- -

"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document.

- -

"Licensor" shall mean the copyright owner or entity authorized by the -copyright owner that is granting the License.

- -

"Legal Entity" shall mean the union of the acting entity and all other -entities that control, are controlled by, or are under common control with -that entity. For the purposes of this definition, "control" means (i) the -power, direct or indirect, to cause the direction or management of such -entity, whether by contract or otherwise, or (ii) ownership of fifty -percent (50%) or more of the outstanding shares, or (iii) beneficial -ownership of such entity.

- -

"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License.

- -

"Source" form shall mean the preferred form for making modifications, -including but not limited to software source code, documentation source, -and configuration files.

- -

"Object" form shall mean any form resulting from mechanical transformation -or translation of a Source form, including but not limited to compiled -object code, generated documentation, and conversions to other media types.

- -

"Work" shall mean the work of authorship, whether in Source or Object form, -made available under the License, as indicated by a copyright notice that -is included in or attached to the work (an example is provided in the -Appendix below).

- -

"Derivative Works" shall mean any work, whether in Source or Object form, -that is based on (or derived from) the Work and for which the editorial -revisions, annotations, elaborations, or other modifications represent, as -a whole, an original work of authorship. For the purposes of this License, -Derivative Works shall not include works that remain separable from, or -merely link (or bind by name) to the interfaces of, the Work and Derivative -Works thereof.

- -

"Contribution" shall mean any work of authorship, including the original -version of the Work and any modifications or additions to that Work or -Derivative Works thereof, that is intentionally submitted to Licensor for -inclusion in the Work by the copyright owner or by an individual or Legal -Entity authorized to submit on behalf of the copyright owner. For the -purposes of this definition, "submitted" means any form of electronic, -verbal, or written communication sent to the Licensor or its -representatives, including but not limited to communication on electronic -mailing lists, source code control systems, and issue tracking systems that -are managed by, or on behalf of, the Licensor for the purpose of discussing -and improving the Work, but excluding communication that is conspicuously -marked or otherwise designated in writing by the copyright owner as "Not a -Contribution."

- -

"Contributor" shall mean Licensor and any individual or Legal Entity on -behalf of whom a Contribution has been received by Licensor and -subsequently incorporated within the Work.

- -
- -

2. Grant of Copyright License. Subject to the -terms and conditions of this License, each Contributor hereby grants to You -a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -copyright license to reproduce, prepare Derivative Works of, publicly -display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form.

- -

3. Grant of Patent License. Subject to the terms -and conditions of this License, each Contributor hereby grants to You a -perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except as stated in this section) patent license to make, have made, use, -offer to sell, sell, import, and otherwise transfer the Work, where such -license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by -combination of their Contribution(s) with the Work to which such -Contribution(s) was submitted. If You institute patent litigation against -any entity (including a cross-claim or counterclaim in a lawsuit) alleging -that the Work or a Contribution incorporated within the Work constitutes -direct or contributory patent infringement, then any patent licenses -granted to You under this License for that Work shall terminate as of the -date such litigation is filed.

- -

4. Redistribution. You may reproduce and -distribute copies of the Work or Derivative Works thereof in any medium, -with or without modifications, and in Source or Object form, provided that -You meet the following conditions:

- -
    -
  1. You must give any other recipients of the Work or Derivative Works a -copy of this License; and
  2. - -
  3. You must cause any modified files to carry prominent notices stating -that You changed the files; and
  4. - -
  5. You must retain, in the Source form of any Derivative Works that You -distribute, all copyright, patent, trademark, and attribution notices from -the Source form of the Work, excluding those notices that do not pertain to -any part of the Derivative Works; and
  6. - -
  7. If the Work includes a "NOTICE" text file as part of its distribution, -then any Derivative Works that You distribute must include a readable copy -of the attribution notices contained within such NOTICE file, excluding -those notices that do not pertain to any part of the Derivative Works, in -at least one of the following places: within a NOTICE text file distributed -as part of the Derivative Works; within the Source form or documentation, -if provided along with the Derivative Works; or, within a display generated -by the Derivative Works, if and wherever such third-party notices normally -appear. The contents of the NOTICE file are for informational purposes only -and do not modify the License. You may add Your own attribution notices -within Derivative Works that You distribute, alongside or as an addendum to -the NOTICE text from the Work, provided that such additional attribution -notices cannot be construed as modifying the License. -
    -
    -You may add Your own copyright statement to Your modifications and may -provide additional or different license terms and conditions for use, -reproduction, or distribution of Your modifications, or for any such -Derivative Works as a whole, provided Your use, reproduction, and -distribution of the Work otherwise complies with the conditions stated in -this License. -
  8. - -
- -

5. Submission of Contributions. Unless You -explicitly state otherwise, any Contribution intentionally submitted for -inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the -terms of any separate license agreement you may have executed with Licensor -regarding such Contributions.

- -

6. Trademarks. This License does not grant -permission to use the trade names, trademarks, service marks, or product -names of the Licensor, except as required for reasonable and customary use -in describing the origin of the Work and reproducing the content of the -NOTICE file.

- -

7. Disclaimer of Warranty. Unless required by -applicable law or agreed to in writing, Licensor provides the Work (and -each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, -without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You -are solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise -of permissions under this License.

- -

8. Limitation of Liability. In no event and -under no legal theory, whether in tort (including negligence), contract, or -otherwise, unless required by applicable law (such as deliberate and -grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, -incidental, or consequential damages of any character arising as a result -of this License or out of the use or inability to use the Work (including -but not limited to damages for loss of goodwill, work stoppage, computer -failure or malfunction, or any and all other commercial damages or losses), -even if such Contributor has been advised of the possibility of such -damages.

- -

9. Accepting Warranty or Additional Liability. -While redistributing the Work or Derivative Works thereof, You may choose -to offer, and charge a fee for, acceptance of support, warranty, indemnity, -or other liability obligations and/or rights consistent with this License. -However, in accepting such obligations, You may act only on Your own behalf -and on Your sole responsibility, not on behalf of any other Contributor, -and only if You agree to indemnify, defend, and hold each Contributor -harmless for any liability incurred by, or claims asserted against, such -Contributor by reason of your accepting any such warranty or additional -liability.

- -

END OF TERMS AND CONDITIONS

- -
- -

How to apply the Apache License to your work

-

You should include a copy of the Apache License, typically in a file called -LICENSE, in your work, and consider also including a NOTICE file.

-

To apply the Apache License to specific files in your work, attach the following boilerplate -declaration, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included -on the same "printed page" as the copyright notice for easier -identification within third-party archives.

-
Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
- - - - - - - - - - -
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/plugin-info.html b/spring-cloud-contract-maven-plugin/plugin-info.html index 8f15bde77e..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/plugin-info.html +++ b/spring-cloud-contract-maven-plugin/plugin-info.html @@ -1,378 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Plugin Documentation - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Plugin Documentation

-

Goals available for this plugin:

- - - - - - - - - - - - - - - - - - - - - -
GoalDescription
spring-cloud-contract:convertConvert Spring Cloud Contract Verifier contracts into stubs -mappings. -

This goal allows you to generate `stubs-jar` or execute -`spring-cloud-contract:run` with generated mappings.

spring-cloud-contract:generateStubsPicks the converted .json files and creates a jar. Requires convert -to be executed first.
spring-cloud-contract:generateTestsFrom the provided directory with contracts generates the acceptance -tests on the producer side.
spring-cloud-contract:helpDisplay help information on -spring-cloud-contract-maven-plugin.
-Call mvn spring-cloud-contract:help -Ddetail=true --Dgoal=<goal-name> to display parameter details.
spring-cloud-contract:pushStubsToScmThe generated stubs get committed to the SCM repo and pushed to -origin.
spring-cloud-contract:runMojo for running stubs.
-

System Requirements

-

The following specifies the minimum requirements to run this Maven plugin:

- - - - - - - - - - - - -
Maven3.2.5
JDK1.8
MemoryNo minimum requirement.
Disk SpaceNo minimum requirement.
-

Usage

-

You should specify the version in your project's plugin configuration:

-
<project>
-  ...
-  <build>
-    <!-- To define the plugin version in your parent POM -->
-    <pluginManagement>
-      <plugins>
-        <plugin>
-          <groupId>org.springframework.cloud</groupId>
-          <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-          <version>3.0.0-SNAPSHOT</version>
-        </plugin>
-        ...
-      </plugins>
-    </pluginManagement>
-    <!-- To use the plugin goals in your POM or parent POM -->
-    <plugins>
-      <plugin>
-        <groupId>org.springframework.cloud</groupId>
-        <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-        <version>3.0.0-SNAPSHOT</version>
-      </plugin>
-      ...
-    </plugins>
-  </build>
-  ...
-</project>
-
-

For more information, see "Guide to Configuring Plug-ins"

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/plugin-management.html b/spring-cloud-contract-maven-plugin/plugin-management.html index 7401ef0cd8..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/plugin-management.html +++ b/spring-cloud-contract-maven-plugin/plugin-management.html @@ -1,438 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Plugin Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Plugin Management

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersion
io.spring.javaformatspring-javaformat-maven-plugin0.0.9
org.apache.maven.pluginsmaven-antrun-plugin3.0.0
org.apache.maven.pluginsmaven-assembly-plugin2.2-beta-5
org.apache.maven.pluginsmaven-checkstyle-plugin3.1.0
org.apache.maven.pluginsmaven-compiler-plugin3.8.0
org.apache.maven.pluginsmaven-dependency-plugin2.8
org.apache.maven.pluginsmaven-eclipse-plugin2.10
org.apache.maven.pluginsmaven-enforcer-plugin3.0.0-M2
org.apache.maven.pluginsmaven-failsafe-plugin3.0.0-M3
org.apache.maven.pluginsmaven-jar-plugin3.1.0
org.apache.maven.pluginsmaven-javadoc-plugin3.1.0
org.apache.maven.pluginsmaven-release-plugin2.5.3
org.apache.maven.pluginsmaven-resources-plugin3.1.0
org.apache.maven.pluginsmaven-shade-plugin3.1.1
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-M4
org.apache.maven.pluginsmaven-war-plugin3.2.2
org.codehaus.gmavenplusgmavenplus-plugin1.8.1
org.codehaus.mojoexec-maven-plugin1.6.0
org.codehaus.mojoflatten-maven-plugin1.2.3
org.eclipse.m2elifecycle-mapping1.0.0
org.springframework.bootspring-boot-maven-plugin2.4.0-SNAPSHOT
pl.project13.mavengit-commit-id-plugin3.0.0
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/plugins.html b/spring-cloud-contract-maven-plugin/plugins.html index ada1aad68c..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/plugins.html +++ b/spring-cloud-contract-maven-plugin/plugins.html @@ -1,444 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Plugins - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Build Plugins

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersion
io.spring.javaformatspring-javaformat-maven-plugin0.0.9
org.apache.maven.pluginsmaven-checkstyle-plugin3.1.0
org.apache.maven.pluginsmaven-clean-plugin3.1.0
org.apache.maven.pluginsmaven-compiler-plugin3.8.0
org.apache.maven.pluginsmaven-deploy-plugin2.7
org.apache.maven.pluginsmaven-failsafe-plugin3.0.0-M3
org.apache.maven.pluginsmaven-install-plugin2.4
org.apache.maven.pluginsmaven-jar-plugin3.1.0
org.apache.maven.pluginsmaven-javadoc-plugin3.1.0
org.apache.maven.pluginsmaven-plugin-plugin3.6.0
org.apache.maven.pluginsmaven-resources-plugin3.1.0
org.apache.maven.pluginsmaven-scm-publish-plugin3.0.0
org.apache.maven.pluginsmaven-site-plugin3.8.2
org.apache.maven.pluginsmaven-source-plugin3.0.1
org.apache.maven.pluginsmaven-surefire-plugin3.0.0-M4
org.codehaus.plexusplexus-component-metadata2.0.0
org.eluder.coverallscoveralls-maven-plugin4.3.0
org.jacocojacoco-maven-plugin0.8.5
-

Project Report Plugins

- - - - - - - - - - - - - - - - - - - - -
GroupIdArtifactIdVersion
org.apache.maven.pluginsmaven-checkstyle-plugin3.1.0
org.apache.maven.pluginsmaven-javadoc-plugin3.1.0
org.apache.maven.pluginsmaven-plugin-plugin3.6.0
org.apache.maven.pluginsmaven-project-info-reports-plugin3.0.0
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/project-info.html b/spring-cloud-contract-maven-plugin/project-info.html index 1ea58a9168..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/project-info.html +++ b/spring-cloud-contract-maven-plugin/project-info.html @@ -1,378 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Information - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Information

-

This document provides an overview of the various documents and links that are part of this project's general information. All of this content is automatically generated by Maven on behalf of the project.

-

Overview

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DocumentDescription
CI ManagementThis is a link to the definitions of all continuous integration processes that builds and tests code on a frequent, regular basis.
AboutSpring Cloud Contract Maven Plugin
Issue ManagementThis document provides information on the issue management system used in this project.
LicensesThis document lists the project license(s).
Plugin ManagementThis document lists the plugins that are defined through pluginManagement.
PluginsThis document lists the build plugins and the report plugins used by this project.
TeamThis document provides information on the members of this project. These are the individuals who have contributed to the project in one form or another.
Source Code ManagementThis document lists ways to access the online source repository.
SummaryThis document lists other related information of this project
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/project-reports.html b/spring-cloud-contract-maven-plugin/project-reports.html index 83996e82cd..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/project-reports.html +++ b/spring-cloud-contract-maven-plugin/project-reports.html @@ -1,318 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Generated Reports - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Generated Reports

-

This document provides an overview of the various reports that are automatically generated by Maven . Each report is briefly described below.

-

Overview

- - - - - - - - - - - - -
DocumentDescription
JavadocJavadoc API documentation.
CheckstyleReport on coding style conventions.
Plugin DocumentationThis report provides goals and parameters documentation of a plugin.
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/project-summary.html b/spring-cloud-contract-maven-plugin/project-summary.html index 448ebefd4f..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/project-summary.html +++ b/spring-cloud-contract-maven-plugin/project-summary.html @@ -1,393 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Summary - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Summary

-
-

Project Information

- - - - - - - - - - - - -
FieldValue
NameSpring Cloud Contract Maven Plugin
DescriptionSpring Cloud Contract Maven Plugin
Homepagehttps://github.com/spring-cloud/spring-cloud-contract
-
-

Project Organization

- - - - - - - - - -
FieldValue
NameSpring
URLhttps://spring.io/
-
-

Build Information

- - - - - - - - - - - - - - - - - - -
FieldValue
GroupIdorg.springframework.cloud
ArtifactIdspring-cloud-contract-maven-plugin
Version2.1.0.BUILD-SNAPSHOT
Typemaven-plugin
Java Version1.7
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html b/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html index fe2621d1b5..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html +++ b/spring-cloud-contract-maven-plugin/pushStubsToScm-mojo.html @@ -1,551 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:pushStubsToScm - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:pushStubsToScm

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:pushStubsToScm

- -

Description:

- -
The generated stubs get committed to the SCM repo and pushed to -origin.
- -

Attributes:

- -
    - -
  • Requires a Maven project to be executed.
  • -
-
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<contractsMode>StubRunnerProperties$StubsMode-Picks the mode in which stubs will be found and registered.
Default value is: CLASSPATH.
User property is: contractsMode.
<contractsProperties>Map-Map of properties that can be passed to custom -StubDownloaderBuilder.
User property is: contractsProperties.
<contractsRepositoryPassword>String-The password to be used to connect to the repo with contracts.
User property is: contractsRepositoryPassword.
<contractsRepositoryUrl>String-The URL from which a contracts should get downloaded. If not -provided but artifactid / coordinates notation was provided then -the current Maven's build repositories will be taken into -consideration.
User property is: contractsRepositoryUrl.
<contractsRepositoryUsername>String-The user name to be used to connect to the repo with contracts.
User property is: contractsRepositoryUsername.
<deleteStubsAfterTest>boolean-If set to false will NOT delete stubs from a temporary -folder after running tests.
Default value is: true.
User property is: deleteStubsAfterTest.
<outputDirectory>File-(no description)
Default value is: ${project.build.directory}/stubs.
User property is: stubsDirectory.
<skip>boolean-Set this to "true" to bypass the whole Verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
<taskSkip>boolean-Set this to "true" to bypass only JAR creation.
Default value is: false.
User property is: spring.cloud.contract.verifier.publish-stubs-to-scm.skip.
-
-
-

Parameter Details

-
-

<contractsMode>

- -
Picks the mode in which stubs will be found and registered.
- -
    - -
  • Type: org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties$StubsMode
  • - -
  • Required: No
  • - -
  • User Property: contractsMode
  • - -
  • Default: CLASSPATH
  • -

-

<contractsProperties>

- -
Map of properties that can be passed to custom -StubDownloaderBuilder.
- -
    - -
  • Type: java.util.Map
  • - -
  • Required: No
  • - -
  • User Property: contractsProperties
  • -

-

<contractsRepositoryPassword>

- -
The password to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryPassword
  • -

-

<contractsRepositoryUrl>

- -
The URL from which a contracts should get downloaded. If not -provided but artifactid / coordinates notation was provided then -the current Maven's build repositories will be taken into -consideration.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUrl
  • -

-

<contractsRepositoryUsername>

- -
The user name to be used to connect to the repo with contracts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: contractsRepositoryUsername
  • -

-

<deleteStubsAfterTest>

- -
If set to false will NOT delete stubs from a temporary -folder after running tests.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: deleteStubsAfterTest
  • - -
  • Default: true
  • -

-

<outputDirectory>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: stubsDirectory
  • - -
  • Default: ${project.build.directory}/stubs
  • -

-

<skip>

- -
Set this to "true" to bypass the whole Verifier execution.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skip
  • - -
  • Default: false
  • -

-

<taskSkip>

- -
Set this to "true" to bypass only JAR creation.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.publish-stubs-to-scm.skip
  • - -
  • Default: false
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/run-mojo.html b/spring-cloud-contract-maven-plugin/run-mojo.html index 831bd97c79..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/run-mojo.html +++ b/spring-cloud-contract-maven-plugin/run-mojo.html @@ -1,594 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – spring-cloud-contract:run - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- - - -
-

spring-cloud-contract:run

- -

Full name:

- -

org.springframework.cloud:spring-cloud-contract-maven-plugin:3.0.0-SNAPSHOT:run

- -

Description:

- -
Mojo for running stubs.
- -

Attributes:

- -
    - -
  • Requires dependency resolution of artifacts in scope: runtime.
  • -
-
-

Optional Parameters

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeSinceDescription
<destination>File-(no description)
Default value is: ${basedir}.
User property is: stubsDirectory.
<httpPort>int-HTTP port for the WireMock server that serves stubs.
Default value is: 8080.
User property is: spring.cloud.contract.verifier.http.port.
<maxPort>int-Maximal port at which the stub should start.
Default value is: 15000.
User property is: spring.cloud.contract.verifier.http.maxPort.
<minPort>int-Minimal port at which the stub should start.
Default value is: 10000.
User property is: spring.cloud.contract.verifier.http.minPort.
<serverId>String-(no description)
User property is: spring.cloud.contract.verifier.server-id.
<skip>boolean-Set this to "true" to bypass verifier execution.
Default value is: false.
User property is: spring.cloud.contract.verifier.skip.
<skipTestOnly>boolean-Set this to "true" to bypass verifier test generation.
Default value is: false.
User property is: spring.cloud.contract.verifier.skipTestOnly.
<stubs>String-List of stubs to be downloaded and ran in a colon separated Ivy -notation.
User property is: spring.cloud.contract.verifier.stubs.
<stubsClassifier>String-Classifier used by stubs artifacts.
Default value is: stubs.
<stubsDirectory>File-(no description)
Default value is: ${project.build.directory}/stubs/.
<waitForKeyPressed>boolean-Should the plugin wait for the user to press the key after starting -the stubs.
Default value is: true.
User property is: spring.cloud.contract.verifier.wait-for-key-pressed.
-
-
-

Parameter Details

-
-

<destination>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • User Property: stubsDirectory
  • - -
  • Default: ${basedir}
  • -

-

<httpPort>

- -
HTTP port for the WireMock server that serves stubs.
- -
    - -
  • Type: int
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.http.port
  • - -
  • Default: 8080
  • -

-

<maxPort>

- -
Maximal port at which the stub should start.
- -
    - -
  • Type: int
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.http.maxPort
  • - -
  • Default: 15000
  • -

-

<minPort>

- -
Minimal port at which the stub should start.
- -
    - -
  • Type: int
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.http.minPort
  • - -
  • Default: 10000
  • -

-

<serverId>

- -
(no description)
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.server-id
  • -

-

<skip>

- -
Set this to "true" to bypass verifier execution.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skip
  • - -
  • Default: false
  • -

-

<skipTestOnly>

- -
Set this to "true" to bypass verifier test generation.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.skipTestOnly
  • - -
  • Default: false
  • -

-

<stubs>

- -
List of stubs to be downloaded and ran in a colon separated Ivy -notation.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.stubs
  • -

-

<stubsClassifier>

- -
Classifier used by stubs artifacts.
- -
    - -
  • Type: java.lang.String
  • - -
  • Required: No
  • - -
  • Default: stubs
  • -

-

<stubsDirectory>

- -
(no description)
- -
    - -
  • Type: java.io.File
  • - -
  • Required: No
  • - -
  • Default: ${project.build.directory}/stubs/
  • -

-

<waitForKeyPressed>

- -
Should the plugin wait for the user to press the key after starting -the stubs.
- -
    - -
  • Type: boolean
  • - -
  • Required: No
  • - -
  • User Property: spring.cloud.contract.verifier.wait-for-key-pressed
  • - -
  • Default: true
  • -
-
-
- - -
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/scm.html b/spring-cloud-contract-maven-plugin/scm.html index 23c638488d..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/scm.html +++ b/spring-cloud-contract-maven-plugin/scm.html @@ -1,357 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Source Code Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses Git to manage its source code. Instructions on Git use can be found at https://git-scm.com/documentation.

-

Web Browser Access

-

The following is a link to a browsable version of the source repository:

-
-

Anonymous Access

-

The source can be checked out anonymously from Git with this command (See https://git-scm.com/docs/git-clone):

-
$ git clone https://github.com/spring-cloud/spring-cloud-contract.git
-

Developer Access

-

Only project developers can access the Git tree via this method (See https://git-scm.com/docs/git-clone).

-
$ git clone git@github.com:spring-cloud/spring-cloud-contract.git
-

Access from Behind a Firewall

-

Refer to the documentation of the SCM used for more information about access behind a firewall.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/sitemap.html b/spring-cloud-contract-maven-plugin/sitemap.html index f89aef9306..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/sitemap.html +++ b/spring-cloud-contract-maven-plugin/sitemap.html @@ -1,344 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Sitemap - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Sitemap

- -

This page lists all entries of the navigation menu in expanded form.

-
-

Overview


- - -
-

Related Projects


- - -
-

Project Documentation


- -
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/source-repository.html b/spring-cloud-contract-maven-plugin/source-repository.html index eaf6eba700..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/source-repository.html +++ b/spring-cloud-contract-maven-plugin/source-repository.html @@ -1,359 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Source Code Management - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Overview

-

This project uses Git to manage its source code. Instructions on Git use can be found at https://git-scm.com/documentation.

-
-

Web Browser Access

-

The following is a link to a browsable version of the source repository:

-
-
-

Anonymous Access

-

The source can be checked out anonymously from Git with this command (See https://git-scm.com/docs/git-clone):

-
$ git clone https://github.com/spring-cloud/spring-cloud-contract.git
-
-

Developer Access

-

Only project developers can access the Git tree via this method (See https://git-scm.com/docs/git-clone).

-
$ git clone git@github.com:spring-cloud/spring-cloud-contract.git
-
-

Access from Behind a Firewall

-

Refer to the documentation of the SCM used for more information about access behind a firewall.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/spock.html b/spring-cloud-contract-maven-plugin/spock.html index bb5976cf77..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/spock.html +++ b/spring-cloud-contract-maven-plugin/spock.html @@ -1,400 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Groovy Project with Spock Specifications

-
-
-

Sample minimal configuration for Groovy Project with Spock Specification

-
-
-

Test dependencies for generated contract verification tests

-
-
-
                <dependency>
-                        <groupId>org.spockframework</groupId>
-                        <artifactId>spock-core</artifactId>
-                        <version>1.0-groovy-2.4</version>
-                        <scope>test</scope>
-                </dependency>
-                <dependency>
-                        <groupId>org.springframework.cloud</groupId>
-                        <artifactId>spring-cloud-starter-contract-verifier</artifactId>
-                        <version>${it-plugin.version}</version>
-                        <scope>test</scope>
-                </dependency>
-
-
-
-
-

Project configuration for Spring Cloud Contract Verifier, Groovy, Spock specifications and stub publishing

-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <version>${spring-cloud-verifier-plugin.version}</version>
-                                <extensions>true</extensions>
-                                <configuration>
-                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
-                                        <testFramework>SPOCK</testFramework>
-                                </configuration>
-                        </plugin>
-
-                        <plugin>
-                                <groupId>org.codehaus.gmavenplus</groupId>
-                                <artifactId>gmavenplus-plugin</artifactId>
-                                <executions>
-                                        <execution>
-                                                <goals>
-                                                        <goal>compileTests</goal>
-                                                </goals>
-                                        </execution>
-                                </executions>
-                                <configuration>
-                                        <testSources>
-                                                <testSource>
-                                                        <directory>${project.basedir}/src/test/groovy</directory>
-                                                        <includes>
-                                                                <include>**/*.groovy</include>
-                                                        </includes>
-                                                </testSource>
-                                                <testSource>
-                                                        <directory>
-                                                                ${project.build.directory}/generated-test-sources/contracts
-                                                        </directory>
-                                                        <includes>
-                                                                <include>**/*.groovy</include>
-                                                        </includes>
-                                                </testSource>
-                                        </testSources>
-                                </configuration>
-                        </plugin>
-                        <plugin>
-                                <artifactId>maven-surefire-plugin</artifactId>
-                                <configuration>
-                                        <includes>
-                                                <include>**/*Spec.java</include>
-                                        </includes>
-                                </configuration>
-                        </plugin>
-
-
-
-
-

Base Specification class

-
-
-
/*
- * Copyright 2013-2020 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package hello
-
-import io.restassured.module.mockmvc.RestAssuredMockMvc
-import spock.lang.Specification
-
-class BaseAccurest extends Specification {
-
-        def setup() {
-                RestAssuredMockMvc.standaloneSetup(new GreetingController())
-        }
-
-}
-
-
-
- -
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/summary.html b/spring-cloud-contract-maven-plugin/summary.html index 96c86d3f8a..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/summary.html +++ b/spring-cloud-contract-maven-plugin/summary.html @@ -1,391 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Summary - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Summary

-

Project Information

- - - - - - - - - - - - -
FieldValue
NameSpring Cloud Contract Maven Plugin
DescriptionSpring Cloud Contract Maven Plugin
Homepagehttps://github.com/spring-cloud/spring-cloud-contract
-

Project Organization

- - - - - - - - - -
FieldValue
NameSpring
URLhttps://spring.io/
-

Build Information

- - - - - - - - - - - - - - - - - - -
FieldValue
GroupIdorg.springframework.cloud
ArtifactIdspring-cloud-contract-maven-plugin
Version3.0.0-SNAPSHOT
Typemaven-plugin
Java Version1.8
-

Download

https://github.com/spring-cloud
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/team-list.html b/spring-cloud-contract-maven-plugin/team-list.html index 76fb61feb9..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/team-list.html +++ b/spring-cloud-contract-maven-plugin/team-list.html @@ -1,372 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Team - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Team

-

A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.

-

The project team is comprised of Members and Contributors. Members have direct access to the source of a project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. Get involved today. All contributions to the project are greatly appreciated.

-
-

Members

-

The following is a list of developers with commit privileges that have directly contributed to the project in one way or another.

- - - - - - - - - - - - - - - - - - - - -
ImageIdNameEmail
mariuszsMariusz Smykulamariuszs@gmail.com
marcingrzejszczakMarcin Grzejszczakmgrzejszczak@pivotal.io
dsyerDavid Syerdsyer@pivotal.io
-
-

Contributors

-

There are no contributors listed for this project. Please check back again later.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/team.html b/spring-cloud-contract-maven-plugin/team.html index d99a2e676b..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/team.html +++ b/spring-cloud-contract-maven-plugin/team.html @@ -1,377 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – Project Team - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -
-

Project Team

-

A successful project requires many people to play many roles. Some members write code or documentation, while others are valuable as testers, submitting patches and suggestions.

-

The project team is comprised of Members and Contributors. Members have direct access to the source of a project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. Get involved today. All contributions to the project are greatly appreciated.

-

Members

-

The following is a list of developers with commit privileges that have directly contributed to the project in one way or another.

- - - - - - - - - - - - - - - - - - - - - - - - - -
ImageIdNameEmail
mariuszsMariusz Smykulamariuszs@gmail.com
marcingrzejszczakMarcin Grzejszczakmgrzejszczak@pivotal.io
dsyerDavid Syerdsyer@pivotal.io
OlgaMaciaszekOlga Maciaszek-Sharmaomaciaszeksharma@pivotal.io
-

Contributors

-

There are no contributors listed for this project. Please check back again later.

-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-maven-plugin/usage.html b/spring-cloud-contract-maven-plugin/usage.html index 7045787d1f..9990b6e5bb 100644 --- a/spring-cloud-contract-maven-plugin/usage.html +++ b/spring-cloud-contract-maven-plugin/usage.html @@ -1,362 +1,12 @@ - - - - - - - - - Spring Cloud Contract Maven Plugin – - - - + - - + + - - - - - - - - - - Fork me on GitHub - - - - - + - - - -
- +Page Redirection - - - -
-
- -
- - -
- -

Usage

-
-

Converting Spring Cloud Contract DSL into WireMock stub mappings

-
-
-
-
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert
-
-
-
-

or shortly [1]

-
-
-
-
mvn spring-cloud-contract:convert
-
-
-
-

For more information please go to the Spring Cloud Contract Wiki or Plugin Documentation Site.

-
-
-
-
-

Spring Cloud Contract Stub Runner

-
-
-

Run stubs mappings from current directory:

-
-
-
-
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run
-
-
-
-

or shortly [1]

-
-
-
-
mvn spring-cloud-contract:run
-
-
-
-
-
-

Running stubs from repository

-
-
-
-
mvn spring-cloud-contract:run -Dstubs="org.springframework:gs-rest-service"
-
-
-
-

where org.springframework:gs-rest-service is artifact with stubs classifier contains WireMock mappings.

-
-
-

In order for the goal to be executed correctly, target/stubs subdirectory should be added in the directory from which -the command will be executed.

-
-
-
-
-

Project configuration

-
-
-
-
                        <plugin>
-                                <groupId>org.springframework.cloud</groupId>
-                                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                <version>${spring-cloud-verifier-plugin.version}</version>
-                                <extensions>true</extensions>
-                                <configuration>
-                                        <baseClassForTests>hello.BaseAccurest</baseClassForTests>
-                                </configuration>
-                        </plugin>
-
-
-
-
-
-
-
-1. Additional configuration inside ~/.m2/settings.xml is required: <pluginGroups><pluginGroup>org.springframework.cloud</pluginGroup></pluginGroups>. -
-
-
-
-
- -
- - - - +If you are not redirected automatically, follow the link to docs diff --git a/spring-cloud-contract-shade/dependency-reduced-pom.xml b/spring-cloud-contract-shade/dependency-reduced-pom.xml deleted file mode 100644 index 54d3061d26..0000000000 --- a/spring-cloud-contract-shade/dependency-reduced-pom.xml +++ /dev/null @@ -1,211 +0,0 @@ - - - - spring-cloud-contract-parent - org.springframework.cloud - 2.2.0.BUILD-SNAPSHOT - - 4.0.0 - spring-cloud-contract-shade - Spring Cloud Contract Shaded Dependencies - Spring Cloud Contract Shaded Dependencies - - - - maven-shade-plugin - ${maven-shade-plugin.version} - - - package - - shade - - - true - false - true - true - false - - - com.google - shaded.com.google - - - org.eclipse.aether.connector - shaded.org.eclipse.aether.connector - - - org.eclipse.aether.transport - shaded.org.eclipse.aether.transport - - - org.eclipse.aether.impl - shaded.org.eclipse.aether.impl - - - org.eclipse.aether.internal - shaded.org.eclipse.aether.internal - - - org.eclipse.aether.spi - shaded.org.eclipse.aether.spi - - - org.apache.maven - shaded.org.apache.maven - - - - - - org/slf4j/ - - - - - - - - - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - unpack-dependencies - package - - unpack - - - - - org.springframework.cloud - spring-cloud-contract-shade - ${project.version} - sources - jar - false - ${project.build.directory}/sources - - - **/shaded/**/*.*,**/org/eclipse/**/*.*,**/org/codehaus/plexus/**/*.* - - - - - - org.codehaus.mojo - build-helper-maven-plugin - ${build-helper-maven-plugin.version} - - - add-source - package - - add-source - - - - ${project.build.directory}/sources - - - - - - - maven-surefire-plugin - - false - - - - - - - org.eclipse.sisu - org.eclipse.sisu.inject - 0.1.1 - provided - true - - - org.eclipse.sisu - org.eclipse.sisu.plexus - 0.1.1 - provided - - - cdi-api - javax.enterprise - - - plexus-classworlds - org.codehaus.plexus - - - true - - - org.sonatype.sisu - sisu-guice - 4.2.0 - no_aop - provided - - - aopalliance - aopalliance - - - jsr305 - com.google.code.findbugs - - - guava - com.google.guava - - - true - - - org.ow2.asm - asm - 7.1 - provided - true - - - cglib - cglib - 3.2.9 - provided - - - ant - org.apache.ant - - - true - - - org.checkerframework - checker - 2.8.2 - provided - true - - - - 4.2.0 - 3.2.1 - 4.2.2 - 7.1 - 27.1-jre - 0.1.1 - 1.12 - 2.8.2 - 3.1.1 - 0.1.1 - -