diff --git a/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache b/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache
new file mode 100644
index 0000000000..ca8988965c
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache
@@ -0,0 +1 @@
+{"checksum":"23a7e5a52b04e1a55f2d102255d7ea04","width":886,"height":676}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache b/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache
new file mode 100644
index 0000000000..a17e22fcb1
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"c9ffba1bc9383435e35a7973e5641dd8","width":1213,"height":1341}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache b/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache
new file mode 100644
index 0000000000..2f99cba6c4
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache
@@ -0,0 +1 @@
+{"checksum":"30b3d3322b3ecb24a6c5346a8571ba98","width":815,"height":618}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache b/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache
new file mode 100644
index 0000000000..5a3310d3c6
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"37241bc45c73dbad7383a4733a05d559","width":930,"height":810}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache b/reference/html/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache
new file mode 100644
index 0000000000..2d6b2f9d08
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"b137ec966db7960885422f991695d28f","width":783,"height":677}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache b/reference/html/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache
new file mode 100644
index 0000000000..eac3cd74e2
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache
@@ -0,0 +1 @@
+{"checksum":"a46f733654d99c8861184f0e4e04bb95","width":590,"height":685}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/getting-started-cdc-client.png.cache b/reference/html/.asciidoctor/diagram/getting-started-cdc-client.png.cache
new file mode 100644
index 0000000000..89ce0d961d
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/getting-started-cdc-client.png.cache
@@ -0,0 +1 @@
+{"checksum":"b1418561d3b01d5d71885b4b7bb1be93","width":1138,"height":1223}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/getting-started-cdc-server.png.cache b/reference/html/.asciidoctor/diagram/getting-started-cdc-server.png.cache
new file mode 100644
index 0000000000..0b7b2d7806
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/getting-started-cdc-server.png.cache
@@ -0,0 +1 @@
+{"checksum":"7a8cb19e9d604071d61e4aa9201ee623","width":688,"height":903}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/getting-started-three-second.png.cache b/reference/html/.asciidoctor/diagram/getting-started-three-second.png.cache
new file mode 100644
index 0000000000..3e5f4a8ff5
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/getting-started-three-second.png.cache
@@ -0,0 +1 @@
+{"checksum":"27396daead141eee677aa6311403d175","width":986,"height":704}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/how-to-common-repo.png.cache b/reference/html/.asciidoctor/diagram/how-to-common-repo.png.cache
new file mode 100644
index 0000000000..c23499f956
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/how-to-common-repo.png.cache
@@ -0,0 +1 @@
+{"checksum":"89bbfd25e4c214245543ed34208e2afa","width":1588,"height":1421}
\ No newline at end of file
diff --git a/reference/html/.asciidoctor/diagram/rest-docs.png.cache b/reference/html/.asciidoctor/diagram/rest-docs.png.cache
new file mode 100644
index 0000000000..74da30c065
--- /dev/null
+++ b/reference/html/.asciidoctor/diagram/rest-docs.png.cache
@@ -0,0 +1 @@
+{"checksum":"e3500a52c420af0a5337450779a25536","width":1237,"height":835}
\ No newline at end of file
diff --git a/reference/html/README.html b/reference/html/README.html
index 3dfbe5ed6d..2e5526be54 100644
--- a/reference/html/README.html
+++ b/reference/html/README.html
@@ -100,7 +100,7 @@ $(addBlockSwitches);
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
+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.
@@ -486,9 +466,9 @@ Remember to set the Scan Scope to All sources since we
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.
+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.
@@ -513,7 +493,7 @@ have Docker installed.
-If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed.
+If you want to run the build in offline mode, you must have Maven 3.5.2+ installed.
@@ -521,7 +501,7 @@ If you want to run the build in offline mode, you have to have Maven 3.5.2+ inst
To build the core functionality together with Maven Plugin you can run
+
To build the core functionality together with the Maven Plugin, you can run the following
+command:
@@ -602,11 +586,12 @@ If you want to run the build in offline mode, you have to have Maven 3.5.2+ inst
-
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).
+
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 the Gradle Plugin only
+
To build only the Gradle Plugin, you can run the following commands:
@@ -618,10 +603,11 @@ standalone samples in proper order (both for Maven and Gradle).
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:
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;
+
+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[]
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:
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.
+
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:
/*
+ * 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.
+
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
+ }
+ };
+ }
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).
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:
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:
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:
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:
+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.
+
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.
+
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:
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.
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.
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:
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_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.
+
+
+
+
+
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.
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:
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.
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.
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.
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
diff --git a/reference/html/documentation-overview.html b/reference/html/documentation-overview.html
new file mode 100644
index 0000000000..92d2337dae
--- /dev/null
+++ b/reference/html/documentation-overview.html
@@ -0,0 +1,372 @@
+
+
+
+
+
+
+
+Spring Cloud Contract Documentation
+
+
+
+
+
+
+
+
+
+
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.
+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.
+
+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.
+
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.
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:
+
+
+
+
+
+
+
+
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.
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.
+
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-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`
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:
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 information 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.
+You can now merge the changes, and you can publish both the application and the stub artifacts
+in an online repository.
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:
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:
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:
+Use the REMOTEstubsMode 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.
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:
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.
+
+
+
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:
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
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 information needed 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
+the following example shows:
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:
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:
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:
+Use the REMOTEstubsMode 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}]
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
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.
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.
+
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-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 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.
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:
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] 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.
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):
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).
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.
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.
+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-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 the following output:
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:
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.
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.
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:
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.
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:
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:
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:
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.
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.
+
+
+
+
+
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.
+
+
+
+
+
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.
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:
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.
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
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:
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:
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.
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.
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:
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
diff --git a/reference/html/howto.html b/reference/html/howto.html
new file mode 100644
index 0000000000..ce0e38f66b
--- /dev/null
+++ b/reference/html/howto.html
@@ -0,0 +1,2508 @@
+
+
+
+
+
+
+
+“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.
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.
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:
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:
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:
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.
+
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.
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:
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:
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:
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.
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:
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:
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-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 uses the assembly plugin to build the JAR with all the contracts. The following example
+shows such a setup:
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:
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.
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:
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.
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.
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:
+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.
+
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):
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.
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:
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")
+
+
+
+
+
+
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.
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://${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 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.
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.
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:
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.
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.
+
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.
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" }).
Spring Cloud Contract can read the Pact JSON definition. You can place the file in the
+src/test/resources/contracts folder. The following example shows such a Pact contract:
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:
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:
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. The following listing shows how to do so for both
+Maven and Gradle:
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:
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.
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.
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:
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 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:
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:
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.
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.
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:
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:
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.
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):
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.
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.
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.
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/reference/html/images/flow-overview-consumer-cdc-external-consumer.png b/reference/html/images/flow-overview-consumer-cdc-external-consumer.png
new file mode 100644
index 0000000000..6304c4a33d
Binary files /dev/null and b/reference/html/images/flow-overview-consumer-cdc-external-consumer.png differ
diff --git a/reference/html/images/flow-overview-consumer-cdc-external-producer.png b/reference/html/images/flow-overview-consumer-cdc-external-producer.png
new file mode 100644
index 0000000000..df52a24114
Binary files /dev/null and b/reference/html/images/flow-overview-consumer-cdc-external-producer.png differ
diff --git a/reference/html/images/flows-provider-non-jvm-consumer.png b/reference/html/images/flows-provider-non-jvm-consumer.png
new file mode 100644
index 0000000000..0390d902a0
Binary files /dev/null and b/reference/html/images/flows-provider-non-jvm-consumer.png differ
diff --git a/reference/html/images/flows-provider-non-jvm-producer.png b/reference/html/images/flows-provider-non-jvm-producer.png
new file mode 100644
index 0000000000..98d31a4856
Binary files /dev/null and b/reference/html/images/flows-provider-non-jvm-producer.png differ
diff --git a/reference/html/images/flows-provider-rest-docs-producer.png b/reference/html/images/flows-provider-rest-docs-producer.png
new file mode 100644
index 0000000000..9f9ccd432c
Binary files /dev/null and b/reference/html/images/flows-provider-rest-docs-producer.png differ
diff --git a/reference/html/images/getting-started-cdc-client-final.png b/reference/html/images/getting-started-cdc-client-final.png
new file mode 100644
index 0000000000..4736d615c6
Binary files /dev/null and b/reference/html/images/getting-started-cdc-client-final.png differ
diff --git a/reference/html/images/getting-started-cdc-client.png b/reference/html/images/getting-started-cdc-client.png
new file mode 100644
index 0000000000..447d7ecfdf
Binary files /dev/null and b/reference/html/images/getting-started-cdc-client.png differ
diff --git a/reference/html/images/getting-started-cdc-server.png b/reference/html/images/getting-started-cdc-server.png
new file mode 100644
index 0000000000..7dadee02cf
Binary files /dev/null and b/reference/html/images/getting-started-cdc-server.png differ
diff --git a/reference/html/images/getting-started-three-second.png b/reference/html/images/getting-started-three-second.png
new file mode 100644
index 0000000000..f04d2a1c7a
Binary files /dev/null and b/reference/html/images/getting-started-three-second.png differ
diff --git a/reference/html/images/how-to-common-repo.png b/reference/html/images/how-to-common-repo.png
new file mode 100644
index 0000000000..3f4fbd5db3
Binary files /dev/null and b/reference/html/images/how-to-common-repo.png differ
diff --git a/reference/html/images/rest-docs.png b/reference/html/images/rest-docs.png
new file mode 100644
index 0000000000..2ab7d3d3f1
Binary files /dev/null and b/reference/html/images/rest-docs.png differ
diff --git a/reference/html/index.html b/reference/html/index.html
index 8a5b0421d5..7fc936cdf6 100644
--- a/reference/html/index.html
+++ b/reference/html/index.html
@@ -5,7 +5,8 @@
-Spring Cloud Contract
+
+Spring Cloud Contract Reference Documentation
@@ -90,15013 +91,79 @@ $(addBlockSwitches);
-
+
+Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
-
Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak,
-Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
+
The reference documentation consists of the following sections:
You need confidence when pushing new features to a new application or service in a
-distributed system. This project provides support for Consumer Driven Contracts and
-service schemas in Spring applications (for both HTTP and message-based interactions),
-covering a range of options for writing tests, publishing them as assets, and asserting
-that a contract is kept by producers and consumers.
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.
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.
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.
-
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:
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.
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:
-Use the REMOTEstubsMode 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.
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:
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:
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:
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:
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:
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.
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:
-Use the REMOTEstubsMode 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}]
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`
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.
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.
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:
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.
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.
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.
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
[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):
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.
-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:
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:
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:
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.
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.
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
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
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
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:
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:
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):
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.
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
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
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.
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):
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.
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:
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.
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.
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.
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.
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.
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):
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.
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:
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
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
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.
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
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
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.
-
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
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.
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
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
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.
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.
Add the additional snapshot repository to your build.gradle to use snapshot versions,
-which are automatically uploaded after every successful build, as shown here:
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:
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.
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.
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.
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:
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.
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.
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.
LoanApplication makes a call to FraudDetection service. This request is handled by a
-WireMock server configured with stubs generated by Spring Cloud Contract Verifier.
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:
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.
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.
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 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.
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:
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.
The Spring Cloud Contract Maven Plugin generates verification code in a directory called
-/generated-test-sources/contractVerifier and attaches this directory to testCompile
-goal.
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.
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>
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:
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:
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.
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:
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.
-
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.
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:
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
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.
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.
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:
-
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:
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).
-
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.
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
- }
- }
-}
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.
Add the additional snapshot repository to your build.gradle file to use snapshot
-versions, which are automatically uploaded after every successful build:
The easiest approach would be to centralize the way stubs are kept. For example, you can
-keep them as jars in a Maven repository.
-
-
-
-
-
-
-
-
-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
- }
- }
-}
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.
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
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:
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 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
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:
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();
-
-}
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.
-
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.
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.
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.
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.
The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing
-
-
-
-
-
DiscoveryClient
-
-
-
RibbonServerList
-
-
-
-
-
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'
-}
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");
- }
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
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.
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.
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.
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.
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.
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
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:
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.
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.
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.
-
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.
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
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 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.
-
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:
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.
It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath.
-Remember to annotate your test class with @AutoConfigureStubRunner.
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.
You can have both Spring Integration and Spring Cloud Contract Stub Runner on the
-classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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.
-
You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the
-classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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.
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.
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"
- ])
- }
-}
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
-
-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.
-
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.
-
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:
/*
- * 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())
- }
- }
-}
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.
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.
-
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
- }
-}
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
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:
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.
-
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.
-
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:
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.
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:
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:
-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
-
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 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' }}}
-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.
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
-
-
/*
- * 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.
-
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
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]:
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}'))))
- }
- }
-}
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):
-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.
-
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.
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:
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:
-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.
-
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.
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).
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:
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.
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.
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):
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.
---
-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:
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.
-
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.
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:
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[]
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:
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.
-
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).
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:
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" }
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.
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.
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:
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:
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:
-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.
+
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.
+
+
About the Documentation, Getting Help, First Steps, and more.
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
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
The Spring Cloud Contract WireMock modules let you use WireMock in a
-Spring Boot application. Check out the
-samples
-for more details.
-
-
-
If you have a Spring Boot application that uses Tomcat as an embedded server (which is
-the default with spring-boot-starter-web), you can add
-spring-cloud-starter-contract-stub-runner to your classpath and add @AutoConfigureWireMock in
-order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you
-can register stub behavior using a Java API or via static JSON declarations as part of
-your test. The following code shows an example:
-
-
-
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
-@AutoConfigureWireMock(port = 0)
-public class WiremockForDocsTests {
-
- // A service that calls out over HTTP
- @Autowired
- private Service service;
-
- @Before
- public void setup() {
- this.service.setBase("http://localhost:"
- + this.environment.getProperty("wiremock.server.port"));
- }
-
- // Using the WireMock APIs in the normal way:
- @Test
- public void contextLoads() throws Exception {
- // Stubbing WireMock
- stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
- .withHeader("Content-Type", "text/plain").withBody("Hello World!")));
- // We're asserting if WireMock responded properly
- assertThat(this.service.go()).isEqualTo("Hello World!");
- }
-
-}
-
-
-
-
To start the stub server on a different port use (for example),
-@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub
-server port can be bound in the test application context with the "wiremock.server.port"
-property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to
-your test application context, where it will be cached in between methods and classes
-having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.
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:
-Actually, WireMock always loads mappings from src/test/resources/mappingsas
-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.
+
+
Introducing Spring Cloud Contract, Developing Your First Spring Cloud Contract-based Application
-
-
-
-
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.
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.
+
+
Spring Cloud Contract usage examples and workflows
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.
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:
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.
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
-a Spring MockRestServiceServer. The following code shows an example:
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).
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
- }
- };
- }
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:
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:
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:
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:
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:
-You can use either the wiremock() method or the jsonPath() and contentType()
-methods to create request matchers, but you can’t use both approaches.
+
+
Contract DSL, Messaging, Spring Cloud Contract Stub Runner, and Spring Cloud Contract WireMock.
-
-
-
-
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.
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.
+
The generated document (formatted in Asciidoc in this case) contains a formatted
-contract. The location of this file would be index/dsl-contract.adoc.
In 1.1.x we have introduced a change to the structure of generated stubs. If you have
-been using the @AutoConfigureWireMock notation to use the stubs from the classpath,
-it no longer works. The following example shows how the @AutoConfigureWireMock notation
-used to work:
-
-
-
-
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
-
-
-
-
You must either change the location of the stubs to:
-classpath:…/META-INF/groupId/artifactId/version/mappings or use the new
-classpath-based @AutoConfigureStubRunner, as shown in the following example:
-
-
-
-
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
-
-
-
-
If you do not want to use @AutoConfigureStubRunner and you want to remain with the old
-structure, set your plugin tasks accordingly. The following example would work for the
-structure presented in the previous snippet.
-
-
-
Maven
-
-
<!-- start of pom.xml -->
-
-<properties>
- <!-- we don't want the verifier to do a jar for us -->
- <spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
-</properties>
-
-<!-- ... -->
-
-<!-- You need to set up the assembly plugin -->
-<build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>stub</id>
- <phase>prepare-package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- <inherited>false</inherited>
- <configuration>
- <attach>true</attach>
- <descriptor>${basedir}/src/assembly/stub.xml</descriptor>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
-</build>
-<!-- end of pom.xml -->
-
-<!-- start of stub.xml-->
-
-<assembly
- xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
- <id>stubs</id>
- <formats>
- <format>jar</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <fileSets>
- <fileSet>
- <directory>${project.build.directory}/snippets/stubs</directory>
- <outputDirectory>customer-stubs/mappings</outputDirectory>
- <includes>
- <include>**/*</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>${basedir}/src/test/resources/contracts</directory>
- <outputDirectory>customer-stubs/contracts</outputDirectory>
- <includes>
- <include>**/*.groovy</include>
- </includes>
- </fileSet>
- </fileSets>
-</assembly>
-
-<!-- end of stub.xml-->
-
-
-
-
Gradle
-
-
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
-// Preserve directory structure from 1.0.X of spring-cloud-contract
- from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
- into "${project.buildDir}/resources/main/customer-stubs"
-}
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.
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).
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
diff --git a/reference/html/maven-project.html b/reference/html/maven-project.html
new file mode 100644
index 0000000000..5e39802736
--- /dev/null
+++ b/reference/html/maven-project.html
@@ -0,0 +1,1039 @@
+
+
+
+
+
+
+
+Maven Project
+
+
+
+
+
+
+
+
+
+
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:
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:
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.
+
+
+
+
+
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.
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:
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:
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.
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
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:
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:
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.
The Spring Cloud Contract Maven Plugin generates verification code in a directory called
+/generated-test-sources/contractVerifier and attaches this directory to testCompile
+goal.
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.
The following image shows an exception that you may see when you use STS:
+
+
+
+
+
+
+
+
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>
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:
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:
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.
Spring Cloud Contract supports the DSLs written in the following languages:
+
+
+
+
+
Groovy
+
+
+
YAML
+
+
+
+
+
+
+
+
+
+
+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 { … }.
+
+
+
+
+
+
+
+
+
+
+
+Spring Cloud Contract supports defining multiple contracts in a single file.
+
+
+
+
+
+
The following example shows a contract definition:
+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.
+
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:
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:
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:
/*
+ * 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())
+ }
+ }
+}
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 Groovy DSL or a bodyFromFileAsBytes field in YAML.
+
+
+
The following example shows how to pass the contents of binary files:
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.
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:
+...
+
+
+
+
+
+
+
+
+
+
+
+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.
+
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:
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+ }
+}
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 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:
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
+
+
+
+
+
+
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.
+
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.
+
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:
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.
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:
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:
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:
+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.
+
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:
+
+
+
+
method GET()
+
+
+
+
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, 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:
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, 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' }}}
+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.
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:
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.
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:
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}'))))
+ }
+ }
+}
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):
+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, 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.
+
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.
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:
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:
---
+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 the following:
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.
+
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:
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:
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:
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:
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.
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).
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.
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:
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:
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:
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:
+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.
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.
+
The generated document (formatted in Asciidoc in this case) contains a formatted
+contract. The location of this file would be index/dsl-contract.adoc.
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.
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.
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.
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):
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.
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, the messaging part of Spring Cloud Contract 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 follows:
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:
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).
+
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.
+
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:
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.
You can have both Apache Camel and Spring Cloud Contract Stub Runner on the classpath.
+Remember to annotate your test class with @AutoConfigureStubRunner.
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.
You can have both Spring Integration and Spring Cloud Contract Stub Runner on the
+classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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:
You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the
+classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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.
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.
+
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"
+ ])
+ }
+}
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:
The binding definition binds the queue called test.queue. As a result, the following listener
+definition is matched and invoked with the contract message:
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.
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:
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
+ }
+ }
+}
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.
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:
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:
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:
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:
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:
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:
+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.
+
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.
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.
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:
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:
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.
The most important feature of Stub Runner Spring Cloud is the fact that it stubs:
+
+
+
+
+
DiscoveryClient
+
+
+
RibbonServerList
+
+
+
+
+
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:
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");
+ }
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
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.
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.
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):
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.
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):
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
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:
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:
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.
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.
@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 .
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.
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.
You can set repetitive properties by using system properties or Spring configuration
+properties. The following table shows their names with their default values:
+
+
+
+
+
+
+
+
+
+
Property name
+
Default value
+
Description
+
+
+
+
+
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.
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.
+
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:
+
+
+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+ // A service that calls out over HTTP
+ @Autowired
+ private Service service;
+
+ @Before
+ public void setup() {
+ this.service.setBase("http://localhost:"
+ + this.environment.getProperty("wiremock.server.port"));
+ }
+
+ // Using the WireMock APIs in the normal way:
+ @Test
+ public void contextLoads() throws Exception {
+ // Stubbing WireMock
+ stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+ .withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+ // We're asserting if WireMock responded properly
+ assertThat(this.service.go()).isEqualTo("Hello World!");
+ }
+
+}
+
+
+
+
+
+
To start the stub server on a different port, use (for example),
+@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub
+server port can be bound in the test application context with the "wiremock.server.port"
+property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to
+your test application context, where it 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.
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 byusing 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:
+Actually, WireMock always loads mappings from src/test/resources/mappingsas
+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:
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.
+
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:
+
+
+
+
+
+
@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.
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:
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.
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
+a Spring MockRestServiceServer. The following code shows an example:
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).
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.
As long as Spring Cloud Sleuth is on the classpath any Spring Boot application will generate trace data:
+
As long as Spring Cloud Sleuth is on the classpath, any Spring Boot application can
+generate trace data. The following example shows how to do so:
+
+
-
@SpringBootApplication
+
@SpringBootApplication
@RestController
public class Application {
@@ -167,11 +197,16 @@ public class Application {
SpringApplication.run(Application.class, args);
}
-}
+}
+
+
-
Run this app and then hit the home page. You will see traceId and spanId populated in the logs. If this app calls out to another one (e.g. with RestTemplate) it will send the trace data in headers and if the receiver is another Sleuth app you will see the trace continue there.
+
Now you can run this application and visit the home page. In the logs, you can see
+traceId and spanId populated. If this application calls out to another one (for
+example, with RestTemplate), it sends the trace data in headers, and, if the receiver is
+another Sleuth application, you can see the trace continue there.
@@ -180,7 +215,8 @@ public class Application {
-instead of logging the request in the handler explicitly, you could set logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG
+instead of logging the request in the handler explicitly, you could set
+logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG
@@ -192,7 +228,10 @@ instead of logging the request in the handler explicitly, you could set lo
-If you use Zipkin, configure the probability of spans exported by setting (for 2.0.x) spring.sleuth.sampler.probability or (up till 2.0.x)spring.sleuth.sampler.percentage (default: 0.1, which is 10 percent). Otherwise, you might think that Sleuth is not working because it omits some spans.
+If you use Zipkin, you can configure the probability of spans being exported by
+setting (for 2.0.x) spring.sleuth.sampler.probability or (up till 2.0.x)
+spring.sleuth.sampler.percentage (default: 0.1, which is 10 percent). Otherwise, you
+might think that Sleuth is not working because it omits some spans.
@@ -204,7 +243,8 @@ If you use Zipkin, configure the probability of spans exported by setting (for <
-Set spring.application.name=bar (for instance) to see the service name as well as the trace and span ids.
+Set spring.application.name=bar (for instance) to see the service name as
+well as the trace and span IDs.
@@ -212,6 +252,7 @@ Set spring.application.name=bar (for instance) to see the service n
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from Dapper, Zipkin and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service.
+
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing
+heavily from Dapper,
+Zipkin, and HTrace. For most users, Sleuth should be
+invisible, and all your interactions with external systems should be instrumented
+automatically. You can capture data in logs or by sending it to a remote collector service.
A Span is the basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Span’s are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, key-value annotations, the ID of the span that caused them, and process ID’s (normally IP address). Spans are started and stopped, and they keep track of their timing information. Once you create a span, you must stop it at some point in the future. A set of spans forming a tree-like structure called a Trace. For example, if you are running a distributed big-data store, a trace might be formed by a put request.
+
A span is the basic unit of work. For example, sending an RPC is a new span, as is sending
+a response to an RPC. Spans are identified by a unique 64-bit ID for the span and another
+64-bit ID for the trace of which the span is a part. Spans also have other data, such as
+descriptions, key-value annotations, the ID of the span that caused them, and process IDs
+(normally IP addresses). Spans are started and stopped, and they keep track of their
+timing information. Once you create a span, you must stop it at some point in the future.
+A set of spans (which form a tree-like structure) is called a trace. For example, if you
+run a distributed big-data store, a trace might be formed by a PUT request.
-
Spring Cloud Sleuth features:
+
Spring Cloud Sleuth:
-
Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator.
+
Adds trace and span IDs to the Slf4J MDC so that you can extract all the logs from a
+given trace or span in a log aggregator.
-
Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible.
+
Provides an abstraction over common distributed tracing data models: traces, spans
+(forming a DAG), annotations, and key-value annotations. This is loosely based on HTrace
+but is Zipkin (Dapper) compatible.
-
Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client).
+
Instruments common ingress and egress points from Spring applications (servlet filter,
+rest template, scheduled actions, message channels, zuul filters, and the feign client).
-
If spring-cloud-sleuth-zipkin is available then the app will generate and collect Zipkin-compatible traces via HTTP. By default it sends them to a Zipkin collector service on localhost (port 9411). Configure the location of the service using spring.zipkin.baseUrl.
+
If spring-cloud-sleuth-zipkin is available, the app generates and collects
+Zipkin-compatible traces over HTTP. By default, it sends them to a Zipkin collector
+service on localhost (port 9411). You can configure the location of the service using
+spring.zipkin.baseUrl.
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.
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).
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:
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.
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:
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. -->
+
+ <!-- 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.
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:
+
+
+
+
+
The consumer works with the contract definitions from the separate repository
+
+
+
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.
+
+
+
The producer takes over the pull request to the separate repository with contract
+definitions and installs the JAR with all contracts locally.
+
+
+
The producer generates tests from the locally stored JAR and writes the missing
+implementation to make the tests pass.
+
+
+
Once the producer’s work is done, the pull request to the repository that holds the
+contract definitions is merged.
+
+
+
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.
+
+
+
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.
Writes a test that would send a request to the producer.
+
+
The test fails due to no server being present.
+
+
+
+
Clones the repository that holds the contract definitions.
+
+
+
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/)
+
+
+
+
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
+
+
+
+
+
+
+
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
+
+
+
+
+
+
+
+
The following UML diagram shows the consumer flow:
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
+}
+
+
+
+
+
+
+
Runs the build to generate tests and stubs, as follows:
+
+
+
+
Maven
+
+
./mvnw clean install
+
+
+
+
Gradle
+
+
./gradlew clean build
+
+
+
+
+
+
+
Writes the missing implementation, to make the tests pass.
+
+
+
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
+
+
+
+
+
+
+
The CI system builds the project with the contract definitions and uploads the JAR with
+the contract definitions to Nexus or Artifactory.
+
+
+
Switches to working remotely.
+
+
+
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
+}
+
+
+
+
+
+
+
Merges the producer code with the new implementation.
+
+
+
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.
+
+
+
+
+
+
+
+
The following UML diagram shows the producer process:
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);
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.
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.
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.
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)
+
+
+
+
+
+
+
+
+
Now, when we run the tests, stubs are automatically published and packaged.
+
+
+
The following UML diagram shows the producer 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.
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache b/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache
new file mode 100644
index 0000000000..ca8988965c
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-consumer.png.cache
@@ -0,0 +1 @@
+{"checksum":"23a7e5a52b04e1a55f2d102255d7ea04","width":886,"height":676}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache b/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache
new file mode 100644
index 0000000000..a17e22fcb1
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/flow-overview-consumer-cdc-external-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"c9ffba1bc9383435e35a7973e5641dd8","width":1213,"height":1341}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache
new file mode 100644
index 0000000000..2f99cba6c4
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-consumer.png.cache
@@ -0,0 +1 @@
+{"checksum":"30b3d3322b3ecb24a6c5346a8571ba98","width":815,"height":618}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache
new file mode 100644
index 0000000000..5a3310d3c6
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-non-jvm-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"37241bc45c73dbad7383a4733a05d559","width":930,"height":810}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache
new file mode 100644
index 0000000000..2d6b2f9d08
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/flows-provider-rest-docs-producer.png.cache
@@ -0,0 +1 @@
+{"checksum":"b137ec966db7960885422f991695d28f","width":783,"height":677}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache
new file mode 100644
index 0000000000..eac3cd74e2
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client-final.png.cache
@@ -0,0 +1 @@
+{"checksum":"a46f733654d99c8861184f0e4e04bb95","width":590,"height":685}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client.png.cache b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client.png.cache
new file mode 100644
index 0000000000..89ce0d961d
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-client.png.cache
@@ -0,0 +1 @@
+{"checksum":"b1418561d3b01d5d71885b4b7bb1be93","width":1138,"height":1223}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-server.png.cache b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-server.png.cache
new file mode 100644
index 0000000000..0b7b2d7806
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/getting-started-cdc-server.png.cache
@@ -0,0 +1 @@
+{"checksum":"7a8cb19e9d604071d61e4aa9201ee623","width":688,"height":903}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/getting-started-three-second.png.cache b/reference/htmlsingle/.asciidoctor/diagram/getting-started-three-second.png.cache
new file mode 100644
index 0000000000..3e5f4a8ff5
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/getting-started-three-second.png.cache
@@ -0,0 +1 @@
+{"checksum":"27396daead141eee677aa6311403d175","width":986,"height":704}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/how-to-common-repo.png.cache b/reference/htmlsingle/.asciidoctor/diagram/how-to-common-repo.png.cache
new file mode 100644
index 0000000000..c23499f956
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/how-to-common-repo.png.cache
@@ -0,0 +1 @@
+{"checksum":"89bbfd25e4c214245543ed34208e2afa","width":1588,"height":1421}
\ No newline at end of file
diff --git a/reference/htmlsingle/.asciidoctor/diagram/rest-docs.png.cache b/reference/htmlsingle/.asciidoctor/diagram/rest-docs.png.cache
new file mode 100644
index 0000000000..74da30c065
--- /dev/null
+++ b/reference/htmlsingle/.asciidoctor/diagram/rest-docs.png.cache
@@ -0,0 +1 @@
+{"checksum":"e3500a52c420af0a5337450779a25536","width":1237,"height":835}
\ No newline at end of file
diff --git a/reference/htmlsingle/images/flow-overview-consumer-cdc-external-consumer.png b/reference/htmlsingle/images/flow-overview-consumer-cdc-external-consumer.png
new file mode 100644
index 0000000000..6304c4a33d
Binary files /dev/null and b/reference/htmlsingle/images/flow-overview-consumer-cdc-external-consumer.png differ
diff --git a/reference/htmlsingle/images/flow-overview-consumer-cdc-external-producer.png b/reference/htmlsingle/images/flow-overview-consumer-cdc-external-producer.png
new file mode 100644
index 0000000000..df52a24114
Binary files /dev/null and b/reference/htmlsingle/images/flow-overview-consumer-cdc-external-producer.png differ
diff --git a/reference/htmlsingle/images/flows-provider-non-jvm-consumer.png b/reference/htmlsingle/images/flows-provider-non-jvm-consumer.png
new file mode 100644
index 0000000000..0390d902a0
Binary files /dev/null and b/reference/htmlsingle/images/flows-provider-non-jvm-consumer.png differ
diff --git a/reference/htmlsingle/images/flows-provider-non-jvm-producer.png b/reference/htmlsingle/images/flows-provider-non-jvm-producer.png
new file mode 100644
index 0000000000..98d31a4856
Binary files /dev/null and b/reference/htmlsingle/images/flows-provider-non-jvm-producer.png differ
diff --git a/reference/htmlsingle/images/flows-provider-rest-docs-producer.png b/reference/htmlsingle/images/flows-provider-rest-docs-producer.png
new file mode 100644
index 0000000000..9f9ccd432c
Binary files /dev/null and b/reference/htmlsingle/images/flows-provider-rest-docs-producer.png differ
diff --git a/reference/htmlsingle/images/getting-started-cdc-client-final.png b/reference/htmlsingle/images/getting-started-cdc-client-final.png
new file mode 100644
index 0000000000..4736d615c6
Binary files /dev/null and b/reference/htmlsingle/images/getting-started-cdc-client-final.png differ
diff --git a/reference/htmlsingle/images/getting-started-cdc-client.png b/reference/htmlsingle/images/getting-started-cdc-client.png
new file mode 100644
index 0000000000..447d7ecfdf
Binary files /dev/null and b/reference/htmlsingle/images/getting-started-cdc-client.png differ
diff --git a/reference/htmlsingle/images/getting-started-cdc-server.png b/reference/htmlsingle/images/getting-started-cdc-server.png
new file mode 100644
index 0000000000..7dadee02cf
Binary files /dev/null and b/reference/htmlsingle/images/getting-started-cdc-server.png differ
diff --git a/reference/htmlsingle/images/getting-started-three-second.png b/reference/htmlsingle/images/getting-started-three-second.png
new file mode 100644
index 0000000000..f04d2a1c7a
Binary files /dev/null and b/reference/htmlsingle/images/getting-started-three-second.png differ
diff --git a/reference/htmlsingle/images/how-to-common-repo.png b/reference/htmlsingle/images/how-to-common-repo.png
new file mode 100644
index 0000000000..3f4fbd5db3
Binary files /dev/null and b/reference/htmlsingle/images/how-to-common-repo.png differ
diff --git a/reference/htmlsingle/images/rest-docs.png b/reference/htmlsingle/images/rest-docs.png
new file mode 100644
index 0000000000..2ab7d3d3f1
Binary files /dev/null and b/reference/htmlsingle/images/rest-docs.png differ
diff --git a/reference/htmlsingle/index.html b/reference/htmlsingle/index.html
new file mode 100644
index 0000000000..331fd21248
--- /dev/null
+++ b/reference/htmlsingle/index.html
@@ -0,0 +1,14911 @@
+
+
+
+
+
+
+
+
+Spring Cloud Contract Reference Documentation
+
+
+
+
+
+
+
+
+
+
+
Spring Cloud Contract Reference Documentation
+
+Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
+
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.
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.
+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.
+
+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.
+
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.
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:
+
+
+
+
+
+
+
+
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.
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.
+
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-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`
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:
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 information 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.
+You can now merge the changes, and you can publish both the application and the stub artifacts
+in an online repository.
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:
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:
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:
+Use the REMOTEstubsMode 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.
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:
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.
+
+
+
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:
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
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 information needed 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
+the following example shows:
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:
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:
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:
+Use the REMOTEstubsMode 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}]
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
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.
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.
+
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-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 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.
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:
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] 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.
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):
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).
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.
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.
+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-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 the following output:
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:
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.
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.
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:
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.
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.
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).
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:
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.
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:
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. -->
+
+ <!-- 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.
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:
+
+
+
+
+
The consumer works with the contract definitions from the separate repository
+
+
+
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.
+
+
+
The producer takes over the pull request to the separate repository with contract
+definitions and installs the JAR with all contracts locally.
+
+
+
The producer generates tests from the locally stored JAR and writes the missing
+implementation to make the tests pass.
+
+
+
Once the producer’s work is done, the pull request to the repository that holds the
+contract definitions is merged.
+
+
+
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.
+
+
+
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.
Writes a test that would send a request to the producer.
+
+
The test fails due to no server being present.
+
+
+
+
Clones the repository that holds the contract definitions.
+
+
+
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/)
+
+
+
+
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
+
+
+
+
+
+
+
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
+
+
+
+
+
+
+
+
The following UML diagram shows the consumer flow:
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
+}
+
+
+
+
+
+
+
Runs the build to generate tests and stubs, as follows:
+
+
+
+
Maven
+
+
./mvnw clean install
+
+
+
+
Gradle
+
+
./gradlew clean build
+
+
+
+
+
+
+
Writes the missing implementation, to make the tests pass.
+
+
+
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
+
+
+
+
+
+
+
The CI system builds the project with the contract definitions and uploads the JAR with
+the contract definitions to Nexus or Artifactory.
+
+
+
Switches to working remotely.
+
+
+
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
+}
+
+
+
+
+
+
+
Merges the producer code with the new implementation.
+
+
+
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.
+
+
+
+
+
+
+
+
The following UML diagram shows the producer process:
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);
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.
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.
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.
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)
+
+
+
+
+
+
+
+
+
Now, when we run the tests, stubs are automatically published and packaged.
+
+
+
The following UML diagram shows the producer 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.
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" and
+"Using Spring Cloud Contract" sections, so that you have a good grounding of the
+basics.
Spring Cloud Contract supports the DSLs written in the following languages:
+
+
+
+
+
Groovy
+
+
+
YAML
+
+
+
+
+
+
+
+
+
+
+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 { … }.
+
+
+
+
+
+
+
+
+
+
+
+Spring Cloud Contract supports defining multiple contracts in a single file.
+
+
+
+
+
+
The following example shows a contract definition:
+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.
+
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:
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:
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:
/*
+ * 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())
+ }
+ }
+}
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 Groovy DSL or a bodyFromFileAsBytes field in YAML.
+
+
+
The following example shows how to pass the contents of binary files:
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.
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:
+...
+
+
+
+
+
+
+
+
+
+
+
+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.
+
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:
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+
+
+
+
+
+
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
+ }
+}
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 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:
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
+
+
+
+
+
+
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.
+
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.
+
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:
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.
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:
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:
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:
+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.
+
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:
+
+
+
+
method GET()
+
+
+
+
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, 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:
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, 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' }}}
+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.
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:
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.
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:
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}'))))
+ }
+ }
+}
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):
+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, 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.
+
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.
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:
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:
---
+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 the following:
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.
+
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:
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:
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:
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:
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.
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).
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.
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:
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:
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:
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:
+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.
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.
+
The generated document (formatted in Asciidoc in this case) contains a formatted
+contract. The location of this file would be index/dsl-contract.adoc.
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.
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.
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.
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):
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.
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, the messaging part of Spring Cloud Contract 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 follows:
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:
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).
+
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.
+
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:
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.
You can have both Apache Camel and Spring Cloud Contract Stub Runner on the classpath.
+Remember to annotate your test class with @AutoConfigureStubRunner.
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.
You can have both Spring Integration and Spring Cloud Contract Stub Runner on the
+classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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:
You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the
+classpath. Remember to annotate your test class with @AutoConfigureStubRunner.
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.
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.
+
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"
+ ])
+ }
+}
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:
The binding definition binds the queue called test.queue. As a result, the following listener
+definition is matched and invoked with the contract message:
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.
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:
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
+ }
+ }
+}
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.
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:
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:
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:
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:
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:
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:
+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.
+
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.
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.
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:
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:
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.
The most important feature of Stub Runner Spring Cloud is the fact that it stubs:
+
+
+
+
+
DiscoveryClient
+
+
+
RibbonServerList
+
+
+
+
+
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:
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");
+ }
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
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.
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.
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):
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.
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):
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
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:
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:
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.
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.
@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 .
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.
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.
You can set repetitive properties by using system properties or Spring configuration
+properties. The following table shows their names with their default values:
+
+
+
+
+
+
+
+
+
+
Property name
+
Default value
+
Description
+
+
+
+
+
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.
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.
+
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:
+
+
+
+
+
+
@RunWith(SpringRunner.class)
+@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@AutoConfigureWireMock(port = 0)
+public class WiremockForDocsTests {
+
+ // A service that calls out over HTTP
+ @Autowired
+ private Service service;
+
+ @Before
+ public void setup() {
+ this.service.setBase("http://localhost:"
+ + this.environment.getProperty("wiremock.server.port"));
+ }
+
+ // Using the WireMock APIs in the normal way:
+ @Test
+ public void contextLoads() throws Exception {
+ // Stubbing WireMock
+ stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
+ .withHeader("Content-Type", "text/plain").withBody("Hello World!")));
+ // We're asserting if WireMock responded properly
+ assertThat(this.service.go()).isEqualTo("Hello World!");
+ }
+
+}
+
+
+
+
+
+
To start the stub server on a different port, use (for example),
+@AutoConfigureWireMock(port=9999). For a random port, use a value of 0. The stub
+server port can be bound in the test application context with the "wiremock.server.port"
+property. Using @AutoConfigureWireMock adds a bean of type WiremockConfiguration to
+your test application context, where it 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.
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 byusing 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:
+Actually, WireMock always loads mappings from src/test/resources/mappingsas
+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:
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.
+
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:
+
+
+
+
+
+
@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.
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:
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.
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
+a Spring MockRestServiceServer. The following code shows an example:
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).
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.
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.
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.
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:
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:
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:
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.
+
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.
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:
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:
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:
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.
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:
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:
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-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 uses the assembly plugin to build the JAR with all the contracts. The following example
+shows such a setup:
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:
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.
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:
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.
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.
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:
+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.
+
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):
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.
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:
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")
+
+
+
+
+
+
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.
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://${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 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.
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.
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:
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.
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.
+
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.
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" }).
Spring Cloud Contract can read the Pact JSON definition. You can place the file in the
+src/test/resources/contracts folder. The following example shows such a Pact contract:
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:
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:
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. The following listing shows how to do so for both
+Maven and Gradle:
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:
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.
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.
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:
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 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:
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:
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.
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.
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:
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:
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.
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):
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.
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.
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.
Display help information on spring-cloud-contract-maven-plugin.
+ Call mvn spring-cloud-contract:help -Ddetail=true -Dgoal=<goal-name> to display parameter details.