Editing pass for the new docs layout

I did a full editing pass on all the asciidoc files.
This commit is contained in:
Jay Bryant
2019-08-06 14:37:41 -05:00
parent 43792f53fb
commit da3a09669c
21 changed files with 2392 additions and 1629 deletions

View File

@@ -7,8 +7,8 @@ Edit the files in the src/main/asciidoc/ directory instead.
== Spring Cloud Contract
You always need confidence when pushing new features into a new application or service in
a distributed system. To that end, this project provides support for Consumer-driven
Contracts and service schemas in Spring applications, covering a range of options for
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.
@@ -204,21 +204,21 @@ Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on t
IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources.
== How to build it
== How to Build Spring Cloud Contract
IMPORTANT: 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.
IMPORTANT: Spring Cloud Contract builds Docker images. Remember to
have Docker installed.
IMPORTANT: If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed.
IMPORTANT: If you want to run the build in offline mode, you must have Maven 3.5.2+ installed.
=== Project structure
Here you can find the Spring Cloud Contract folder structure
The following listing shows the Spring Cloud Contract folder structure:
```
├── config
@@ -237,34 +237,38 @@ Here you can find the Spring Cloud Contract folder structure
└── tests
```
- `config` - folder contains setup for Spring Cloud Release Tools automated release process
- `docker` - folder contains docker images
- `samples` - folder contains test samples together with standalone ones used also to build documentation
- `scripts` - contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
- `specs` - contains specifications for the Contract DSL.
- `spring-cloud-contract-dependencies` - contains Spring Cloud Contract BOM
- `spring-cloud-contract-shade` - shaded dependencies used by the plugins
- `spring-cloud-contract-starters` - contains Spring Cloud Contract Starters
- `spring-cloud-contract-spec` - contains specification modules (contains concept of a Contract)
- `spring-cloud-contract-stub-runner` - contains Stub Runner related modules
- `spring-cloud-contract-stub-runner-boot` - contains Stub Runner Boot app
- `spring-cloud-contract-tools` - Gradle and Maven plugin for `Spring Cloud Contract Verifier`
- `spring-cloud-contract-verifier` - core of the `Spring Cloud Contract Verifier` functionality
- `spring-cloud-contract-wiremock` - all WireMock related functionality
- `tests` - integration tests for different messaging technologies
The following list describes each of the top-level folders in the project structure:
- `config`: Folder contains setup for Spring Cloud Release Tools automated release process
- `docker`: Folder contains docker images
- `samples`: Folder contains test samples together with standalone ones used also to build documentation
- `scripts`: Contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
- `specs`: Contains specifications for the Contract DSL.
- `spring-cloud-contract-dependencies`: Contains Spring Cloud Contract BOM
- `spring-cloud-contract-shade`: Shaded dependencies used by the plugins
- `spring-cloud-contract-starters`: Contains Spring Cloud Contract Starters
- `spring-cloud-contract-spec`: Contains specification modules (contains concept of a Contract)
- `spring-cloud-contract-stub-runner`: Contains Stub Runner related modules
- `spring-cloud-contract-stub-runner-boot`: Contains Stub Runner Boot app
- `spring-cloud-contract-tools`: Gradle and Maven plugin for `Spring Cloud Contract Verifier`
- `spring-cloud-contract-verifier`: Core of the `Spring Cloud Contract Verifier` functionality
- `spring-cloud-contract-wiremock`: All WireMock related functionality
- `tests`: Integration tests for different messaging technologies
=== Commands
To build the core functionality together with Maven Plugin you can run
To build the core functionality together with the Maven Plugin, you can run the following
command:
```
./mvnw clean install -P integration
```
Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the
standalone samples in proper order (both for Maven and Gradle).
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:
```
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
@@ -273,34 +277,37 @@ cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
=== Helpful scripts
We're providing a couple of helpful scripts to build the project.
We provide a couple of helpful scripts to build the project.
To build the project in parallel (by default uses 4 cores but you can change it)
To build the project in parallel (by default, it uses four cores, but you can change it),
run the following command:
```
./scripts/parallelBuild.sh
```
and with 8 cores
To use eight 8 cores, run thke following command:
```
CORES=8 ./scripts/parallelBuild.sh
```
To build the project without any integration tests (by default uses 1 core)
To build the project without any integration tests (by default, this uses one core), run
the following command:
```
./scripts/noIntegration.sh
```
and with 8 cores
To use eight cores, run the following command:
```
CORES=8 ./scripts/noIntegration.sh
```
To generate the documentation (both the root one and the maven plugin one)
To generate the documentation (for both the root project and the maven plugin), run the
following command:
```
./scripts/generateDocs.sh
```
```

View File

@@ -1,8 +1,8 @@
== Spring Cloud Contract
You always need confidence when pushing new features into a new application or service in
a distributed system. To that end, this project provides support for Consumer-driven
Contracts and service schemas in Spring applications, covering a range of options for
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.

View File

@@ -1,18 +1,18 @@
== How to build it
== How to Build Spring Cloud Contract
IMPORTANT: 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.
IMPORTANT: Spring Cloud Contract builds Docker images. Remember to
have Docker installed.
IMPORTANT: If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed.
IMPORTANT: If you want to run the build in offline mode, you must have Maven 3.5.2+ installed.
=== Project structure
Here you can find the Spring Cloud Contract folder structure
The following listing shows the Spring Cloud Contract folder structure:
```
├── config
@@ -31,34 +31,38 @@ Here you can find the Spring Cloud Contract folder structure
└── tests
```
- `config` - folder contains setup for Spring Cloud Release Tools automated release process
- `docker` - folder contains docker images
- `samples` - folder contains test samples together with standalone ones used also to build documentation
- `scripts` - contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
- `specs` - contains specifications for the Contract DSL.
- `spring-cloud-contract-dependencies` - contains Spring Cloud Contract BOM
- `spring-cloud-contract-shade` - shaded dependencies used by the plugins
- `spring-cloud-contract-starters` - contains Spring Cloud Contract Starters
- `spring-cloud-contract-spec` - contains specification modules (contains concept of a Contract)
- `spring-cloud-contract-stub-runner` - contains Stub Runner related modules
- `spring-cloud-contract-stub-runner-boot` - contains Stub Runner Boot app
- `spring-cloud-contract-tools` - Gradle and Maven plugin for `Spring Cloud Contract Verifier`
- `spring-cloud-contract-verifier` - core of the `Spring Cloud Contract Verifier` functionality
- `spring-cloud-contract-wiremock` - all WireMock related functionality
- `tests` - integration tests for different messaging technologies
The following list describes each of the top-level folders in the project structure:
- `config`: Folder contains setup for Spring Cloud Release Tools automated release process
- `docker`: Folder contains docker images
- `samples`: Folder contains test samples together with standalone ones used also to build documentation
- `scripts`: Contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
- `specs`: Contains specifications for the Contract DSL.
- `spring-cloud-contract-dependencies`: Contains Spring Cloud Contract BOM
- `spring-cloud-contract-shade`: Shaded dependencies used by the plugins
- `spring-cloud-contract-starters`: Contains Spring Cloud Contract Starters
- `spring-cloud-contract-spec`: Contains specification modules (contains concept of a Contract)
- `spring-cloud-contract-stub-runner`: Contains Stub Runner related modules
- `spring-cloud-contract-stub-runner-boot`: Contains Stub Runner Boot app
- `spring-cloud-contract-tools`: Gradle and Maven plugin for `Spring Cloud Contract Verifier`
- `spring-cloud-contract-verifier`: Core of the `Spring Cloud Contract Verifier` functionality
- `spring-cloud-contract-wiremock`: All WireMock related functionality
- `tests`: Integration tests for different messaging technologies
=== Commands
To build the core functionality together with Maven Plugin you can run
To build the core functionality together with the Maven Plugin, you can run the following
command:
```
./mvnw clean install -P integration
```
Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the
standalone samples in proper order (both for Maven and Gradle).
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:
```
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
@@ -67,35 +71,37 @@ cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
=== Helpful scripts
We're providing a couple of helpful scripts to build the project.
We provide a couple of helpful scripts to build the project.
To build the project in parallel (by default uses 4 cores but you can change it)
To build the project in parallel (by default, it uses four cores, but you can change it),
run the following command:
```
./scripts/parallelBuild.sh
```
and with 8 cores
To use eight 8 cores, run thke following command:
```
CORES=8 ./scripts/parallelBuild.sh
```
To build the project without any integration tests (by default uses 1 core)
To build the project without any integration tests (by default, this uses one core), run
the following command:
```
./scripts/noIntegration.sh
```
and with 8 cores
To use eight cores, run the following command:
```
CORES=8 ./scripts/noIntegration.sh
```
To generate the documentation (both the root one and the maven plugin one)
To generate the documentation (for both the root project and the maven plugin), run the
following command:
```
./scripts/generateDocs.sh
```

View File

@@ -2,28 +2,28 @@
== Contract DSL
include::_attributes.adoc[]
Spring Cloud Contract supports out of the box following types of DSL.
Spring Cloud Contract supports the DSLs written in the following languages:
* written in `Groovy`
* written in `YAML`
* Groovy
* YAML
TIP: If you're not familiar with Groovy, don't worry - you can use Java syntax in the
TIP: 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
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.
IMPORTANT: 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
the `Contract` class (`import org.springframework.cloud.spec.Contract`) and then call
`Contract.make { ... }`.
TIP: Spring Cloud Contract supports defining multiple contracts in a single file.
The following is a complete example of a contract definition:
The following example shows a contract definition:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -39,23 +39,30 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest.yml[indent=0]
----
====
TIP: You can compile contracts to stubs mapping using standalone maven command:
`mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert`
[TIP]
====
You can compile contracts to stubs mapping by using the following standalone Maven command:
----
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert
----
====
[[contract-limitations]]
=== Limitations
WARNING: 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`:
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 provide the `assertJsonSize` property in the plugin configuration.
You can also set the `assertJsonSize` property in the plugin configuration.
WARNING: 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.
[[contract-common-top-elements]]
=== Common Top-Level elements
=== Common Top-Level Elements
The following sections describe the most common top-level elements:
@@ -97,6 +104,8 @@ generated test not compile. Also, remember that, if you provide the same name fo
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:
====
[source,groovy,indent=0,role="primary"]
.groovy
@@ -114,8 +123,9 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=name,inde
[[contract-dsl-ignoring-contracts]]
==== Ignoring Contracts
If you want to ignore a contract, you can either set a value of ignored contracts in the
plugin configuration or set the `ignored` property on the contract itself:
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:
====
[source,groovy,indent=0,role="primary"]
@@ -135,7 +145,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=ignored,i
==== Passing Values from Files
Starting with version `1.2.0`, you can pass values from files. Assume that you have the
following resources in our project.
following resources in your project:
[source,bash,indent=0]
----
@@ -180,12 +190,14 @@ include::{verifier_core_path}/src/test/resources/classpath/response.json[indent=
----
====
When test or stub generation takes place, the contents of the file is passed to the body
When test or stub generation takes place, the contents of the `readFromFile.groovy` 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.
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:
====
[source,groovy,indent=0,role="primary"]
@@ -201,23 +213,29 @@ include::{verifier_core_path}/src/test/resources/yml/contract_pdf.yml[indent=0]
----
====
IMPORTANT: You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.
IMPORTANT: You should use this approach whenever you want to work with binary payloads,
both for HTTP and messaging.
[[features-http]]
== Contracts for HTTP
Spring Cloud Contract allows you to verify applications that use REST or HTTP as a
means of communication. Spring Cloud Contract verifies that for a request that matches the
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, will provide a
generate WireMock stubs that, for any request matching the provided criteria, provide a
suitable response.
[[contract-dsl-http-top-level-elements]]
=== HTTP Top-Level Elements
The following methods can be called in the top-level closure of a contract definition.
`request` and `response` are mandatory. `priority` is optional.
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:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -237,15 +255,17 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response,
----
====
IMPORTANT: 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`.
IMPORTANT: 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`.
[[contract-dsl-request]]
=== HTTP Request
The HTTP protocol requires only **method and url** to be specified in a request. The
same information is mandatory in request definition of the Contract.
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:
====
[source,groovy,indent=0,role="primary"]
@@ -261,8 +281,10 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=request_o
----
====
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**.
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`:
====
[source,groovy,indent=0,role="primary"]
@@ -278,7 +300,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest_with_path.yml
----
====
`request` may contain **query parameters**.
`request` may contain query parameters, as the following example (which uses `urlPath`) shows:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -296,7 +318,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=query_par
----
====
`request` may contain additional **request headers**, as shown in the following example:
`request` can contain additional request headers, as the following example shows:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -314,7 +336,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=headers,i
----
====
`request` may contain additional **request cookies**, as shown in the following example:
`request` may contain additional request cookies, as the following example shows:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -332,7 +354,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=cookies,i
----
====
`request` may contain a **request body**:
`request` may contain a request body, as the following example shows:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -350,8 +372,8 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=body,inde
----
====
`request` may contain **multipart** elements. To include multipart elements, use the
`multipart` method/section, as shown in the following examples
`request` can contain multipart elements. To include multipart elements, use the
`multipart` method/section, as the following examples show:
====
[source,groovy,indent=0,role="primary"]
@@ -373,25 +395,25 @@ In the preceding example, we define parameters in either of two ways:
* 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
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 via `multipart.params` section
* 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 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
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 this contract, the generated test and stubs look as follows:
From the contract in the preceding example, the generated test and stubs look as follows:
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
@@ -422,7 +444,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[contract-dsl-response]]
=== HTTP Response
The response must contain an **HTTP status code** and may contain other information. The
The response must contain an HTTP status code and may contain other information. The
following code shows an example:
====
@@ -441,11 +463,11 @@ include::{verifier_core_path}/src/test/resources/yml/contract.yml[tags=response_
----
====
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).
Besides status, the response may contain headers, cookies, and a body, which are
specified the same way as in the request (see <<contract-dsl-request>>).
TIP: 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
TIP: 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`.
[[contract-dsl-dynamic-properties]]
@@ -455,19 +477,19 @@ The contract can contain some dynamic properties: timestamps, IDs, and so on. Yo
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
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`.
NOTE: Before 2.0.0 these were set using `testMatchers` and `stubMatchers`,
check out the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide[migration guide] for more information.
NOTE: Before 2.0.0, these were set by using `testMatchers` and `stubMatchers`.
See the https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide[migration guide] for more information.
For YAML you can only use the `matchers` section.
For YAML, you can use only the `matchers` section.
[[contract-dsl-dynamic-properties-in-body]]
==== Dynamic properties inside the body
==== Dynamic Properties inside the Body
IMPORTANT: This section is valid only for Groovy DSL. Check out the
IMPORTANT: This section is valid only for the Groovy DSL. Check out the
<<contract-dsl-matchers>> section for YAML examples of a similar feature.
You can set the properties inside the body either with the `value` method or, if you use
@@ -494,23 +516,23 @@ $(client(...), server(...))
----
====
Both approaches work equally well. `stub` and `client` methods are aliases over the `consumer`
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.
[[contract-dsl-regex]]
==== Regular expressions
==== Regular Expressions
IMPORTANT: This section is valid only for Groovy DSL. Check out the
<<contract-dsl-matchers>> section for YAML examples of a similar feature.
You can use regular expressions to write your requests in Contract DSL. Doing so is
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 test and your server side tests.
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
https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches--[Pattern.matches()]
is called. For instance, `abc` pattern doesn't match `aabc` string but `.abc` does.
Make sure that regex matches a whole region of a sequence, as, internally, a call to
https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches[`Pattern.matches()`]
is called. For instance, `abc` does not match `aabc`, but `.abc` does.
There are several additional <<contract-dsl-regex-limitations,known limitations>> as well.
The following example shows how to use regular expressions to write a request:
@@ -533,29 +555,30 @@ In the preceding example, the opposite side of the communication has the respect
generated for request and response.
Spring Cloud Contract comes with a series of predefined regular expressions that you can
use in your contracts, as shown in the following example:
use in your contracts, as the following example shows:
[source,java,indent=0]
----
include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/internal/RegexPatterns.java[tags=regexps,indent=0]
----
In your contract, you can use it as shown in the following example:
In your contract, you can use it as follows:
[source,groovy,indent=0]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=contract_with_regex,indent=0]
----
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:
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:
[source,java,indent=0]
----
include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/internal/RegexCreatingProperty.java[tags=regex_creating_props,indent=0]
----
and this is an example of how you can reference those methods:
The following example shows how you can reference those methods:
[source,groovy,indent=0]
----
@@ -565,13 +588,13 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[contract-dsl-regex-limitations]]
===== Limitations
WARNING: 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. https://github.com/spring-cloud/spring-cloud-contract/issues/899[Issue 899]
WARNING: 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 https://github.com/spring-cloud/spring-cloud-contract/issues/899[Issue 899].
WARNING: 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.
https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900]
WARNING: 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 https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900].
[[contract-dsl-optional-params]]
==== Passing Optional Parameters
@@ -579,11 +602,11 @@ https://github.com/spring-cloud/spring-cloud-contract/issues/900[Issue 900]
IMPORTANT: This section is valid only for Groovy DSL. Check out the
<<contract-dsl-matchers>> section for YAML examples of a similar feature.
It is possible to provide optional parameters in your contract. However, you can provide
You can provide optional parameters in your contract. However, you can provide
optional parameters only for the following:
* __STUB__ side of the Request
* __TEST__ side of the Response
* The STUB side of the Request
* The TEST side of the Response
The following example shows how to provide optional parameters:
@@ -595,7 +618,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
By wrapping a part of the body with the `optional()` method, you create a regular
expression that must be present 0 or more times.
If you use Spock for, the following test would be generated from the previous example:
If you use Spock, the following test would be generated from the previous example:
[source,groovy,indent=0]
----
@@ -615,8 +638,8 @@ include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/spr
IMPORTANT: This section is valid only for Groovy DSL. Check out the
<<contract-dsl-matchers>> section for YAML examples of a similar feature.
You can define a method call that executes on the server side during the test. Such a
method can be added to the class defined as "baseClassForTests" in the configuration. The
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:
[source,groovy,indent=0]
@@ -631,7 +654,7 @@ The following code shows the base class portion of the test case:
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0]
----
IMPORTANT: You cannot use both a String and `execute` to perform concatenation. For
IMPORTANT: 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.
@@ -642,14 +665,14 @@ 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.
* `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.
IMPORTANT: You must provide both the consumer and the producer side. The `execute` part
is applied for the whole body - not for parts of it.
is applied for the whole body, not for parts of it.
The following example shows how to read an object from JSON:
@@ -681,7 +704,7 @@ It should resemble the following code:
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
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:
@@ -697,21 +720,21 @@ given name.
* `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
https://handlebarsjs.com/[Handlebars] `{{{ }}}` notation with custom, Spring Cloud Contract
functions to achieve this.
If you use the YAML contract definition, you have to use the
https://handlebarsjs.com/[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.
E.g. for key `foo`, first entry `{{{ request.query.foo.[0] }}}`
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. E.g.
for first entry ```{{{ request.path.[0] }}}
* `{{{ 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. E.g. for json path `$.foo` - `{{{ jsonpath this '$.foo' }}}`
matches the JSON Path. For example, for a JSON path of `$.here`, use `{{{ jsonpath this '$.here' }}}`
Consider the following contract:
@@ -820,7 +843,7 @@ in sending the following response body:
}
----
IMPORTANT: This feature works only with WireMock having a version greater than or equal
IMPORTANT: 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:
@@ -843,77 +866,79 @@ You can set it in the `request` or `inputMessage` part of your contract.
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
Currently, Spring Cloud Contract Verifier supports only JSON path-based matchers with the
following matching possibilities:
.Groovy DSL
===== 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
* For the stubs (in tests on the consumer's side):
** `byEquality()`: The value taken from the consumer's request in the provided JSON path must be
equal to the value provided in the contract.
** `byRegex(...)`: The value taken from the consumer's request 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
** `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 via the provided JSON Path must
** `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 via the provided JSON Path must
** `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 via the provided JSON Path must be
* 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 via the provided JSON Path must
** `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 via the provided JSON Path must match
** `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 via the provided JSON Path must
** `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 via the provided JSON Path must match
** `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 via the provided JSON Path needs to be
** `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.
`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
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('foo($it)')` results in calling a `foo` method to which the value matching the
`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 other kind of number.
*** `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 via the provided JSON Path must be null
** `byNull()`: The value taken from the response in the provided JSON path must be null.
.YAML
===== YAML
_Please read the Groovy section for detailed explanation of
what the types mean_
NOTE: See the Groovy section for detailed explanation of
what the types mean.
For YAML the structure of a matcher looks like this
For YAML, the structure of a matcher resembles the following example:
[source,yml,indent=0]
----
- path: $.foo
- path: $.thing1
type: by_regex
value: bar
value: thing2
regexType: as_string
----
Or if you want to use one of the predefined regular expressions
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]`:
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:
[source,yml,indent=0]
----
- path: $.foo
- path: $.thing1
type: by_regex
predefined: only_alpha_unicode
----
Below you can find the allowed list of `type`s.
The following list shows the allowed list of `type` values:
* For `stubMatchers`:
** `by_equality`
@@ -922,7 +947,7 @@ Below you can find the allowed list of `type`s.
** `by_timestamp`
** `by_time`
** `by_type`
*** there are 2 additional fields accepted: `minOccurrence` and `maxOccurrence`.
*** Two additional fields (`minOccurrence` and `maxOccurrence`) are accepted.
* For `testMatchers`:
** `by_equality`
** `by_regex`
@@ -930,19 +955,20 @@ Below you can find the allowed list of `type`s.
** `by_timestamp`
** `by_time`
** `by_type`
*** there are 2 additional fields accepted: `minOccurrence` and `maxOccurrence`.
*** Two additional fields (`minOccurrence` and `maxOccurrence`) are accepted.
** `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:
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
* `as_integer`
* `as_double`
* `as_float`
* `as_long`
* `as_short`
* `as_boolean`
* `as_string`
Consider the following example:
@@ -974,14 +1000,14 @@ has a value for which the JSON path matches the given field, is of the same type
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
* 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 min and maximum occurrence.
between the minimum and maximum occurrence.
The resulting test would resemble the following example (note that an `and` section
The resulting test resembles the following example (note that an `and` section
separates the autogenerated assertions and the assertion from matchers):
[source,java,indent=0]
@@ -1039,7 +1065,7 @@ The resulting WireMock stub is in the following example:
include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=matchers,indent=0]
----
IMPORTANT: If you use a `matcher`, then the part of the request and response that the
IMPORTANT: 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.
@@ -1099,9 +1125,9 @@ collection and assert it with the `byCommand(...)` method.
[[contract-dsl-async]]
=== Async Support
=== Asynchronous Support
If you're using asynchronous communication on the server side (your controllers are
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:
@@ -1130,7 +1156,8 @@ response:
----
====
You can also use the `fixedDelayMilliseconds` method / property to add delay to your stubs.
You can also use the `fixedDelayMilliseconds` method or property to add delay to your stubs.
The following example shows how to do so:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -1159,14 +1186,15 @@ response:
[[contract-dsl-xml]]
=== XML Support for HTTP
For HTTP contracts, we also support XML request and response body.
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 request and response. In place of the `jsonPath(...)` method, the `org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath`
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.
Here is an example of a Groovy DSL contract with XML response body:
The following example shows a Groovy DSL contract with XML in the response body:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -1182,7 +1210,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
----
====
Here is an example of an automatically generated test for XML response body:
The following example shows an automatically generated test for XML in the response body:
[source,java,indent=0]
----
@@ -1234,7 +1262,7 @@ include::{verifier_core_path}/src/test/resources/yml/multiple_contracts.yml[inde
====
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:
leads to generation of two tests that look more or less like the following:
[source,java,indent=0]
----
@@ -1283,39 +1311,46 @@ public class V1Test extends TestBase {
----
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_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 is shown in the following example:
The generated stubs are shown in the following example:
====
[source]
----
should post a user.json
1_WithList.json
----
====
As you can see, the first file got the `name` parameter from the contract. The second
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).
TIP: As you can see, it is much better if you name your contracts because doing so makes
TIP: It is much better to name your contracts, because doing so makes
your tests far more meaningful.
[[contract-stateful-contracts]]
=== Stateful Contracts
Stateful contracts (known also as scenarios) are contract definitions that should be read in order. This might be useful in the following situations:
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're using Spring Cloud Contract to test your stateful application
** NOTE: we really discourage you to do that since contract tests should be stateless
* you want the same endpoint to return different results for the same request
* You want to execute the contract in a precisely defined order, since you use Spring
Cloud Contract to test your stateful application
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 regardless
of whether you're working with YAML or Groovy. Example:
TIP: 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:
====
[source,indent=0]
----
my_contracts_dir\
@@ -1324,15 +1359,18 @@ my_contracts_dir\
2_showCart.groovy
3_logout.groovy
----
====
Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a
name of `scenario1` and the three following steps:
. login marked as `Started` pointing to...
. showCart marked as `Step1` pointing to...
. logout marked as `Step2` which will close the scenario.
. login, marked as `Started` pointing to...
. showCart, marked as `Step1` pointing to...
. logout, marked as `Step2` (which closes the scenario).
More details about WireMock scenarios can be found at
https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/]
You can find nore details about WireMock scenarios at
https://wiremock.org/docs/stateful-behaviour/[https://wiremock.org/docs/stateful-behaviour/].
Spring Cloud Contract also generates tests with a guaranteed order of execution.
Spring Cloud Contract also generates tests with a guaranteed order of execution.
// TODO: How can someone specify the order of execution in SC Contract?
// That sentence is a great lead-in to more content, which then does not appear.

View File

@@ -8,7 +8,7 @@ include::_attributes.adoc[]
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 set. Otherwise, the default of `application/octet-stream` gets used.
content type be set. Otherwise, the default of `application/octet-stream` gets used.
In order to use JAX-RS mode, use the following settings:
@@ -27,7 +27,8 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[feature-webflux]]
=== WebFlux with WebTestClient
You can work with WebFlux via the `WebTestClient` mode.
You can work with WebFlux by using WebTestClient. The following listing shows how to
configure WebTestClient as the test mode:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -53,7 +54,7 @@ contracts {
----
====
The following example shows how to set up a `WebTestClient` base class and `RestAssured`
The following example shows how to set up a WebTestClient base class and RestAssured
for WebFlux:
[source,groovy,indent=0]
@@ -72,13 +73,13 @@ public abstract class BeerRestBase {
}
----
IMPORTANT: The `WebTestClient` mode is faster than the `EXPLICIT` mode
TIP: The `WebTestClient` mode is faster than the `EXPLICIT` mode.
[[feature-webflux-explicit]]
=== WebFlux with Explicit mode
=== WebFlux with Explicit Mode
Another way is with the `EXPLICIT` mode in your generated tests
to work with WebFlux.
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:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -104,7 +105,7 @@ contracts {
----
====
The following example shows how to set up a base class and Rest Assured for Web Flux:
The following example shows how to set up a base class and RestAssured for Web Flux:
[source,groovy,indent=0]
----
@@ -123,10 +124,12 @@ include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.j
Spring Cloud Contract supports context paths.
IMPORTANT: 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.
[IMPORTANT]
=====
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`:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -151,9 +154,10 @@ contracts {
}
----
====
=====
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
That way, you generate a test that does not use MockMvc. It means that you generate
real requests and you need to set up your generated test's base class to work on a real
socket.
Consider the following contract:
@@ -163,7 +167,7 @@ Consider the following contract:
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0]
----
The following example shows how to set up a base class and Rest Assured:
The following example shows how to set up a base class and RestAssured:
[source,groovy,indent=0]
----
@@ -180,36 +184,35 @@ that information (for example, in the stubs, you have to call `/my-context-path/
[[features-rest-docs]]
=== Working with REST Docs
https://projects.spring.io/spring-restdocs[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
You can use https://projects.spring.io/spring-restdocs[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.
[plantuml, rest-docs, png]
----
"API Producer"->"API Producer": add Spring Cloud Contract (SCC) \nStub Runner dependency
"API Producer"->"API Producer": setup stub jar assembly
"API Producer"->"API Producer": write and setup REST Docs tests
"API Producer"->"Build": run build
"Build"->"REST Docs": generate API \ndocumentation
"REST Docs"->"SCC": generate stubs from the \nREST Docs tests
"REST Docs"->"SCC": generate contracts from the \nREST Docs tests
"Build"->"Build": assemble stubs jar with \nstubs and contracts
"Build"->"Nexus / Artifactory": upload contracts \nand stubs and the project arifact
"API Producer"->"API Producer": Add Spring Cloud Contract (SCC) \nStub Runner dependency
"API Producer"->"API Producer": Set up stub jar assembly
"API Producer"->"API Producer": Write and set up REST Docs tests
"API Producer"->"Build": Run build
"Build"->"REST Docs": Generate API \ndocumentation
"REST Docs"->"SCC": Generate stubs from the \nREST Docs tests
"REST Docs"->"SCC": Generate contracts from the \nREST Docs tests
"Build"->"Build": Assemble stubs jar with \nstubs and contracts
"Build"->"Nexus / Artifactory": Upload contracts \nand stubs and the project arifact
"Build"->"API Producer": Build successful
"API Consumer"->"API Consumer": add SCC Stub Runner \ndependency
"API Consumer"->"API Consumer": write a SCC Stub Runner \nbased contract test
"SCC Stub Runner"->"Nexus / Artifactory": test asks for [API Producer] stubs
"Nexus / Artifactory"->"SCC Stub Runner": fetch the [API Producer] stubs
"SCC Stub Runner"->"SCC Stub Runner": run in memory\n HTTP server stubs
"API Consumer"->"SCC Stub Runner": send a request \nto the HTTP server stub
"SCC Stub Runner"->"API Consumer": communication is correct
"API Consumer"->"API Consumer": Add SCC Stub Runner \ndependency
"API Consumer"->"API Consumer": Write a SCC Stub Runner \nbased contract test
"SCC Stub Runner"->"Nexus / Artifactory": Test asks for [API Producer] stubs
"Nexus / Artifactory"->"SCC Stub Runner": Fetch the [API Producer] stubs
"SCC Stub Runner"->"SCC Stub Runner": Run in memory\n HTTP server stubs
"API Consumer"->"SCC Stub Runner": Send a request \nto the HTTP server stub
"SCC Stub Runner"->"API Consumer": Communication is correct
----
The following code shows an
example using `MockMvc`:
The following example uses `MockMvc`:
[source,java,indent=0]
----
@@ -231,9 +234,9 @@ public class ApplicationTests {
}
----
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:
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:
[source,java,indent=0]
----
@@ -256,7 +259,7 @@ public class ApplicationTests {
----
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
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:
@@ -264,14 +267,14 @@ explicitly create a request matcher. Doing so has two effects:
* 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:
as a substitute for the `document()` convenience method, as the following
example shows:
====
[source,java,indent=0]
----
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
----
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureRestDocs(outputDir = "target/snippets")
@@ -291,16 +294,17 @@ public class ApplicationTests {
}
}
----
====
This contract specifies that any valid POST with an "id" field receives the response
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 https://github.com/jayway/JsonPath[JayWay
matchers. If JSON Path is unfamiliar, the https://github.com/jayway/JsonPath[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:
WireMock APIs to verify that the request matches the created stub, as the
following example shows:
[source,java,indent=0]
----
@@ -317,9 +321,9 @@ 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:
The WireMock API is rich. You can match headers, query parameters, and the request body by
regex as well as by JSON path. You can use these features to create stubs with a wider
range of parameters. The preceding example generates a stub resembling the following example:
.post-resource.json
[source,json]
@@ -344,17 +348,17 @@ range of parameters. The above example generates a stub resembling the following
----
NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()`
methods to create request matchers, but you can't use both approaches.
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
<<features-stub-runner-publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a
<<features-stub-runner-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.
[[features-rest-docs-contracts]]
==== Generating Contracts viaREST Docs
==== Generating Contracts with REST Docs
You can also generate Spring Cloud Contract DSL files and documentation with Spring REST
Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts
@@ -366,21 +370,24 @@ but they already have a lot of Spring MVC tests. Using this feature lets you gen
the contract files that you can later modify and move to folders (defined in your
configuration) so that the plugin finds them.
TIP: You might wonder why this functionality is in the WireMock module. The functionality
NOTE: You might wonder why this functionality is in the WireMock module. The functionality
is there because it makes sense to generate both the contracts and the stubs.
Consider the following test:
====
[source,java]
----
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet]
----
====
The preceding test creates the stub presented in the previous section, generating both
the contract and a documentation file.
The contract is called `index.groovy` and might look like the following example:
The contract is called `index.groovy` and might resemble the following example:
====
[source,groovy]
----
import org.springframework.cloud.contract.spec.Contract
@@ -412,6 +419,7 @@ Contract.make {
}
}
----
====
The generated document (formatted in Asciidoc in this case) contains a formatted
contract. The location of this file would be `index/dsl-contract.adoc`.

View File

@@ -20,7 +20,7 @@ following sections explain the differences:
[[contract-dsl-output-triggered-method]]
==== Output Triggered by a Method
The output message can be triggered by calling a method (such as a `Scheduler` when a was
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:
====
@@ -38,8 +38,8 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_method.yml
====
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
`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.
[[contract-dsl-output-triggered-message]]
@@ -63,9 +63,9 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_input_mess
====
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
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
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.
[[contract-dsl-consumer-producer]]
@@ -87,9 +87,9 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[contract-dsl-messaging-common]]
==== Common
In the `input` or `outputMessage` section you can call `assertThat` with the name
of a `method` (e.g. `assertThatMessageIsOnTheQueue()`) that you have defined in the
base class or in a static import. Spring Cloud Contract will execute that method
In the `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.
[[features-messaging-integrations]]
@@ -106,13 +106,15 @@ Since we use Spring Boot, if you have added one of these libraries to the classp
the messaging configuration is automatically set up.
IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your
generated tests. Otherwise, messaging part of Spring Cloud Contract does not
generated tests. Otherwise, the messaging part of Spring Cloud Contract does not
work.
IMPORTANT: If you want to use Spring Cloud Stream, remember to add a dependency on
`org.springframework.cloud:spring-cloud-stream-test-support`, as shown below
[IMPORTANT]
=====
If you want to use Spring Cloud Stream, remember to add a dependency on
`org.springframework.cloud:spring-cloud-stream-test-support`, as follows:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
@@ -128,6 +130,7 @@ IMPORTANT: If you want to use Spring Cloud Stream, remember to add a dependency
----
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
----
====
=====
[[features-messaging-manual]]
@@ -140,8 +143,9 @@ 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:
The following example shows how to do so:
====
[source,java,indent=0]
----
@RunWith(SpringTestRunner.class)
@@ -154,34 +158,35 @@ public static class MessagingContractTests {
...
}
----
====
NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the
messaging configuration, so you only need the one annotation.
[[features-messaging-test-generation]]
=== Messaging Producer Side Test Generation
=== Producer Side Messaging Test Generation
Having the `input` or `outputMessage` sections in your DSL results in creation of tests
on the publisher's side. By default, JUnit 4 tests are created. However, there is also a
possibility to create JUnit 5, TestNG or Spock tests.
possibility to create JUnit 5, TestNG, or Spock tests.
There are 3 main scenarios that we should take into consideration:
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, scheduler).
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.
* Scenario 3: The input message is consumed, and there is no output message.
IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different
meanings for different messaging implementations. For *Stream* and *Integration* it is
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,
it is resolved as a channel name. For Camel, that's a certain component (for example,
`jms`).
[[features-messaging-scenario1]]
==== Scenario 1: No Input Message
For the given contract:
Consider the following contract:
=====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -198,7 +203,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario1.
----
=====
The following test would be created
For the preceding example, the following test would be created:
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
@@ -217,7 +222,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[features-messaging-scenario2]]
==== Scenario 2: Output Triggered by Input
For the given contract:
Consider the following contract:
=====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -233,7 +238,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario2.
----
=====
The following test would be created
For the preceding contract, the following test would be created:
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
@@ -252,7 +257,7 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[features-messaging-scenario3]]
==== Scenario 3: No Output Message
For the given contract:
Consider the following contract:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -268,7 +273,7 @@ include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.
----
====
The following test would be created
For the preceding contract, the following test would be created:
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
@@ -287,18 +292,19 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract
[[features-messaging-consumer]]
=== Consumer Stub Generation
Unlike 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.
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.
IMPORTANT: 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.
IMPORTANT: 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.
[[features-messaging-stub-triggering]]
==== Stub triggering
To trigger a message, use the `StubTrigger` interface:
To trigger a message, use the `StubTrigger` interface, as the following example shows:
[source,groovy]
----
@@ -318,6 +324,8 @@ or the other in your tests.
[[features-messaging-trigger-label]]
==== Trigger by Label
The following example shows how to trigger a message with a label:
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0]
@@ -331,7 +339,9 @@ include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/o
----
[[features-messaging-trigger-artifact-ids]]
==== Trigger by Artifact Ids
==== Trigger by Artifact IDs
The following example shows how to trigger a message from artifact IDs:
[source,groovy]
----
@@ -341,6 +351,8 @@ include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/o
[[features-messaging-trigger-all-messages]]
==== Trigger All Messages
The following example shows how to trigger all messages:
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_all,indent=0]
@@ -350,29 +362,30 @@ include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/o
:output_name: jms:output
[[features-messaging-stub-runner-camel]]
=== Messaging Consumer Side With Apache Camel
=== Consumer Side Messaging With Apache Camel
Spring Cloud Contract Stub Runner's messaging module gives you an easy way to integrate with Apache Camel.
For the provided artifacts it will automatically download the stubs and register the required
For the provided artifacts, it automatically downloads the stubs and registers the required
routes.
[[features-messaging-stub-runner-camel-adding]]
==== Adding it to the project
==== Adding Apache Camel to the Project
It's enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath.
You can have both Apache Camel and Spring Cloud Contract Stub Runner on the classpath.
Remember to annotate your test class with `@AutoConfigureStubRunner`.
[[features-messaging-stub-runner-camel-disabling]]
==== Disabling the functionality
==== Disabling the Functionality
If you need to disable this functionality just pass `stubrunner.camel.enabled=false` property.
If you need to disable this functionality, set the `stubrunner.camel.enabled=false` property.
[[features-messaging-stub-runner-camel-example]]
==== Examples
Let us assume that we have the following Maven repository with a deployed stubs for the
Assume that we have the following Maven repository with deployed stubs for the
`camelService` application.
====
[source,bash,indent=0]
----
└── .m2
@@ -388,9 +401,11 @@ Let us assume that we have the following Maven repository with a deployed stubs
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml
----
====
And the stubs contain the following structure:
Further assume that the stubs contain the following structure:
====
[source,bash,indent=0]
----
├── META-INF
@@ -402,73 +417,88 @@ And the stubs contain the following structure:
│   └── bookReturned2.groovy
└── mappings
----
====
Let's consider the following contracts (let' number it with *1*):
Now consider the following contracts (we number them 1 and 2):
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
----
and number *2*
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0]
----
====
[[features-messaging-stub-runner-camel-scenario1]]
===== Scenario 1 (no input message)
===== Scenario 1 (No Input Message)
So as to trigger a message via the `return_book_1` label we'll use the `StubTigger` interface as follows
To trigger a message from the `return_book_1` label, we use the `StubTigger` interface, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
====
Next we'll want to listen to the output of the message sent to `{output_name}`
Next, we want to listen to the output of the message sent to `{output_name}`:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0]
----
====
And the received message would pass the following assertions
The received message would then pass the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_trigger_message,indent=0]
----
====
[[features-messaging-stub-runner-camel-scenario2]]
===== Scenario 2 (output triggered by input)
===== Scenario 2 (Output Triggered by Input)
Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
Since the route is set for you, you can send a message to the `{output_name}` destination.
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_send,indent=0]
----
====
Next we'll want to listen to the output of the message sent to `{output_name}`
Next, we want to listen to the output of the message sent to `{output_name}`, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive,indent=0]
----
====
And the received message would pass the following assertions
The received message would pass the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=client_receive_message,indent=0]
----
====
[[features-messaging-stub-runner-camel-scenario3]]
===== Scenario 3 (input with no output)
===== Scenario 3 (Input with No Output)
Since the route is set for you it's enough to just send a message to the `{output_name}` destination.
Since the route is set for you, you can send a message to the `{output_name}` destination, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/camel/CamelStubRunnerSpec.groovy[tags=trigger_no_output,indent=0]
@@ -476,9 +506,10 @@ include::{tests_path}/spring-cloud-contract-stub-runner-camel/src/test/groovy/or
:input_name: input
:output_name: output
====
[[features-messaging-stub-runner-integration]]
=== Messaging Consumer Side With Spring Integration
=== Consumer Side Messaging with Spring Integration
Spring Cloud Contract Stub Runner's messaging module gives you an easy way to
integrate with Spring Integration. For the provided artifacts, it automatically downloads
@@ -491,7 +522,7 @@ You can have both Spring Integration and Spring Cloud Contract Stub Runner on th
classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`.
[[features-messaging-stub-runner-integration-disabling]]
==== Disabling the functionality
==== Disabling the Functionality
If you need to disable this functionality, set the
`stubrunner.integration.enabled=false` property.
@@ -502,6 +533,7 @@ If you need to disable this functionality, set the
Assume that you have the following Maven repository with deployed stubs for the
`integrationService` application:
====
[source,bash,indent=0]
----
└── .m2
@@ -517,9 +549,11 @@ Assume that you have the following Maven repository with deployed stubs for the
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml
----
====
Further assume the stubs contain the following structure:
====
[source,bash,indent=0]
----
├── META-INF
@@ -531,107 +565,126 @@ Further assume the stubs contain the following structure:
│   └── bookReturned2.groovy
└── mappings
----
====
Consider the following contracts (numbered *1*):
Consider the following contracts (numbered 1 and 2):
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
----
Now consider *2*:
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0]
----
====
and the following Spring Integration Route:
Now consider the following Spring Integration Route:
====
[source,xml]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/resources/integration-context.xml[lines=1;18..-1]
----
====
These examples lend themselves to three scenarios:
* <<features-messaging-stub-runner-integration-scenario1>>
* <<features-messaging-stub-runner-integration-scenario2>>
* <<features-messaging-stub-runner-integration-scenario3>>
. <<features-messaging-stub-runner-integration-scenario1>>
. <<features-messaging-stub-runner-integration-scenario2>>
. <<features-messaging-stub-runner-integration-scenario3>>
[[features-messaging-stub-runner-integration-scenario1]]
===== Scenario 1 (no input message)
===== Scenario 1 (No Input Message)
To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as
To trigger a message from the `return_book_1` label, use the `StubTigger` interface, as
follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
====
To listen to the output of the message sent to `{output_name}`:
The following listing shows how to listen to the output of the message sent to `{output_name}`:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0]
----
====
The received message would pass the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0]
----
====
[[features-messaging-stub-runner-integration-scenario2]]
===== Scenario 2 (output triggered by input)
===== Scenario 2 (Output Triggered by Input)
Since the route is set for you, you can send a message to the `{output_name}`
destination:
destination, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0]
----
====
To listen to the output of the message sent to `{output_name}`:
The following listing shows how to listen to the output of the message sent to `{output_name}`:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0]
----
====
The received message passes the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0]
----
====
[[features-messaging-stub-runner-integration-scenario3]]
===== Scenario 3 (input with no output)
===== Scenario 3 (Input with No Output)
Since the route is set for you, you can send a message to the `{input_name}` destination:
Since the route is set for you, you can send a message to the `{input_name}` destination, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-integration/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=trigger_no_output,indent=0]
----
====
[[features-messaging-stub-runner-stream]]
=== Messaging Consumer Side With Spring Cloud Stream
=== Consumer Side Messaging With Spring Cloud Stream
Spring Cloud Contract Stub Runner's messaging module gives you an easy way to
integrate with Spring Stream. For the provided artifacts, it automatically downloads the
stubs and registers the required routes.
WARNING: 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
WARNING: 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.
IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on
`org.springframework.cloud:spring-cloud-stream-test-support`.
[IMPORTANT]
=====
If you want to use Spring Cloud Stream, remember to add a dependency on
`org.springframework.cloud:spring-cloud-stream-test-support`, as follows:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -650,6 +703,7 @@ IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
----
====
=====
[[features-messaging-stub-runner-stream-adding]]
==== Adding the Runner to the Project
@@ -658,7 +712,7 @@ You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on t
classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`.
[[features-messaging-stub-runner-stream-disabling]]
==== Disabling the functionality
==== Disabling the Functionality
If you need to disable this functionality, set the `stubrunner.stream.enabled=false`
property.
@@ -666,9 +720,10 @@ property.
[[features-messaging-stub-runner-stream-example]]
==== Examples
Assume that you have the following Maven repository with a deployed stubs for the
Assume that you have the following Maven repository with deployed stubs for the
`streamService` application:
====
[source,bash,indent=0]
----
└── .m2
@@ -684,9 +739,11 @@ Assume that you have the following Maven repository with a deployed stubs for th
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml
----
====
Further assume the stubs contain the following structure:
====
[source,bash,indent=0]
----
├── META-INF
@@ -698,27 +755,30 @@ Further assume the stubs contain the following structure:
│   └── bookReturned2.groovy
└── mappings
----
====
Consider the following contracts (numbered *1*):
Consider the following contracts (numbered 1 and 2):
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
----
Now consider *2*:
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0]
----
====
Now consider the following Spring configuration:
====
[source,yaml]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/resources/application.yml[]
----
====
These examples lend themselves to three scenarios:
@@ -727,69 +787,83 @@ These examples lend themselves to three scenarios:
* <<features-messaging-stub-runner-stream-scenario3>>
[[features-messaging-stub-runner-stream-scenario1]]
===== Scenario 1 (no input message)
===== Scenario 1 (No Input Message)
To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as
To trigger a message from the `return_book_1` label, use the `StubTrigger` interface as
follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
====
To listen to the output of the message sent to a channel whose `destination` is
The following example shows how to listen to the output of the message sent to a channel whose `destination` is
`returnBook`:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0]
----
====
The received message passes the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0]
----
====
[[features-messaging-stub-runner-stream-scenario2]]
===== Scenario 2 (output triggered by input)
===== Scenario 2 (Output Triggered by Input)
Since the route is set for you, you can send a message to the `bookStorage`
`destination`:
`destination`, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0]
----
====
To listen to the output of the message sent to `returnBook`:
The following example shows how to listen to the output of the message sent to `returnBook`:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0]
----
====
The received message passes the following assertions:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0]
----
====
[[features-messaging-stub-runner-stream-scenario3]]
===== Scenario 3 (input with no output)
===== Scenario 3 (Input with No Output)
Since the route is set for you, you can send a message to the `{output_name}`
destination:
destination, as follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_no_output,indent=0]
----
====
[[features-messaging-stub-runner-amqp]]
=== Messaging Consumer Side With Spring AMQP
=== Consumer Side Messaging With Spring AMQP
Spring Cloud Contract Stub Runner's messaging module provides an easy way to
integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it
@@ -797,7 +871,7 @@ 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
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
@@ -807,11 +881,11 @@ As messages are usually sent to exchanges in AMQP, the message contract contains
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
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, it's enough to pass them via the `amqp_receivedRoutingKey`
If you need to work with routing keys, you can pass them by using the `amqp_receivedRoutingKey`
messaging header.
[[features-messaging-stub-runner-amqp-adding]]
@@ -829,8 +903,9 @@ to disable them explicitly by setting the `stubrunner.stream.enabled=false` and
==== Examples
Assume that you have the following Maven repository with a deployed stubs for the
`spring-cloud-contract-amqp-test` application.
`spring-cloud-contract-amqp-test` application:
====
[source,bash,indent=0]
----
└── .m2
@@ -844,9 +919,11 @@ Assume that you have the following Maven repository with a deployed stubs for th
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml
----
====
Further assume that the stubs contain the following structure:
====
[source,bash,indent=0]
----
├── META-INF
@@ -854,53 +931,67 @@ Further assume that the stubs contain the following structure:
└── contracts
└── shouldProduceValidPersonData.groovy
----
====
Consider the following contract:
Then consider the following contract:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0]
----
====
Now consider the following Spring configuration:
====
[source,yaml]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/resources/application.yml[]
----
====
[[features-messaging-stub-runner-amqp-triggering]]
===== Triggering the message
===== Triggering the Message
To trigger a message using the contract above, use the `StubTrigger` interface as
To trigger a message using the contract in the preceding section, use the `StubTrigger` interface as
follows:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
====
The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner
integration looks for bindings related to this exchange.
integration looks for bindings related to this exchange, as the following example shows:
====
[source,java]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_binding,indent=0]
----
====
The binding definition binds the queue `test.queue`. As a result, the following listener
definition is matched and invoked with the contract message.
The binding definition binds the queue called `test.queue`. As a result, the following listener
definition is matched and invoked with the contract message:
====
[source,java]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0]
----
====
Also, the following annotated listener matches and is invoked:
====
[source,java]
----
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java[tags=amqp_annotated_listener,indent=0]
----
====
NOTE: The message is directly handed over to the `onMessage` method of the
`MessageListener` associated with the matching `SimpleMessageListenerContainer`.
@@ -908,15 +999,17 @@ NOTE: The message is directly handed over to the `onMessage` method of the
[[features-messaging-stub-runner-amqp-configuration]]
===== Spring AMQP Test Configuration
In order to avoid Spring AMQP trying to connect to a running broker during our tests
In order to avoid Spring AMQP trying to connect to a running broker during our tests, we
configure a mock `ConnectionFactory`.
To disable the mocked ConnectionFactory, set the following property:
`stubrunner.amqp.mockConnection=false`
To disable the mocked `ConnectionFactory`, set the following property:
`stubrunner.amqp.mockConnection=false`, as follows:
====
[source,yaml]
----
stubrunner:
amqp:
mockConnection: false
----
----
====

View File

@@ -10,10 +10,10 @@ question. That is why we introduced Spring Cloud Contract Stub Runner. It can
automatically download and run the stubs for you.
[[features-stub-runner-snapshot-versions]]
=== Snapshot versions
=== Snapshot Versions
Add the additional snapshot repository to your `build.gradle` file to use snapshot
versions, which are automatically uploaded after every successful build:
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:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -32,12 +32,14 @@ include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0]
[[features-stub-runner-publishing-stubs-as-jars]]
=== Publishing Stubs as JARs
The easiest approach would be to centralize the way stubs are kept. For example, you can
keep them as jars in a Maven repository.
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.
TIP: 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:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -62,47 +64,52 @@ include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/f
[[features-stub-runner-core]]
=== Stub Runner Core
Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of
https://martinfowler.com/articles/consumerDrivenContracts.html[Consumer Driven Contracts].
The stub runner core runs stubs for service collaborators. Treating stubs as contracts of
services lets you use stub-runner as an implementation of
https://martinfowler.com/articles/consumerDrivenContracts.html[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.
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.
[[features-stub-runner-retrieving]]
==== Retrieving stubs
You can pick the following options of acquiring stubs
You can pick from the following options of acquiring stubs:
- Aether based solution that downloads JARs with stubs from Artifactory / Nexus
- Classpath scanning solution that searches classpath via pattern to retrieve stubs
- Write your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization
- Aether-based solution that downloads JARs with stubs from Artifactory or Nexus
- Classpath-scanning solution that searches the classpath with a pattern to retrieve stubs
- Writing your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization
The latter example is described in the <<advanced.adoc#customization-custom-stub-runner, Custom Stub Runner>> section.
[[features-stub-runner-downloading-stub]]
===== Stub downloading
===== Downloading Stubs
You can control the stub downloading via the `stubsMode` switch. It picks value from the
`StubRunnerProperties.StubsMode` enum. You can use the following options
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) - 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
- `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
Example:
The following example picks stubs from a local location:
====
[source,java]
----
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
----
====
[[features-stub-runner-classpath-scanning]]
===== Classpath scanning
If you set the `stubsMode` property to `StubRunnerProperties.StubsMode.CLASSPATH`
(or set nothing since `CLASSPATH` is the default value) then classpath will get scanned.
Let's look at the following example:
(or set nothing since `CLASSPATH` is the default value), the classpath is scanned.
Consider the following example:
====
[source,java]
----
@AutoConfigureStubRunner(ids = {
@@ -110,8 +117,9 @@ Let's look at the following example:
"com.example.foo:bar:1.0.0:superstubs:8096"
})
----
====
If you've added the dependencies to your classpath
You can add the dependencies to your classpath, as follows:
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
@@ -131,8 +139,8 @@ If you've added the dependencies to your classpath
</exclusions>
</dependency>
<dependency>
<groupId>com.example.foo</groupId>
<artifactId>bar</artifactId>
<groupId>com.example.thing1</groupId>
<artifactId>thing2</artifactId>
<classifier>superstubs</classifier>
<version>1.0.0</version>
<scope>test</scope>
@@ -151,29 +159,31 @@ If you've added the dependencies to your classpath
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
transitive = false
}
testCompile("com.example.foo:bar:1.0.0:superstubs") {
testCompile("com.example.thing1:thing2:1.0.0:superstubs") {
transitive = false
}
----
====
Then the following locations on your classpath will get scanned. For `com.example:beer-api-producer-restdocs`
Then the specified locations on your classpath get scanned. For `com.example:beer-api-producer-restdocs`,
the following locations are scanned:
- /META-INF/com.example/beer-api-producer-restdocs/**/*.*
- /contracts/com.example/beer-api-producer-restdocs/**/*.*
- /mappings/com.example/beer-api-producer-restdocs/**/*.*
and `com.example.foo:bar`
For `com.example.thing1:thing2`, the following locations are scanned:
- /META-INF/com.example.foo/bar/**/*.*
- /contracts/com.example.foo/bar/**/*.*
- /mappings/com.example.foo/bar/**/*.*
- /META-INF/com.example.thing1/thing2/**/*.*
- /contracts/com.example.thing1/thing2/**/*.*
- /mappings/com.example.thing1/thing2/**/*.*
TIP: As you can see you have to explicitly provide the group and artifact ids when packaging the
TIP: You have to explicitly provide the group and artifact IDs when you package the
producer stubs.
The producer would setup the contracts like this:
To achieve proper stub packaging, the producer would set up the contracts as follows:
====
[source,bash]
----
└── src
@@ -186,13 +196,13 @@ The producer would setup the contracts like this:
      └── contract3.groovy
----
====
To achieve proper stub packaging.
Or using the https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/pom.xml[Maven `assembly` plugin] or
https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/build.gradle[Gradle Jar] task you have to create the following
structure in your stubs jar.
By using the https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/pom.xml[Maven `assembly` plugin] or
https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/build.gradle[Gradle Jar] task, you have to create the following
structure in your stubs jar:
====
[source,bash]
----
└── META-INF
@@ -206,52 +216,68 @@ structure in your stubs jar.
   └── mapping.json
----
====
By maintaining this structure classpath gets scanned and you can profit from the messaging /
By maintaining this structure, the classpath gets scanned and you can profit from the messaging or
HTTP stubs without the need to download artifacts.
[[features-stub-runner-configuring-http-server-stubs]]
===== Configuring HTTP Server Stubs
Stub Runner has a notion of a `HttpServerStub` that abstracts the underlaying
concrete implementation of the HTTP server (e.g. WireMock is one of the implementations).
Sometimes, you need to perform some additional tuning of the stub servers,
that is concrete for the given implementation. To do that, Stub Runner gives you
the `httpServerStubConfigurer` property that is available in the annotation,
JUnit rule, and is accessible via system properties, where you can provide
your implementation of the `org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer` interface. The implementations can alter
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. Example:
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:
.WireMockHttpServerStubConfigurer implementation
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer]
----
====
You can then reuse it via the annotation
You can then reuse it with the `@AutoConfigureStubRunner` annotation, as follows:
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=annotation]
----
====
Whenever an https port is found, it will take precedence over the http one.
Whenever an HTTPS port is found, it takes precedence over the HTTP port.
[[features-stub-runner-running-stubs]]
==== Running stubs
This section describes how to run stubs. It contains the following topics:
* <<features-stub-runner-http-stubs>>
* <<features-stub-runner-viewing>>
* <<features-stub-runner-messaging>>
[[features-stub-runner-http-stubs]]
===== HTTP Stubs
Stubs are defined in JSON documents, whose syntax is defined in http://wiremock.org/stubbing.html[WireMock documentation]
Example:
The following example defines a stub in JSON:
====
[source,javascript,indent=0]
----
{
@@ -268,23 +294,27 @@ Example:
}
}
----
====
[[features-stub-runner-viewing]]
===== Viewing registered mappings
===== Viewing Registered Mappings
Every stubbed collaborator exposes list of defined mappings under `__/admin/` endpoint.
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 annotation based approach it would look like this
For the annotation-based approach, it would resembling the following example:
====
[source,java]
----
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
mappingsOutputFolder = "target/outputmappings/")
----
====
and for the JUnit approach like this:
For the JUnit approach, it resembles the following example:
====
[source,java]
----
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
@@ -293,20 +323,24 @@ and for the JUnit approach like this:
.downloadStub("a.b.c:fraudDetectionServer")
.withMappingsOutputFolder("target/outputmappings")
----
====
Then if you check out the folder `target/outputmappings` you would see the following structure
Then, if you check out the `target/outputmappings` folder, you would see the following structure;
====
[source,bash]
----
.
├── fraudDetectionServer_13705
└── loanIssuance_12255
----
====
That means that there were two stubs registered. `fraudDetectionServer` was registered at port `13705`
and `loanIssuance` at port `12255`. If we take a look at one of the files we would see (for WireMock)
mappings available for the given server:
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:
====
[source,json]
----
[{
@@ -324,42 +358,53 @@ mappings available for the given server:
...
]
----
====
[[features-stub-runner-messaging]]
===== Messaging Stubs
Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.
Depending on the provided Stub Runner dependency and the DSL, the messaging routes are automatically set up.
[[features-stub-runner-junit]]
=== Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:
Stub Runner comes with a JUnit rule that lets you can download and run stubs for a given
group and artifact ID, as the following example shows:
====
[source,java,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=classrule]
----
====
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:
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 / 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)
- 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 https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies.
Stub Runner uses the https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies.
Check their https://wiki.eclipse.org/Aether[docs] for more information.
Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they allow you to find the started stubs:
Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they let
you find the started stubs, as the following example shows:
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java[lines=16..-1]
----
====
The following examples provide more detail about using Stub Runner:
====
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
@@ -381,66 +426,78 @@ include::{stubrunner_core_path}/src/test/java/org/springframework/cloud/contract
----
====
Check the <<features-stub-runner-common-properties-junit-spring>> for more information on how to apply global configuration of Stub Runner.
See the <<features-stub-runner-common-properties-junit-spring>> for more information on
how to apply global configuration of Stub Runner.
IMPORTANT: 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.
`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.
[[features-stub-runner-rule-maven-settings]]
==== Maven settings
==== Maven Settings
The stub downloader honors Maven settings for a different local repository folder.
Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.
Authentication details for repositories and profiles are currently not taken into account,
so you need to specify it by using the properties mentioned above.
[[features-stub-runner-rule-fixed-ports]]
==== Providing fixed ports
==== Providing Fixed Ports
You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of
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.
[[features-stub-runner-rule-fluent-api]]
==== Fluent API
When using the `StubRunnerRule` or `StubRunnerExtension` you can add a stub to download and then pass the port for the last downloaded stub.
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:
====
[source,java,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=classrule_with_port]
----
====
You can see that for this example the following test is valid:
For the preceding example, the following test is valid:
====
[source,java,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=test_with_port]
----
====
[[features-stub-runner-rule-spring]]
==== Stub Runner with Spring
Sets up Spring configuration of the Stub Runner project.
Stub Runner with Spring sets up Spring configuration of the Stub Runner project.
By providing a list of stubs inside your configuration file the Stub Runner automatically downloads
By providing a list of stubs inside your configuration file, Stub Runner automatically downloads
and registers in WireMock the selected stubs.
If you want to find the URL of your stubbed dependency you can autowire the `StubFinder` interface and use
its methods as presented below:
If you want to find the URL of your stubbed dependency, you can autowire the `StubFinder` interface and use
its methods, as follows:
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=test]
----
====
for the following configuration file:
Doing so depends on the following configuration file:
====
[source,yml,indent=0]
----
include::{stubrunner_core_path}/src/test/resources/application-test.yml[tags=test]
----
====
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.
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:
[source,groovy,indent=0]
----
@@ -448,74 +505,85 @@ include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contra
----
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`.
for every registered WireMock server. The following example shows Stub Runner IDs for
`com.example:thing1` and `com.example:thing2`:
- `stubrunner.runningstubs.foo.port`
- `stubrunner.runningstubs.com.example.foo.port`
- `stubrunner.runningstubs.bar.port`
- `stubrunner.runningstubs.com.example.bar.port`
- `stubrunner.runningstubs.thing1.port`
- `stubrunner.runningstubs.com.example.thing1.port`
- `stubrunner.runningstubs.thing2.port`
- `stubrunner.runningstubs.com.example.thing2.port`
Which you can reference in your code.
You can reference these values 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 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`.
====
[source,java,indent=0]
----
@StubRunnerPort("foo")
int fooPort;
@StubRunnerPort("com.example:bar")
int barPort;
@StubRunnerPort("thing1")
int thing1Port;
@StubRunnerPort("com.example:thing2")
int thing2Port;
----
====
[[features-stub-runner-cloud]]
=== Stub Runner Spring Cloud
Stub Runner can integrate with Spring Cloud.
For real life examples you can check the
For real life examples, see:
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[producer app sample]
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[consumer app sample]
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[The producer app sample]
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[The consumer app sample]
[[features-stub-runner-cloud-stubbing-discovery]]
==== Stubbing Service Discovery
The most important feature of `Stub Runner Spring Cloud` is the fact that it's stubbing
The most important feature of `Stub Runner Spring Cloud` is the fact that it stubs:
- `DiscoveryClient`
- `Ribbon` `ServerList`
that means that regardless of the fact whether you're using Zookeeper, Consul, Eureka or anything else, you don't need that in your tests.
We're starting WireMock instances of your dependencies and we're telling your application whenever you're using `Feign`, load balanced `RestTemplate`
or `DiscoveryClient` directly, to call those stubbed servers instead of calling the real Service Discovery tool.
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 this test will pass
For example, the following test passes:
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=test]
----
====
for the following configuration file
Note that the preceding example requires the following configuration file:
====
[source,yml,indent=0]
----
include::{stubrunner_core_path}/src/test/resources/application.yml[tags=ids]
----
====
[[features-stub-runner-cloud-stubbing-profiles]]
===== Test profiles and service discovery
===== Test Profiles and Service Discovery
In your integration tests you typically don't want to call neither a discovery service (e.g. Eureka)
or Config Server. That's why you create an additional test configuration in which you want to disable
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 https://github.com/spring-cloud/spring-cloud-commons/issues/156[`spring-cloud-commons`] to achieve this you have disable these properties
via a static block like presented below (example for Eureka)
Due to certain limitations of https://github.com/spring-cloud/spring-cloud-commons/issues/156[`spring-cloud-commons`],
to achieve this, you have to disable these properties
in a static block such as the following example (for Eureka):
====
[source,java]
----
//Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
@@ -524,75 +592,80 @@ via a static block like presented below (example for Eureka)
System.setProperty("spring.cloud.config.failFast", "false");
}
----
====
[[features-stub-runner-additional-config]]
==== Additional Configuration
You can match the artifactId of the stub with the name of your app by using the `stubrunner.idsToServiceIds:` map.
You can disable Stub Runner Ribbon support by providing: `stubrunner.cloud.ribbon.enabled` equal to `false`
You can disable Stub Runner support by providing: `stubrunner.cloud.enabled` equal to `false`
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`
TIP: By default all service discovery will be stubbed. That means that regardless of the fact if you have
an existing `DiscoveryClient` its results will be ignored. However, if you want to reuse it, just set
`stubrunner.cloud.delegate.enabled` to `true` and then your existing `DiscoveryClient` results will be
TIP: 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
via the following system properties or environment variables
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
- `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
[[features-stub-runner-boot]]
=== Stub Runner Boot Application
=== Using the Stub Runner Boot Application
Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to
trigger the messaging labels and to access started WireMock servers.
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.
One of the use cases is to run some smoke (end-to-end) tests on a deployed application.
You can check out the https://github.com/spring-cloud/spring-cloud-pipelines[Spring Cloud Pipelines]
project for more information.
[[features-stub-runner-boot-how]]
==== How to use it?
[[features-stub-runner-boot-server]]
===== Stub Runner Server
Just add the
To use the Stub Runner Server, add the following dependency:
====
[source,groovy,indent=0]
----
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
----
====
Annotate a class with `@EnableStubRunnerServer`, build a fat-jar and you're ready to go!
Then annotate a class with `@EnableStubRunnerServer`, build a fat jar, and it is ready to work.
For the properties check the *Stub Runner Spring* section.
For the properties, see the <<features-stub-runner-rule-spring,Stub Runner Spring>> section.
[[features-stub-runner-boot-how-fat-jar]]
===== Stub Runner Server Fat Jar
You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:
You can download a standalone JAR from Maven (for example, for version 2.0.1.RELEASE)
by running the following commands:
====
[source,bash,indent=0]
----
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
----
====
[[features-stub-runner-boot-how-cli]]
===== Spring Cloud CLI
Starting from `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[Spring Cloud CLI]
project you can start Stub Runner Boot by executing `spring cloud stubrunner`.
Starting from the `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[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:
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
====
[source,yml,indent=0]
----
stubrunner:
@@ -600,31 +673,42 @@ stubrunner:
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`.
Then you can call `spring cloud stubrunner` from your terminal window to start
the Stub Runner server. It is available at port `8750`.
[[features-stub-runner-boot-endpoints]]
==== Endpoints
Stub Runner Boot offers two endpoints:
* <<features-stub-runner-boot-endpoints-http>>
* <<features-stub-runner-boot-endpoints-messaging>>
[[features-stub-runner-boot-endpoints-http]]
===== HTTP
- GET `/stubs` - returns a list of all running stubs in `ivy:integer` notation
- GET `/stubs/{ivy}` - returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only)
For HTTP, Stub Runner Boot makes the following endpoints available:
- GET `/stubs`: Returns a list of all running stubs in `ivy:integer` notation
- GET `/stubs/{ivy}`: Returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only)
[[features-stub-runner-boot-endpoints-messaging]]
===== Messaging
For Messaging
For Messaging, Stub Runner Boot makes the following endpoints available:
- GET `/triggers` - returns a list of all running labels in `ivy : [ label1, label2 ...]` notation
- POST `/triggers/{label}` - executes a trigger with `label`
- POST `/triggers/{ivy}/{label}` - executes a trigger with `label` for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only)
- GET `/triggers`: Returns a list of all running labels in `ivy : [ label1, label2 ...]` notation
- POST `/triggers/{label}`: Runs a trigger with `label`
- POST `/triggers/{ivy}/{label}`: Runs a trigger with a `label` for the given `ivy` notation
(when calling the endpoint, `ivy` can also be `artifactId` only)
[[features-stub-runner-boot-endpoints-example]]
==== Example
The following example shows typical usage of Stub Runner Boot:
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/server/StubRunnerBootSpec.groovy[tags=boot_usage]
@@ -633,55 +717,59 @@ include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contra
[[features-stub-runner-boot-service-discovery]]
==== Stub Runner Boot with Service Discovery
One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean?
Let's assume that you don't want to deploy 50 microservice to a test environment in order
to check if your application is working fine. You've already executed a suite of tests during the build process
but you would also like to ensure that the packaging of your application is fine. What you can do
is to deploy your application to an environment, start it and run a couple of tests on it to see if
it's working fine. We can call those tests smoke-tests since their idea is to check only a handful
of testing scenarios.
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 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.
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):
====
[source,java,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka]
----
====
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`.
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 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
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:
====
[source,bash,indent=0]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka_args]
----
====
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
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.
[[features-stub-runner-stubs-per-consumer]]
=== Consumer-Driven Contracts: Stubs Per Consumer
There are cases in which 2 consumers of the same endpoint want to have 2 different responses.
There are cases in which two consumers of the same endpoint want to have two different responses.
TIP: 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.
TIP: 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.
Let's look at the following example for contract defined for the producer called `producer`.
There are 2 consumers: `foo-consumer` and `bar-consumer`.
*Consumer `foo-service`*
Consider the following example of a contract defined for the producer called `producer`,
which has two consumers (`foo-consumer` and `bar-consumer`):
====
.Consumer `foo-service`
[source,groovy]
----
request {
@@ -696,12 +784,11 @@ response {
}
----
*Consumer `bar-service`*
.Consumer `bar-service`
[source,groovy]
----
request {
url '/foo'
url '/bar'
method GET()
}
response {
@@ -711,14 +798,15 @@ response {
}
}
----
====
You can't produce for the same request 2 different responses. That's why you can properly package the
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'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 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
@@ -734,36 +822,40 @@ On the `foo` producer side the contracts would look like this
└── shouldCallFoo.groovy
----
Being the `bar-consumer` consumer you can either set the `spring.application.name` or the `stubrunner.consumer-name` to `bar-consumer`
Or set the test as follows:
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:
====
[source,groovy]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerSpec.groovy[tags=test]
...
}
----
====
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 `bar-consumer` in its name (that is, those from the
`src/test/resources/contracts/bar-consumer/some/contracts/...` folder) are allowed to be referenced.
Or set the consumer name explicitly
You can also set the consumer name explicitly, as follows:
====
[source,groovy]
----
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerWithConsumerNameSpec.groovy[tags=test]
...
}
----
====
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.
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.
You can check out https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more
See https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more
information about the reasons behind this change.
[[features-stub-runner-common]]
=== Common
=== Common Properties
This section briefly describes common properties, including:
@@ -774,14 +866,14 @@ This section briefly describes common properties, including:
==== Common Properties for JUnit and Spring
You can set repetitive properties by using system properties or Spring configuration
properties. Here are their names with their default values:
properties. The following table shows their names with their default values:
[frame="topbot",options="header"]
|===============
| 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.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.
@@ -789,29 +881,31 @@ properties. Here are their names with their default values:
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
|stubrunner.stubsPerConsumer|`false`| Set to `true` if you want to use different stubs for
each consumer instead of registering all stubs for every consumer.
|stubrunner.consumerName|| If you want to use a stub for each consumer and want to
override the consumer name just change this value.
override the consumer name, change this value.
|===============
[[features-stub-runner-stub-runner-stub-ids]]
==== Stub Runner Stubs IDs
You can provide the stubs to download via the `stubrunner.ids` system property. They
follow this pattern:
You can set the stubs to download in the `stubrunner.ids` system property. They
use the following pattern:
====
[source,java,indent=0]
----
groupId:artifactId:version:classifier:port
----
====
Note that `version`, `classifier` and `port` are optional.
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 `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 the `+` will be passed and the latest one is
* If you do not provide the `version`, then `+` is passed, and the latest one is
downloaded.
`port` means the port of the WireMock server.
@@ -819,4 +913,4 @@ downloaded.
IMPORTANT: 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
https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning
ranges here].
ranges here].

View File

@@ -8,34 +8,38 @@ https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samp
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
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:
====
[source,java,indent=0]
----
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1]
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2]
----
====
To start the stub server on a different port use (for example),
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.
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.
[[features-wiremock-registering-stubs]]
=== Registering Stubs Automatically
If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file
system or classpath (by default, from `file:src/test/resources/mappings`). You can
customize the locations using the `stubs` attribute in the annotation, which can be an
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:
====
----
@RunWith(SpringRunner.class)
@SpringBootTest
@@ -52,35 +56,40 @@ public class WiremockImportApplicationTests {
}
----
====
NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as
well as* the custom locations in the stubs attribute. To change this behavior, you can
also specify a files root as described in the next section of this document.
well as* the custom locations in the `stubs` attribute. To change this behavior, you can
also specify a files root, as described in the next section of this document.
If you're using Spring Cloud Contract's default stub jars, then your
stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax.
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:
====
[source,java,indent=0]
----
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs]
----
====
[[features-wiremock-using-files]]
=== Using Files to Specify the Stub Bodies
WireMock can read response bodies from files on the classpath or the file system. In that
case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a
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`
`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
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.
NOTE: 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
in a subdirectory called `mappings`. The value of `files` has no
effect on the stubs loaded explicitly from the `stubs` attribute.
[[features-wiremock-junit-rule]]
@@ -88,13 +97,15 @@ 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 shown in the following example:
instance, as the following example shows:
====
[source,java,indent=0]
----
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1]
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2]
----
====
The `@ClassRule` means that the server shuts down after all the methods in this class
have been run.
@@ -102,16 +113,17 @@ have been run.
[[features-wiremock-relaxed-ssl]]
=== Relaxed SSL Validation for Rest Template
WireMock lets you stub a "secure" server with an "https" URL protocol. If your
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
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 be using the Spring Boot
`RestTemplateBuilder` in your app, as shown in the following example:
To make this work with minimum fuss, you need to use the Spring Boot
`RestTemplateBuilder` in your application, as the following example shows:
====
[source,java,indent=0]
----
@Bean
@@ -119,13 +131,15 @@ To make this work with minimum fuss, you need to be using the Spring Boot
return builder.build();
}
----
====
You need `RestTemplateBuilder` because the builder is passed through callbacks to
initialize it, so the SSL validation can be set up in the client at that point. This
happens automatically in your test if you are using the `@AutoConfigureWireMock`
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 shown in the following example:
`@AutoConfigureHttpClient` annotation as well, as the following example shows:
====
[source,java,indent=0]
----
@RunWith(SpringRunner.class)
@@ -139,11 +153,12 @@ public class WiremockHttpsServerApplicationTests {
...
}
----
====
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
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
won't do any harm). There is no support currently for other clients, but it may be added
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`
@@ -155,21 +170,23 @@ 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:
====
[source,java,indent=0]
----
include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test]
----
====
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
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
https://wiremock.org/docs/stubbing/[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
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).
Wiremock dependencies and exclude the Spring Boot container (if there is one).

View File

@@ -2,12 +2,12 @@
= Spring Cloud Contract customization
include::_attributes.adoc[]
In this section we describe how to customize various parts of Spring Cloud Contract.
In this section, we describe how to customize various parts of Spring Cloud Contract.
[[customization-customization]]
== DSL Customization
IMPORTANT: This section is valid only for Groovy DSL
IMPORTANT: This section is valid only for the Groovy DSL
You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in
the remainder of this section.
@@ -29,35 +29,45 @@ https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here].
The following examples show three classes that can be reused in the DSLs.
*PatternUtils* contains functions used by both the **consumer** and the **producer**.
`PatternUtils` contains functions used by both the consumer and the producer.
The following listing shows the `PatternUtils` class:
====
[source,java]
----
include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[]
----
====
*ConsumerUtils* contains functions used by the **consumer**.
`ConsumerUtils` contains functions used by the consumer.
The following listing shows the `ConsumerUtils` class:
====
[source,java]
----
include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[]
----
====
*ProducerUtils* contains functions used by the **producer**.
`ProducerUtils` contains functions used by the producer.
The following listing shows the `ProducerUtils` class:
====
[source,java]
----
include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[]
----
====
[[customization-test-dep]]
=== Add a test dependency in the Project's Dependencies
=== Adding a Test Dependency in the Project's Dependencies
First, add the common jar dependency as a test dependency. Because your contracts files
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:
==
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
@@ -69,15 +79,15 @@ include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0]
----
include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0]
----
==
====
[[customization-plugin-dep]]
=== Add a test dependency in the Plugin's Dependencies
=== Adding a Test Dependency in the Plugin's Dependencies
Now, you must add the dependency for the plugin to reuse at runtime, as shown in the
following example:
Now, you must add the dependency for the plugin to reuse at runtime, as the
following example shows:
==
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
@@ -89,24 +99,28 @@ include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0]
----
include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0]
----
==
====
[[customization-referencing]]
=== Referencing classes in DSLs
=== Referencing Classes in DSLs
You can now reference your classes in your DSL, as shown in the following example:
You can now reference your classes in your DSL, as the following example shows:
====
[source,groovy]
----
include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0]
----
====
IMPORTANT: 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.
IMPORTANT: 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.
[[customization-wiremock]]
== WireMock customization
== WireMock Customization
In this section you will learn how to customize the way you work with https://wiremock.org[WireMock].
In this section, we show how to customize the way you work with https://wiremock.org[WireMock].
[[customization-wiremock-extension]]
=== Registering Your Own WireMock Extension
@@ -115,44 +129,50 @@ WireMock lets you register custom extensions. By default, Spring Cloud Contract
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
Since we use the `spring.factories` extension approach, you can create an entry in
`META-INF/spring.factories` file similar to the following:
====
[source,groovy,indent=0]
----
include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0]
----
====
The following is an example of a custom extension:
The following example shows a custom extension:
.TestWireMockExtensions.groovy
====
[source,groovy,indent=0]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0]
----
====
IMPORTANT: 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.
[[customization-wiremock-configuration]]
=== Customization of WireMock configuration
=== Customization of WireMock Configuration
You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type
in order to customize the WireMock configuration (e.g. add custom transformers).
Example:
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:
====
[source,java,indent=0]
----
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1]
// perform your customization here
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2]
----
====
[[customization-pluggable-architecture]]
== Using the Pluggable Architecture
You may encounter cases where you have your contracts have been defined in other formats,
such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic
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
@@ -164,10 +184,12 @@ 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:
====
[source,java]
----
include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/ContractConverter.java[indent=0,lines=17..-1]
----
====
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.
@@ -178,11 +200,13 @@ implementation.
The following example shows a typical `spring.factories` file:
====
[source]
----
org.springframework.cloud.contract.spec.ContractConverter=\
org.springframework.cloud.contract.verifier.converter.YamlContractConverter
----
====
[[customization-custom-test-generator]]
=== Using the Custom Test Generator
@@ -193,19 +217,23 @@ 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:
====
[source,groovy]
----
include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.java[indent=0,lines=17..-1]
----
====
Again, you must provide a `spring.factories` file, such as the one shown in the following
example:
====
[source]
----
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
com.example.MyGenerator
----
====
[[customization-custom-stub-generator]]
=== Using the Custom Stub Generator
@@ -214,18 +242,22 @@ If you want to generate stubs for stub servers other than WireMock, you can plug
own implementation of the `StubGenerator` interface. The following code listing shows the
`StubGenerator` interface:
====
[source,groovy]
----
include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1]
----
====
Again, you must provide a `spring.factories` file, such as the one shown in the following
example:
====
[source]
----
include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0]
----
====
The default implementation is the WireMock stub generation.
@@ -244,31 +276,36 @@ 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:
====
[source,groovy]
----
include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1]
----
====
Then, you can register it in your `spring.factories` file, as shown in the following
example:
Then you can register it in your `spring.factories` file, as the following
example shows:
====
[source]
----
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
----
====
Now you can run stubs with Moco.
IMPORTANT: If you do not provide any implementation, then the default (WireMock)
IMPORTANT: 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.
[[customization-custom-stub-downloader]]
=== Using the Custom Stub Downloader
You can customize the way your stubs are downloaded by creating an implementation of the
`StubDownloaderBuilder` interface, as shown in the following example:
`StubDownloaderBuilder` interface, as the following example shows:
====
[source,java]
----
package com.example;
@@ -292,36 +329,39 @@ class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
}
}
----
====
Then you can register it in your `spring.factories` file, as shown in the following
example:
Then you can register it in your `spring.factories` file, as the following
example shows:
====
[source]
----
# 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.
IMPORTANT: If you do not provide any implementation, then the default is used (scan classpath).
IMPORTANT: 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` then the Aether implementation will be used
If you provide more than one, then the first one on the list is used.
`stubsMode = StubRunnerProperties.StubsMode.REMOTE`, the Aether implementation is used
If you provide more than one, the first one on the list is used.
[[scm-stub-downloader]]
=== Using the SCM Stub Downloader
Whenever the `repositoryRoot` starts with a SCM protocol
(currently we support only `git://`), the stub downloader will try
(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.
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
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:
.SCM Stub Downloader properties
|====
@@ -369,5 +409,5 @@ properties
* `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop)
|1000
|Number of millis to wait between attempts to push the commits to `origin`
|Number of milliseconds to wait between attempts to push the commits to `origin`
|====

View File

@@ -2,139 +2,151 @@
= Docker Project
include::_attributes.adoc[]
We're publishing a `springcloud/spring-cloud-contract` Docker image
that contains a project that will generate tests and execute them in `EXPLICIT` mode
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.
TIP: The `EXPLICIT` mode means that the tests generated from contracts will send
TIP: The `EXPLICIT` mode means that the tests generated from contracts send
real requests and not the mocked ones.
We're also publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
that will start the standalone version of Stub Runner.
We also publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
that starts the standalone version of Stub Runner.
[[docker-intro]]
== Short intro to Maven, JARs and Binary storage
== A Short Introduction to Maven, JARs and Binary storage
Since the Docker image can be used by non JVM projects, it's good to
Since non-JVM projects can use the Docker image, it is good to
explain the basic terms behind Spring Cloud Contract packaging defaults.
Part of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary]
Parts of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary]:
- `Project`: Maven thinks in terms of projects. Everything that you
will build are projects. Those projects follow a well defined
- `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
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
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. It's a format based on
- `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 (eg. commons-collections),
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 (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/`.
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 additional suffix
passed to the dependency. E.g. `stubs`, `sources`. The same dependency
e.g. `com.example:application` can produce multiple artifacts that
`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 / 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 https://jfrog.com/artifactory/[Artifactory]
- `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 https://jfrog.com/artifactory/[Artifactory]
or https://www.sonatype.org/nexus/[Nexus].
[[docker-how-it-works]]
== Generating tests on the producer side
== Generating Tests on the Producer Side
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
The output from running the tests is available in the
`/spring-cloud-contract/build` folder (useful for debugging
purposes).
It's enough for you to mount your contracts, pass the environment variables
and the image will:
You can mount your contracts and pass the environment variables.
The image then:
- generate the contract tests
- execute the tests against the provided URL
- generate the https://github.com/tomakehurst/wiremock[WireMock] stubs
- (optional - turned on by default) publish the stubs to a Artifact Manager
- Generates the contract tests
- Runs the tests against the provided URL
- Generates the https://github.com/tomakehurst/wiremock[WireMock] stubs
- Publishes the stubs to a Artifact Manager (optional - turned on by default)
[[docker-env-vars]]
=== Environment Variables
The Docker image requires some environment variables to point to
your running application, to the Artifact manager instance etc.
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` - artifact id. Defaults to `example`
- `PRODUCER_STUBS_CLASSIFIER` - archive classifier used for generated producer stubs, defaults to `stubs`.
- `REPO_WITH_BINARIES_URL` - URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local`
which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally
- `REPO_WITH_BINARIES_USERNAME` - (optional) username when the Artifact Manager is secured, defaults to `admin`.
- `REPO_WITH_BINARIES_PASSWORD` - (optional) password when the Artifact Manager is secured, defaults to `password`.
- `PUBLISH_ARTIFACTS` - if set to `true` then will publish artifact to binary storage. Defaults to `true`.
- `PROJECT_GROUP`: Your project's group ID. Defaults to `com.example`.
- `PROJECT_VERSION`: Your project's version. Defaults to `0.0.1-SNAPSHOT`.
- `PROJECT_NAME`: Your project's artifact id. Defaults to `example`.
- `PRODUCER_STUBS_CLASSIFIER`: Archive classifier used for generated producer stubs. Defaults to `stubs`.
- `REPO_WITH_BINARIES_URL`: URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local`,
which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally.
- `REPO_WITH_BINARIES_USERNAME`: (optional) Username when the Artifact Manager is secured. Defaults to `admin`.
- `REPO_WITH_BINARIES_PASSWORD`: (optional) Password when the Artifact Manager is secured. Defaults to `password`.
- `PUBLISH_ARTIFACTS`: If set to `true`, publishes the artifact to binary storage. Defaults to `true`.
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.
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 https://jfrog.com/artifactory/[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-server-side.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
- `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 `http://localhost:8081/artifactory/libs-release-local`,
which is the default URL of https://jfrog.com/artifactory/[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`.
These environment variables are used when tests are executed:
WARNING: You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`.
- `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
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.
[[docker-example-of-usage]]
=== Example of usage
=== Example of Usage
Let's take a look at a simple MVC 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:
```bash
====
[source,bash]
----
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore
```
----
====
The contracts are available under `/contracts` folder.
The contracts are available in the `/contracts` folder.
Since we want to run tests, we could just execute:
Since we want to run tests, we can run the following command:
```bash
====
[source,bash]
----
$ npm test
```
----
====
however, for learning purposes, let's split it into pieces:
However, for learning purposes, we split it into pieces, as follows:
```bash
====
[source,bash]
----
# Stop docker infra (nodejs, artifactory)
$ ./stop_infra.sh
# Start docker infra (nodejs, artifactory)
@@ -160,61 +172,68 @@ $ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH
# Kill app
$ pkill -f "node app"
```
----
====
What will happen is that via bash scripts:
Through bash scripts, the following happens:
- 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
- The infrastructure (MongoDb and Artifactory) is set up.
In a real-life scenario, you would run the NodeJS application
with a mocked database. In this example, we want to show how we can
benefit from Spring Cloud Contract in very little time.
- Due to those constraints, the contracts also represent the
stateful situation.
** The first request is a `POST` that causes data to get inserted to the database.
** The second request is a `GET` that returns a list of data with 1 previously inserted element.
- The NodeJS application is started (on port `3000`).
- The contract tests are generated through Docker, and tests
are run against the running application.
** The contracts are taken from `/contracts` folder.
** The output of the test execution is available under
`node_modules/spring-cloud-contract/output`.
- the stubs will be uploaded to Artifactory. You can check them out
under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ .
The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.
- The stubs are uploaded to Artifactory. You can find them in
http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ .
The stubs are at http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.
[[docker-stubrunner]]
== Running stubs on the consumer side
== Running Stubs on the Consumer Side
This section describes hot to use Docker on the consumer side to fetch and run stubs.
This section describes how to use Docker on the consumer side to fetch and run stubs.
We're publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
that will start the standalone version of Stub Runner.
We publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
that starts the standalone version of Stub Runner.
[[docker-stubrunner-env-vars]]
=== Environment variables
=== Environment Variables
Just execute the docker image. You can pass any of the <<project-features.adoc#features-stub-runner-common-properties-junit-spring, Common Properties for JUnit and Spring>>
You can run the docker image and pass any of the <<project-features.adoc#features-stub-runner-common-properties-junit-spring, 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.
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.
[[docker-stubrunner-example]]
=== Example of usage
=== Example of Usage
We'd like to use the stubs created in this <<docker-server-side>> step.
Let's assume that we want to run the stubs on port `9876`. The NodeJS code
is available here:
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:
```bash
====
[source,bash]
----
$ 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.
Now we can run the Stub Runner Boot application with the stubs, by running the following
commands:
```bash
====
[source,bash]
----
# 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
@@ -226,27 +245,31 @@ $ 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
When the preceding commands run,
- a standalone Stub Runner application got started
- it downloaded the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876`
- it got downloaded from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local`
- after a while Stub Runner will be running on port `8083`
- and the stubs will be running at port `9876`
- A standalone Stub Runner application gets started.
- It downloads the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876`.
- It gets downloads from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local`.
- After a whil, Stub Runner is running on port `8083`.
- The stubs are running at port `9876`.
On the server side we built a stateful stub. Let's use curl to assert
that the stubs are setup properly.
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:
```bash
====
[source,bash]
----
# 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
```
----
====
IMPORTANT: 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"`
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"`).

View File

@@ -9,10 +9,11 @@ as a map for the rest of the document.
[[contract-documentation-about]]
== About the Documentation
The {project-full-name} reference guide is available as
* {docs-url}/html[Multi-page HTML]
* {docs-url}/htmlsingle[Single page HTML]
* {docs-url}/htmlsingle[Single-page HTML]
* {docs-url}/pdf/{project-name}.pdf[PDF]
Copies of this document may be made for your own use and for distribution to others,
@@ -50,9 +51,9 @@ If you are getting started with {project-full-name} or 'Spring' in general, star
<<getting-started.adoc#getting-started-first-application, First application>>
* *Tutorial:*
<<getting-started.adoc#getting-started-cdc, Introduction>> |
<<getting-started.adoc#consumer-side-loan-issuance, Consumer Part 1>> |
<<getting-started.adoc#consumer-side-loan-issuance, Consumer, Part 1>> |
<<getting-started.adoc#producer-side-fraud-detection-server, Producer>> |
<<getting-started.adoc#consumer-side-loan-issuance-final-step, Consumer Part 2>>
<<getting-started.adoc#consumer-side-loan-issuance-final-step, Consumer, Part 2>>
@@ -62,9 +63,9 @@ you covered>>:
* *Provider contract testing:*
** <<using.adoc#flows-provider-nexus,Provider contract testing with stubs in Nexus / Artifactory>>
** <<using.adoc#flows-provider-nexus,Provider contract testing with stubs in Nexus or Artifactory>>
** <<using.adoc#flows-provider-git,Provider contract testing with stubs in Git>>
** <<using.adoc#flows-provider-non-spring,Provider contract testing with stubs in Artifactory for a non Spring application>>
** <<using.adoc#flows-provider-non-spring,Provider contract testing with stubs in Artifactory for a non-Spring application>>
** <<using.adoc#flows-provider-non-jvm,Provider contract testing with stubs in Artifactory in non JVM world>>
** <<using.adoc#flows-provider-rest-docs,Provider contract testing with REST Docs and stubs in Nexus / Artifactory>>
@@ -73,14 +74,14 @@ you covered>>:
** <<using.adoc#flows-cdc-contracts-external,Consumer Driven Contracts with contracts in external repo>>
** <<using.adoc#flows-cdc-contracts-stubs-git,Consumer Driven Contracts with contracts on the producer side, pushed to git>>
TIP: We talk about *Provider Contracts* when it's 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 can't
directly collaborate with their consumers; for example, when there are too many consumers,
the consumers are external (don't work within the same company).
TIP: 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).
TIP: 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; it's the recommended approach, easy
to implement when both producer and consumer teams work for the same organisations and the number
TIP: 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.
== Learning about {project-full-name} Features
@@ -109,20 +110,19 @@ link:docker-project.html[Docker]
== Advanced Topics
Finally, we have a few topics for more advanced users:
* *Customizing DSL:*
<<advanced.adoc#contract-dsl-customization, DSL customization>> |
* *Customizing the DSL:*
<<advanced.adoc#contract-dsl-customization, DSL Customization>> |
<<advanced.adoc#contract-dsl-extending-common-jar, Common JAR>> |
<<advanced.adoc#contract-dsl-test-dep, Test dependency>> |
<<advanced.adoc#contract-dsl-plugin-dep, Plugin dependency>> |
<<advanced.adoc#contract-dsl-referencing, Referencing DSL>>
<<advanced.adoc#contract-dsl-test-dep, Test Dependency>> |
<<advanced.adoc#contract-dsl-plugin-dep, Plugin Dependency>> |
<<advanced.adoc#contract-dsl-referencing, Referencing the DSL>>
* *Customizing WireMock:*
<<advanced.adoc#customization-wiremock-extension, Extensions>> |
<<advanced.adoc#customization-wiremock-configuration, Configuration>>
* *Customizing {project-full-name}:*
<<advanced.adoc#contract-dsl-pluggable-architecture, Pluggable architecture>> |
<<advanced.adoc#contract-dsl-pluggable-architecture, Pluggable Architecture>> |
<<advanced.adoc#contract-dsl-custom-contract-converter, Contract Converter>> |
<<advanced.adoc#contract-dsl-custom-test-generator, Test Generator>> |
<<advanced.adoc#contract-dsl-custom-stub-generator, Stub Generator>> |
<<advanced.adoc#contract-dsl-custom-stub-runner, Stub Runner>> |
<<advanced.adoc#contract-dsl-custom-stub-downloader, Stub Downloader>>

File diff suppressed because it is too large Load Diff

View File

@@ -21,18 +21,19 @@ following sections:
[[gradle-prerequisites]]
== Prerequisites
In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a
In order to use Spring Cloud Contract Verifier with WireMock, you must use either a
Gradle or a Maven plugin.
WARNING: If you want to use Spock in your projects, you must add separately the
`spock-core` and `spock-spring` modules. Check https://spockframework.github.io/[Spock
docs for more information]
WARNING: If you want to use Spock in your projects, you must separately add the
`spock-core` and `spock-spring` modules. See https://spockframework.github.io/[Spock's
documnetation for more information]
[[gradle-add-gradle-plugin]]
== Add Gradle Plugin with Dependencies
To add a Gradle plugin with dependencies, use code similar to this:
To add a Gradle plugin with dependencies, you can use code similar to the following:
====
[source,groovy,indent=0]
----
buildscript {
@@ -62,13 +63,15 @@ dependencies {
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
}
----
====
[[gradle-and-rest-assured]]
== Gradle and Rest Assured 2.0
By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x
you can add it to the plugins classpath, as shown here:
you can add it to the plugins classpath, as the following listing shows:
====
[source,groovy,indent=0]
----
buildscript {
@@ -90,6 +93,7 @@ depenendencies {
testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
}
----
====
That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
and modifies the imports accordingly.
@@ -97,43 +101,48 @@ and modifies the imports accordingly.
[[gradle-snapshot-versions]]
== Snapshot Versions for Gradle
Add the additional snapshot repository to your build.gradle to use snapshot versions,
which are automatically uploaded after every successful build, as shown here:
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:
====
[source,groovy,indent=0]
----
include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0]
}
----
====
[[gradle-add-stubs]]
== Add stubs
By default, Spring Cloud Contract Verifier is looking for stubs in the
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
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. For example, with following structure:
as the package name. Consider the following structure:
====
[source,groovy,indent=0]
----
src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy
----
====
Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService`
with two methods:
Given the preceding structure, Spring Cloud Contract Verifier creates a test class named
`defaultBasePackage.MyService` with two methods:
- `shouldCreateUser()`
- `shouldReturnUser()`
- `shouldCreateUser()`
- `shouldReturnUser()`
[[gradle-run-plugin]]
== Run the Plugin
== Running the Plugin
The plugin registers itself to be invoked before a `check` task. If you want it to be
part of your build process, you need to do nothing more. If you just want to generate
part of your build process, you need do nothing more. If you just want to generate
tests, invoke the `generateContractTests` task.
[[gradle-default-setup]]
@@ -142,6 +151,7 @@ tests, invoke the `generateContractTests` task.
The default Gradle Plugin setup creates the following Gradle part of the build (in
pseudocode):
====
[source,groovy,indent=0]
----
contracts {
@@ -190,13 +200,15 @@ publishing {
}
}
----
====
[[gradle-configure-plugin]]
== Configure Plugin
== Configuring the Plugin
To change the default configuration, add a `contracts` snippet to your Gradle config, as
shown here:
To change the default configuration, you can add a `contracts` snippet to your Gradle
configuration, as the following listing shows:
====
[source,groovy,indent=0]
----
contracts {
@@ -205,79 +217,85 @@ contracts {
generatedTestSourcesDir = project.file('src/generatedContract')
}
----
====
[[gradle-configuration-options]]
== Configuration Options
* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc,
which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to
*Explicit* for real HTTP calls.
* *imports*: Creates an array with imports that should be included in generated tests
(for example ['org.myorg.Matchers']). By default, it creates an empty array.
* *staticImports*: Creates an array with static imports that should be included in
generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty
* `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 `baseClassForTests`'s package and from `packageWithBaseClasses`.
If neither of these values are set, then the value is set to
* `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
* `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
* `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
* `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
* `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
* `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
* `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
* `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 containing properties to be passed to Spring Cloud Contract
components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.
* `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.
The following properties are used when you want to specify the location of the JAR
containing the contracts:
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
* `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
* `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
* `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.
Below you can find a list of experimental features you can turn on via the plugin:
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'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.
* `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.
[[gradle-single-base-class]]
== Single Base Class for All Tests
When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base
specification for all generated acceptance tests. In this class, you need to point to an
endpoint, which should be verified.
endpoint, which should be verified. The following example shows how to do so:
====
[source,groovy,indent=0]
----
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0]
----
====
If you use `Explicit` mode, you can use a base class to initialize the whole tested app
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.
@@ -289,40 +307,44 @@ If your base classes differ between contracts, you can tell the Spring Cloud Con
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`
* Provide explicit mapping by using `baseClassMappings`
*By Convention*
=== By Convention
The convention is such that if you have a contract under (for example)
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*.
Here is an example of how it works in the `contracts` closure:
forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`.
The following example shows how it works in the `contracts` closure:
====
[source,groovy,indent=0]
----
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0]
----
====
*By Mapping*
=== By Mapping
You can manually map a regular expression of the contract's package to fully qualified
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 `baseClassMapping` objects that takes a
`baseClassMappings` that consists of `baseClassMapping` objects that take a
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
====
[source,groovy,indent=0]
----
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=base_class_mappings,indent=0]
----
====
Let's assume that you have contracts under
Let's assume that you have contracts in the following directories:
- `src/test/resources/contract/com/`
- `src/test/resources/contract/foo/`
By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed.
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`.
@@ -330,49 +352,58 @@ generated from `src/test/resources/contract/com/` contracts extend the
[[gradle-invoking-generated-tests]]
== Invoking Generated Tests
To ensure that the provider side is compliant with defined contracts, you need to invoke:
To ensure that the provider side is compliant with your defined contracts, you need to run
the following command:
====
[source,bash,indent=0]
----
./gradlew generateContractTests test
----
====
[[gradle-pushing-stubs-to-scm]]
== Pushing stubs to SCM
== Pushing Stubs to SCM
If you're using the SCM repository to keep the contracts and
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, it's enough to call the `pushStubsToScm`
task. Example:
the repository. To do that, you can call the `pushStubsToScm`
task by running the following command:
====
[source,bash,indent=0]
----
$ ./gradlew pushStubsToScm
----
====
Under <<scm-stub-downloader>> you can find all possible
configuration options that you can pass either via
the `contractsProperties` field e.g. `contracts { contractsProperties = [foo:"bar"] }`,
via `contractsProperties` method e.g. `contracts { contractsProperties([foo:"bar"]) }`,
a system property or an environment variable.
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.
[[gradle-consumer]]
== Spring Cloud Contract Verifier on the Consumer Side
In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin
in exactly the same way as in case of provider. If you do not want to use Stub Runner
then you need to copy contracts stored in `src/test/resources/contracts` and generate
WireMock JSON stubs using:
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:
====
[source,bash,indent=0]
----
./gradlew generateClientStubs
----
====
NOTE: 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.
When present, JSON stubs can be used in automated tests to consume a service. The
following example shows how to do so:
====
[source,groovy,indent=0]
----
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
@@ -397,6 +428,8 @@ class LoanApplicationServiceSpec extends Specification {
}
}
----
====
`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a
WireMock server configured with stubs generated by Spring Cloud Contract Verifier.
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.

File diff suppressed because it is too large Load Diff

View File

@@ -9,8 +9,8 @@ The reference documentation consists of the following sections:
[horizontal]
<<legal.adoc#legal-information,Legal>> :: Legal information.
<<documentation-overview.adoc#contract-documentation,Documentation Overview>> :: About the Documentation, Getting Help, First Steps, and more.
<<getting-started.adoc#getting-started,Getting Started>> :: Introducing {project-full-name}, Developing Your First {project-full-name} based Application
<<getting-started.adoc#getting-started,Getting Started>> :: Introducing {project-full-name}, Developing Your First {project-full-name}-based Application
<<using.adoc#using,Using {project-full-name}>> :: {project-full-name} usage examples and workflows
<<project-features.adoc#features,{project-full-name} Features>> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, Spring Cloud Contract WireMock
<<project-features.adoc#features-build-tools,Build Tools>> :: Maven Plugin, Gradle Plugin, Docker
<<project-features.adoc#features,{project-full-name} Features>> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, and Spring Cloud Contract WireMock.
<<project-features.adoc#features-build-tools,Build Tools>> :: Maven Plugin, Gradle Plugin, and Docker.
<<howto.adoc#howto,"`How-to`" Guides>> :: Stubs versioning, Pact integration, Debugging, and more.

View File

@@ -1,7 +1,6 @@
[[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
:docinfo: shared
include::_attributes.adoc[]
include::legal.adoc[leveloffset=+1]
@@ -9,4 +8,4 @@ include::documentation-overview.adoc[leveloffset=+1]
include::getting-started.adoc[leveloffset=+1]
include::using.adoc[leveloffset=+1]
include::project-features.adoc[leveloffset=+1]
include::howto.adoc[leveloffset=+1]
include::howto.adoc[leveloffset=+1]

View File

@@ -18,32 +18,37 @@ following sections:
* <<maven-sts>>
[[maven-add-plugin]]
== Add maven plugin
== Adding the Maven Plugin
Add the Spring Cloud Contract BOM in a fashion similar to this:
Add the Spring Cloud Contract BOM in a fashion similar to the following:
====
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_bom,indent=0]
----
====
Next, add the `Spring Cloud Contract Verifier` Maven plugin:
Next, add the `Spring Cloud Contract Verifier` Maven plugin, as follows:
====
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----
====
You can read more in the
spring-cloud-contract-maven-plugin/index.html[Spring
Cloud Contract Maven Plugin Documentation.
Cloud Contract Maven Plugin Documentation].
[[maven-rest-assured]]
== Maven and Rest Assured 2.0
By default, Rest Assured 3.x is added to the classpath. However, you can use Rest
Assured 2.x by adding it to the plugins classpath, as shown here:
Assured 2.x by adding it to the plugins classpath, as follows:
====
[source,groovy,indent=0]
----
<plugin>
@@ -92,39 +97,44 @@ Assured 2.x by adding it to the plugins classpath, as shown here:
</dependency>
</dependencies>
----
====
That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath
That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
and modifies the imports accordingly.
[[maven-snapshot-versions]]
== Snapshot versions for Maven
== Using Snapshot and Milestone Versions for Maven
For Snapshot and Milestone versions, you have to add the following section to your
`pom.xml`, as shown here:
To use Snapshot and Milestone versions, you have to add the following section to your
`pom.xml`:
====
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
----
====
[[maven-add-stubs]]
== Add stubs
== Adding stubs
By default, Spring Cloud Contract Verifier is looking for stubs in the
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 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:
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:
====
[source,groovy,indent=0]
----
src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy
----
====
Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService`
with two methods
Given that structure, Spring Cloud Contract Verifier creates a test class named
`defaultBasePackage.MyService` with two methods:
* `shouldCreateUser()`
* `shouldReturnUser()`
@@ -132,16 +142,17 @@ with two methods
[[maven-run-plugin]]
== Run plugin
The plugin goal `generateTests` is assigned to be invoked in the phase called
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 just want to generate tests, invoke the `generateTests` goal.
anything. If you want only to generate tests, invoke the `generateTests` goal.
[[maven-configure-plugin]]
== Configure plugin
To change the default configuration, just add a `configuration` section to the plugin
definition or the `execution` definition, as shown here:
To change the default configuration, you can add a `configuration` section to the plugin
definition or the `execution` definition, as follows:
====
[source,xml,indent=0]
----
<plugin>
@@ -162,78 +173,80 @@ definition or the `execution` definition, as shown here:
</configuration>
</plugin>
----
====
[[maven-configuration-options]]
== Configuration Options
* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc,
which is based on Spring's MockMvc. It can also be changed to *WebTestClient*, *JaxRsClient* or to
*Explicit* for real HTTP calls.
* *basePackageForTests*: Specifies the base package for all generated tests. If not set,
the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`.
If neither of these values are set, then the value is set to
* `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
* `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
* `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
* 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 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
* `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`, then Spring
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 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
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 containing properties to be passed to Spring Cloud Contract
components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.
`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.
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.
* `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,
* `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.
* `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.
`+` or `1.0.0.BUILD-SNAPSHOT` do not 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:
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'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.
* `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.
[[maven-single-base]]
== Single Base Class for All Tests
When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base
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.
endpoint, which should be verified. The following example shows how to do so:
====
[source,groovy,indent=0]
----
package org.mycompany.tests
@@ -248,9 +261,11 @@ class MvcSpec extends Specification {
}
}
----
====
You can also setup the whole context if necessary.
You can also setup the whole context if necessary, as the following example shows:
====
[source,java,indent=0]
----
import io.restassured.module.mockmvc.RestAssuredMockMvc;
@@ -274,10 +289,13 @@ public abstract class BaseTestClass {
}
}
----
====
If you use `EXPLICIT` mode, you can use a base class to initialize the whole tested app
similarly, as you might find in regular integration tests.
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:
====
[source,java,indent=0]
----
import io.restassured.RestAssured;
@@ -302,45 +320,50 @@ public abstract class BaseTestClass {
}
}
----
====
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.
now, the only way to test the JAX-RS API is to start a web server.
[[maven-different-base]]
== Different base classes for contracts
== Using Different Base Classes for Contracts
If your base classes differ between contracts, you can tell the Spring Cloud Contract
plugin which class should get extended by the autogenerated tests. You have two options:
* Follow a convention by providing the `packageWithBaseClasses`
* provide explicit mapping via `baseClassMappings`
* Follow a convention by providing a value for `packageWithBaseClasses`
* Provide explicit mapping with `baseClassMappings`
*By Convention*
=== 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:
forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`.
The following example shows how it works in the `contracts` closure:
====
[source,xml,indent=0]
----
include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[tags=convention,indent=0]
----
====
*By Mapping*
=== By Mapping
You can manually map a regular expression of the contract's package to fully qualified
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 `baseClassMapping` objects that takes a
`baseClassMappings` that consists of `baseClassMapping` objects that each take a
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
====
[source,xml,indent=0]
----
include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-baseclass-from-mappings/pom.xml[tags=mapping,indent=0]
----
====
Assume that you have contracts under these two locations:
* `src/test/resources/contract/com/`
@@ -352,14 +375,15 @@ generated from `src/test/resources/contract/com/` contracts extend the
`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`.
[[maven-invoking-generated-tests]]
== Invoking generated tests
== Invoking Generated Tests
The Spring Cloud Contract Maven Plugin generates verification code in a directory called
`/generated-test-sources/contractVerifier` and attaches this directory to `testCompile`
goal.
For Groovy Spock code, use the following:
For Groovy Spock code, you can use the following:
====
[source,xml,indent=0]
----
<plugin>
@@ -391,18 +415,20 @@ For Groovy Spock code, use the following:
</configuration>
</plugin>
----
====
To ensure that provider side is compliant with defined contracts, you need to invoke
To ensure that the provider side is compliant with defined contracts, you need to invoke
`mvn generateTest test`.
[[maven-pushing-stubs-to-scm]]
== Pushing stubs to SCM
== Pushing Stubs to SCM
If you're using the SCM repository to keep the contracts and
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, it's enough to add the `pushStubsToScm`
goal. Example:
the repository. To do that, you can add the `pushStubsToScm`
goal. The following example shows how to do so:
====
[source,xml,indent=0]
----
<plugin>
@@ -440,21 +466,23 @@ goal. Example:
</executions>
</plugin>
----
====
Under <<scm-stub-downloader>> you can find all possible
configuration options that you can pass either via
the `<configuration><contractProperties>` map, a system property
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.
[[maven-sts]]
== Maven Plugin and STS
If you see the following exception while using STS:
The following image shows an exception that you may see when you use STS:
image::{github-raw}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception]
When you click on the error marker you should see something like this:
When you click on the error marker you should see something like the following:
====
[source,bash]
----
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-
@@ -465,9 +493,11 @@ When you click on the error marker you should see something like this:
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`:
====
[source,xml]
----
<build>
@@ -503,27 +533,32 @@ In order to fix this issue, provide the following section in your `pom.xml`:
</pluginManagement>
</build>
----
====
== Maven Plugin with Spock Tests
You can select the http://spockframework.org/[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.
You can select the http://spockframework.org/[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 will have to use a plugin, such as https://github.com/groovy/GMavenPlus[GMavenPlus] plugin,
to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the
First of all, you must use a plugin, such as the https://github.com/groovy/GMavenPlus[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.
Please refer to the example below:
The following example shows how to do so:
====
[source,xml,indent=0]
----
include::{samples_url}/producer_with_spock/pom.xml[tags=gmavenplus-setup,indent=0]
----
====
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:
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:
====
[source,xml,indent=0]
----
include::{samples_url}/producer_with_spock/pom.xml[tags=spock-surefire-setup,indent=0]
----
----
====

View File

@@ -19,9 +19,10 @@ include::_project-features-stubrunner.adoc[]
include::_project-features-wiremock.adoc[]
[[features-build-tools]]
== Build Tools integration
== Build Tools Integration
You can run test generation / stub execution in various ways. The most common ones are
You can run test generation and stub execution in various ways. The most common ones are
as follows:
* link:maven-project.html[Maven]
* link:gradle-project.html[Gradle]
@@ -29,10 +30,11 @@ You can run test generation / stub execution in various ways. The most common on
[[features-whats-next]]
== What to Read Next
If you want to learn more about any of the classes discussed in this section, you can browse the
{github-code}[source code directly]. If you have specific questions, take a look at the
{github-code}[source code directly]. If you have specific questions, see the
<<howto.adoc#howto, how-to>> section.
If you are comfortable with {project-full-name}'s core features, you can continue on and read
about
_<<advanced.adoc, {project-full-name} Advanced features>>_.
<<advanced.adoc, {project-full-name}'s advanced features>>.

View File

@@ -1,8 +1,15 @@
Add Sleuth to your classpath:
== Adding Sleuth to Your Classpath:
Maven
This section details how to add Sleuth to your class path for both Maven and Gradle
```xml
=== Maven
To add Sleuth to your classpath with Maven, add the following elements
to your `pom.xml` file:
====
[source,xml]
----
<dependencyManagement>
<dependencies>
<dependency>
@@ -20,11 +27,17 @@ Maven
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
</dependencies>
```
----
====
Gradle
=== Gradle
```groovy
To add Sleuth to your classpath with Gradle, add the following
to your `build.gradle` file:
====
[src,groovy]
----
buildscript {
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE"
@@ -41,11 +54,15 @@ dependencyManagement {
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-sleuth'
}
```
----
====
As long as Spring Cloud Sleuth is on the classpath any Spring Boot application will generate trace data:
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:
```java
====
[src,java]
----
@SpringBootApplication
@RestController
public class Application {
@@ -63,12 +80,21 @@ public class Application {
}
}
```
----
====
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.
IMPORTANT: instead of logging the request in the handler explicitly, you could set `logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG`
IMPORTANT: instead of logging the request in the handler explicitly, you could set
`logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG`
IMPORTANT: 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.
IMPORTANT: 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.
IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as well as the trace and span ids.
IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as
well as the trace and span IDs.

View File

@@ -1,12 +1,30 @@
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from https://research.google.com/pubs/pub36356.html[Dapper], https://github.com/openzipkin/zipkin[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 https://research.google.com/pubs/pub36356.html[Dapper],
https://github.com/openzipkin/zipkin[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.
## Features
A Span is the basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Spans 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 IDs (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.
* Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible.
* Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client).
* If `spring-cloud-sleuth-zipkin` is available then the app will generate and collect Zipkin-compatible traces via HTTP. By default it sends them to a Zipkin collector service on localhost (port 9411). Configure the location of the service using `spring.zipkin.baseUrl`.
* 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, 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, and the feign client).
* 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`.

View File

@@ -3,34 +3,35 @@
include::_attributes.adoc[]
This section goes into more detail about how you should use {project-full-name}. It covers topics
such as description of flows of how to work with {project-full-name}. We also
such as flows of how to work with {project-full-name}. We also
cover some {project-full-name} best practices.
If you are starting out with {project-full-name}, you should probably read the
_<<getting-started.adoc#getting-started, Getting Started>>_ guide before diving into this
<<getting-started.adoc#getting-started, Getting Started>> guide before diving into this
section.
[[flows-provider-nexus]]
== Provider contract testing with stubs in Nexus / Artifactory
== Provider Contract Testing with Stubs in Nexus or Artifactory
You can check the <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> link to see the provider contract testing with stubs in Nexus / Artifactory flow.
You can check the <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> link to see the provider contract testing with stubs in the Nexus or Artifactory flow.
You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow.
You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step-by-step instruction on how to do this flow.
[[flows-provider-git]]
== Provider contract testing with stubs in Git
== Provider Contract Testing with Stubs in Git
In this flow, we will perform the provider contract testing (producer has no knowledge of how consumers use their API). The stubs will be uploaded to a separate repository (they will not be uploaded to Artifactory / Nexus).
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).
Prerequisites:
=== Prerequisites
* Git repository that
** will contain all the stubs for each producer
** for an example of such a project you can check the samples
{samples_code}/contract_git[check the samples ] or {samples_code}/contract_git[check the samples here]
** as a result of pushing stubs there, the repository will have the following structure
+
```
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
{samples_code}/contract_git[this samples ] or {samples_code}/contract_git[this sample].
As a result of pushing stubs there, the repository has the following structure:
====
[src, bash]
----
$ tree .
└── META-INF
   └── folder.with.group.id.as.its.name
@@ -40,24 +41,33 @@ $ tree .
   ├── contractB.yml
   └── contractC.groovy
```
* Consumer code that has Spring Cloud Contract Stub Runner setup
** for an example of such a project you can {samples_code}/consumer[check the samples] and search for a `BeerControllerGitTest` test
* Producer code that has Spring Cloud Contract setup together with a plugin
** for an example of such a project you can {samples_code}/producer_with_empty_git[check the samples]
----
====
You must also provide consumer code that has Spring Cloud Contract Stub Runner set up. For
an example of such a project, see {samples_code}/consumer[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
{samples_code}/producer_with_empty_git[this sample].
[[flows-provider-git-flow]]
=== The flow
=== The Flow
The flow looks exactly as the one presented in he <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> section, but the `Stub Storage` implementation will be a git repository.
The flow looks exactly as the one presented in
<<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>>,
but the `Stub Storage` implementation is a git repository.
You can read more about setting up git repository as a git storage and setting consumer and producer side in the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
You can read more about setting up a git repository and setting consumer and producer side
in the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
[[flows-provider-git-consumer]]
=== Consumer setup
In order to fetch the stubs from a git repository instead of Nexus / Artifactory, you need to use the `git` protocol in the URL of the `repositoryRoot` property in Stub Runner. Below you have an example of how to set it up.
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:
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
.Annotation
----
@@ -86,11 +96,15 @@ stubsMode = StubRunnerProperties.StubsMode.REMOTE,
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
----
====
[[flows-provider-git-producer]]
=== Producer setup
=== Setting up the Producer
In order to push the stubs to a git repository instead of Nexus / 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.
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:
====
[source,xml,indent=0,role="primary"]
@@ -161,69 +175,94 @@ publish.dependsOn("publishStubsToScm")
----
====
You can read more about setting up git repository as a git storage in the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
You can read more about setting up a git repository in the
<<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
[[flows-cdc-contracts-producer]]
== Consumer Driven Contracts with contracts on the producer side
== Consumer Driven Contracts with Contracts on the Producer Side
You can check the <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side>> link to see the Consumer Driven Contracts with contracts on the producer side flow.
See <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven
Contracts (CDC) with Contracts on the Producer Side>> to see the Consumer Driven Contracts
with contracts on the producer side flow.
[[flows-cdc-contracts-external]]
== Consumer Driven Contracts with contracts in external repo
== Consumer Driven Contracts with Contracts in an External Repository
In this flow, we will perform Consumer Driven Contract testing. The contract definitions will be stored in a separate repository.
In this flow, we perform Consumer Driven Contract testing. The contract definitions are
stored in a separate repository.
You can check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step by step instruction on how to do this flow.
See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page]
for step-by-step instructions on how to do this flow.
Prerequisites:
=== Prerequisites
* Git repository that
** will contain all the contract definitions for each producer
** can package the contract definitions in a JAR
** for each contract producer contains a way (e.g. `pom.xml`) to install stubs locally via the Spring Cloud Contract Plugin (SCC Plugin)
** for more information please visit the <<howto.adoc#how-to-common-repo-with-contracts, how to section>> where we describe how to set up such a repository
** for an example of such a project you can {samples_code}/beer_contracts[check the samples]
* Consumer code that has Spring Cloud Contract Stub Runner setup
** for an example of such a project you can {samples_code}/consumer[check the samples]
* Producer code that has Spring Cloud Contract setup together with a plugin
** for an example of such a project you can {samples_code}/producer_with_external_contracts[check the samples]
* The `Stub Storage` will be Nexus / Artifactory
To use consumer-driven contracts with the contracts held in an external repository, you need to set up a git repository that:
At a high level the flow looks as follows:
* 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)
* 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 with contract definitions
* Producer takes over the pull request to the separate repository with contract definitions and installs the JAR with all contracts locally
* 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 with contract definitions is merged.
* After the CI tool builds the repository with contract definitions and the JAR with contract definitions gets uploaded to Nexus / Artifactory, the producer can merge their 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
For more information, see the <<howto.adoc#how-to-common-repo-with-contracts, How To section>>,
where we describe how to set up such a repository
For an example of such a project, see {samples_code}/beer_contracts[this sample].
You also need consumer code that has Spring Cloud Contract Stub Runner set up.
For an example of such a project, see {samples_code}/consumer[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 {samples_code}/producer_with_external_contracts[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.
[[flows-cdc-contracts-external-consumer]]
=== Consumer Flow
As a consumer
The consumer:
* write a test that would send a request to the producer
** the test will fail due to no server being present
* clone the repository with contract definitions
* set up the your requirements as contract under the folder with your consumer name as a subfolder of the producer. E.g. for a producer `producer` and consumer `consumer` the contracts would be stored under `src/main/resources/contracts/producer/consumer/`)
* once the contracts are defined, install the producer stubs to your local storage e.g.
. 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:
+
====
[src,bash]
----
$ cd src/main/resource/contracts/producer
$ ./mvnw clean install
```
* setup Spring Cloud Contract (SCC) Stub Runner in your tests
** to fetch the producer stubs from your local storage
** to work in the `stubs per consumer` mode (this enables Consumer Driven Contracts mode)
* SCC Stub Runner will
** fetch the producer stubs
** run an in memory HTTP server stub with the producer stubs
----
====
. 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:
[plantuml, flow-overview-consumer-cdc-external-consumer, png]
----
"Consumer"->"Repo\nwith\ncontracts": clone
@@ -245,20 +284,30 @@ $ ./mvnw clean install
[[flows-cdc-contracts-external-producer]]
=== Producer Flow
As a producer
The producer:
* take over the pull request to the repository with contract definitions. You can do it from the command line
. Takes over the pull request to the repository with contract definitions. You can do it
from the command line, as follows
+
```bash
====
[src,bash]
----
$ git checkout -b the_branch_with_pull_request master
git pull https://github.com/user_id/project_name.git the_branch_with_pull_request
```
* Install the contract definitions e.g.
```bash
$ ./mvnw clean install
```
* Setup your plugin to fetch the contract definitions from a JAR instead of from `src/test/resources/contracts`
----
====
. Installs the contract definitions, as follows
+
====
[src,bash]
----
$ ./mvnw clean install
----
====
. Sets up the plugin to fetch the contract definitions from a JAR instead of from
`src/test/resources/contracts`, as follows:
+
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
@@ -279,7 +328,7 @@ $ ./mvnw clean install
</configuration>
</plugin>
----
+
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
.Gradle
----
@@ -294,34 +343,41 @@ contracts {
// Additional configuration
}
----
* Run the build, generate tests and stubs
====
. Runs the build to generate tests and stubs, as follows:
+
====
[source,bash,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
./mvnw clean install
----
+
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
.Gradle
----
./gradlew clean build
----
* Write the missing implementation, make the tests pass
* Once done
** merge the pull request to the repository with contract definitions
** you can do it from the command line
====
. Writes the missing implementation, to make the tests pass.
. Merges the pull request to the repository with contract definitions, as follows:
+
```bash
====
[src,bash]
----
$ 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
```
* Now, the CI system will build the project with contract definitions and upload the JAR with contract definitions to Nexus / Artifactory
* The producer can switch to working remotely
** Setup the plugin so that the contract definitions are no longer taken from the local storage but from a remote location
----
====
. 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:
+
====
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
@@ -342,7 +398,7 @@ $ git push origin master
</configuration>
</plugin>
----
+
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
.Gradle
----
@@ -357,8 +413,14 @@ contracts {
// Additional configuration
}
----
** merge the producer code with the new implementation
* Now, the CI system will build the project, generate tests, stubs, stub JAR and upload the artifact with the application and the stubs to Nexus / Artifactory
====
. 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:
[plantuml, flow-overview-consumer-cdc-external-producer, png]
----
@@ -393,27 +455,30 @@ contracts {
----
[[flows-cdc-contracts-stubs-git]]
== Consumer Driven Contracts with contracts on the producer side, pushed to git
== Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git
You can check the <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side>> link to see the Consumer Driven Contracts with contracts on the producer side flow.
You can check <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side>> to see the consumer driven contracts with contracts on the producer side flow.
The Stub Storage implementation would be the git repository. We describe its setup in the <<flows-provider-git>> section.
The stub storage implementation is a git repository. We describe its setup in the
<<flows-provider-git>> section.
You can read more about setting up git repository as a git storage and setting consumer and producer side in the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
You can read more about setting up a git repository for the consumer and producer sides in
the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
[[flows-provider-non-spring]]
== Provider contract testing with stubs in Artifactory for a non Spring application
== Provider Contract Testing with Stubs in Artifactory for a non-Spring Application
[[flows-provider-non-spring-flow]]
=== The flow
=== The Flow
You can check the <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> link to see the provider contract testing with stubs in Nexus / Artifactory flow.
You can check <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> to see the flow for provider contract testing with stubs in Nexus or Artifactory.
[[flows-provider-non-spring-consumer]]
=== Consumer setup
=== Setting up the Consumer
For the consumer side, it's enough to use a JUnit rule. That way you don't even start a Spring context.
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);
====
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
.JUnit 4 Rule
----
@@ -433,16 +498,21 @@ For the consumer side, it's enough to use a JUnit rule. That way you don't even
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
----
====
[[flows-provider-non-spring-producer]]
=== Producer setup
=== Setting up the Producer
By default, the Spring Cloud Contract Plugin will use the Rest Assured's `MockMvc` setup for the generated tests. Since non Spring applications don't use `MockMvc`, it's enough to change the `testMode` to `EXPLICIT` to send a real request to an application bound at a specific port. '
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 will use a framework called https://javalin.io[Javalin] to start a non Spring HTTP server.
In this example, we use a framework called https://javalin.io[Javalin] to start a
non-Spring HTTP server.
Let us assume that we have the following application
Assume that we have the following application:
====
[source,java,indent=0]
----
package com.example.demo;
@@ -469,8 +539,10 @@ public class DemoApplication {
}
----
====
Setup the plugin to use the `EXPLICIT` mode (i.e. to send out requests to a real port).
Given that application, we can set up the plugin to use the `EXPLICIT` mode (that is, to
send out requests to a real port), as follows:
====
[source,xml,indent=0,role="primary"]
@@ -500,8 +572,9 @@ contracts {
----
====
The base class could look like this
The base class might resemble the following:
====
[source,java,indent=0]
----
import io.javalin.Javalin;
@@ -536,45 +609,57 @@ public class BaseClass {
}
}
----
====
With such a setup
With such a setup:
* we've setup the Spring Cloud Contract plugin that it uses the `EXPLICIT` mode to send real requests instead of mocked ones
* we've defined a base class that
** starts the HTTP server on a random port for each test
** sets Rest Assured to send requests to that port
** closes the HTTP server after each test
* We have setup the Spring Cloud Contract plugin to use the `EXPLICIT` mode to send real
requests instead of mocked ones.
* We have defined a base class that:
** Starts the HTTP server on a random port for each test.
** Sets Rest Assured to send requests to that port.
** Closes the HTTP server after each test.
[[flows-provider-non-jvm]]
== Provider contract testing with stubs in Artifactory in non JVM world
== Provider Contract Testing with Stubs in Artifactory in a non-JVM World
In this flow we assume that
In this flow, we assume that:
* the API Producer and API Consumer are non JVM applications.
* the contract definitions are written in YAML
* the Stub Storage is Artifactory / Nexus
* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker (SCC Stub Runner Docker) images will be used
* The API Producer and API Consumer are non-JVM applications.
* The contract definitions are written in YAML.
* The Stub Storage is Artifactory or Nexus.
* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker
(SCC Stub Runner Docker) images are used.
You can read more about how to use Spring Cloud Contract with Docker <<docker-project.adoc,in this page>>.
You can read more about how to use Spring Cloud Contract with Docker
<<docker-project.adoc,in this page>>.
Over https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[here] you can read a blog post about how to use Spring Cloud Contract in a polyglot world.
https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[Here], you can
read a blog post about how to use Spring Cloud Contract in a polyglot world.
https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here] you can find a sample of a NodeJS application using Spring Cloud Contract both as a producer and a consumer.
https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here], you can find
a sample of a NodeJS application that uses Spring Cloud Contract both as a producer and a
consumer.
[[flows-provider-non-jvm-producer]]
=== Producer Flow
At a high level the producer
At a high level, the producer:
* writes contract definitions e.g. in YAML
* sets up the build tool to
** start the application with mocked services on a given port X
** in case when mocking is not possible you can setup the infrastructure and define tests in a stateful way
** run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable
* The SCC Docker image
** generates the tests from the attached volume
** runs the tests against the running application
** upon test completion, stubs will get uploaded to a Stub Storage (e.g. Artifactory, Git)
. Writes contract definitions (for example, in YAML).
. Sets up the build tool to:
.. Start the application with mocked services on a given port.
+
If mocking is not possible, you can setup the infrastructure and define tests in a stateful way.
.. Run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable.
The SCC Docker image:
* Generates the tests from the attached volume.
* Runs the tests against the running application.
Upon test completion, stubs get uploaded to a stub storage site (such as Artifactory or Git).
The following UML diagram shows the producer flow:
[plantuml, flows-provider-non-jvm-producer, png]
----
@@ -599,16 +684,21 @@ At a high level the producer
[[flows-provider-non-jvm-consumer]]
=== Consumer Flow
At a high level the consumer
At a high level, the consumer:
* sets up the build tool to
** start the Spring Cloud Contract Stub Runner Docker image and start the stubs
*** the environment variables passed will configure
**** the stubs to fetch
**** location of the repositories
*** to use the local storage you can also attach it as a volume
*** the ports at which the stubs are running need to be exposed
** run your application tests against the running stubs
. Sets up the build tool to:
* Start the Spring Cloud Contract Stub Runner Docker image and start the stubs.
+
The environment variables configure:
* The stubs to fetch.
* The location of the repositories.
+
Note that:
* To use the local storage, you can also attach it as a volume.
* The ports at which the stubs are running need to be exposed.
. Run the application tests against the running stubs.
The following UML diagram shows the consumer flow:
[plantuml, flows-provider-non-jvm-consumer, png]
----
@@ -627,19 +717,19 @@ At a high level the consumer
----
[[flows-provider-rest-docs]]
== Provider contract testing with REST Docs and stubs in Nexus / Artifactory
== Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory
In this flow, we will not use a Spring Cloud Contract Plugin to generate tests and stubs. We will write https://spring.io/projects/spring-restdocs[Spring RESTDocs] and from them we will automatically generate stubs. Finally, we will setup our builds to package the stubs and upload them to the Stub Storage - in our case Nexus / Artifactory.
In this flow, we do not use a Spring Cloud Contract plugin to generate tests and stubs. We write https://spring.io/projects/spring-restdocs[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.
You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step by step instruction on how to do this flow.
See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step-by-step instruction on how to use this flow.
[[flows-provider-rest-docs-producer]]
=== Producer flow
=== Producer Flow
As a producer
As a producer, we:
* we write RESTDocs tests of our API
* we add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`)
. We write RESTDocs tests of our API.
. We add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`), as follows
+
====
[source,xml,indent=0,role="primary"]
@@ -680,7 +770,7 @@ dependencyManagement {
}
----
====
* we setup the build tool to package our stubs
. We set up the build tool to package our stubs, as follows:
+
====
[source,xml,indent=0,role="primary"]
@@ -747,7 +837,10 @@ stubsJar.dependsOn(test)
bootJar.dependsOn(stubsJar)
----
====
* now, when we run the tests, stubs will be automatically published and packaged
Now, when we run the tests, stubs are automatically published and packaged.
The following UML diagram shows the producer flow:
[plantuml, flows-provider-rest-docs-producer, png]
----
@@ -769,13 +862,14 @@ bootJar.dependsOn(stubsJar)
----
[[flows-provider-rest-docs-consumer]]
=== Consumer flow
=== Consumer Flow
Since the consumer flow isn't affected by the tool used to generate the stubs, you can check the <<getting-started.adoc#getting-started-first-application-consumer, Developing Your First Spring Cloud Contract based application>> link to see the consumer side of the provider contract testing with stubs in Nexus / Artifactory flow.
Since the consumer flow is not affected by the tool used to generate the stubs, you can check <<getting-started.adoc#getting-started-first-application-consumer, 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.
[[using-whats-next]]
== What to Read Next
You should now understand how you can use {project-full-name} and some best practices that you
should follow. You can now go on to learn about specific
_<<project-features#project-features, {project-full-name} features>>_ in depth, or you could
skip ahead and read about the _link:advanced.html[advanced features of {project-full-name}]_.
<<project-features#project-features, {project-full-name} features>>, or you could
skip ahead and read about the link:advanced.html[advanced features of {project-full-name}].