Merge branch 'master' into 2.0.x

This commit is contained in:
Marcin Grzejszczak
2017-09-12 11:51:08 +02:00
15 changed files with 1861 additions and 1338 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -6,14 +6,16 @@ image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg[
== Spring Cloud Contract
What you always need is confidence in pushing new features into a new application or service in a distributed system.
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, asserting that a contract is kept by producers
and consumers, for HTTP and message-based interactions.
You always need confidence when pushing new features into a new application or service in
a distributed system. To that end, this project provides support for Consumer-driven
Contracts and service schemas in Spring applications, covering a range of options for
writing tests, publishing them as assets, and asserting that a contract is kept by
producers and consumers -- for both HTTP and message-based interactions.
=== Spring Cloud Contract workshops
If you prefer to learn about the project by doing some tutorials you can check out the workshops under
If you prefer to learn about the project by doing some tutorials, you can check out the
workshops under
http://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link].
=== Spring Cloud Contract Verifier
@@ -28,7 +30,8 @@ include::spring-cloud-wiremock.adoc[]
== Documentation
You can read more about Spring Cloud Contract Verifier by reading the {documentation_url}[docs]
You can read more about Spring Cloud Contract Verifier by reading the
{documentation_url}[docs]
== Contributing

View File

@@ -1,13 +1,21 @@
== Links
Here you can find interesting links related to Spring Cloud Contract Verifier:
The following links may be helpful when working with Spring Cloud Contract Verifier:
- https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github Repository]
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud Contract Samples]
- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud Contract Documentation]
- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest Legacy Documentation]
- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring Cloud Contract Stub Runner Documentation]
- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring Cloud Contract Stub Runner Messaging Documentation]
- https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter]
- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin]
- https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by Marcin Grzejszczak]
* https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github
Repository]
* https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud
Contract Samples]
* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud
Contract Documentation]
* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest
Legacy Documentation]
* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring
Cloud Contract Stub Runner Documentation]
* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring
Cloud Contract Stub Runner Messaging Documentation]
* https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter]
* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring
Cloud Contract Maven Plugin]
* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by
Marcin Grzejszczak]

View File

@@ -4,33 +4,38 @@
== Migrations
In the following document we will write about necessary migration steps between versions.
This section covers migrating from one version of Spring Cloud Contract Verifier to the
next version. It covers the following versions upgrade paths:
[[cloud-verifier-1.0-1.1]]
=== 1.0.x -> 1.1.x
This section covers upgrading from version 1.0 to version 1.1.
==== New structure of generated stubs
In `1.1.x` we have introduced a changed structure of generated stubs. So if you've
been using the following `@AutoConfigureWireMock` notation to use the stubs from classpath
In `1.1.x` we have introduced a change to the structure of generated stubs. If you have
been using the `@AutoConfigureWireMock` notation to use the stubs from the classpath,
it no longer works. The following example shows how the `@AutoConfigureWireMock` notation
used to work:
[source,java]
----
@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)
----
It will no longer work with the new stubs. You have to either change the location of stubs
to : `classpath:.../META-INF/groupId/artifactId/version/mappings` as follows
You must either change the location of the stubs to:
`classpath:.../META-INF/groupId/artifactId/version/mappings` or use the new
classpath-based `@AutoConfigureStubRunner`, as shown in the following example:
[source,java]
----
@AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084)
----
Or migrate to the new classpath based `@AutoConfigureStubRunner`.
If however you don't want to do that and you want to remain with the old structure
just set your plugin tasks accordingly. Example for the structure presented in the
snippet above.
If you do not want to use `@AutoConfigureStubRunner` and you want to remain with the old
structure, set your plugin tasks accordingly. The following example would work for the
structure presented in the previous snippet.
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -111,36 +116,64 @@ task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
}
----
[[cloud-verifier-1.1-1.2]]
=== 1.1.x -> 1.2.x
This section covers upgrading from version 1.1 to version 1.2.
==== Custom `HttpServerStub`
By introducing a method `String registeredMappings()` in the public interface
`HttpServerStub`, if you wrote a custom `HttpServerStub` implementation, you'll
have to implement that method too. It should return a `String` representing
all mappings available in a single `HttpServerStub`. Related to
https://github.com/spring-cloud/spring-cloud-contract/issues/355[issue 355].
`HttpServerStub` includes a method that was not in version 1.1. The method is
`String registeredMappings()` If you have classes that implement `HttpServerStub`, you
now have to implement the `registeredMappings()` method. It should return a `String`
representing all mappings available in a single `HttpServerStub`.
See https://github.com/spring-cloud/spring-cloud-contract/issues/355[issue 355] for more
detail.
==== New packages for generated tests
The flow for setting the generated tests package name will look like this:
- pick `basePackageForTests`
- if `basePackageForTests` wasn't set pick the package from `baseClassForTests`
- if `baseClassForTests` wasn't set pick `packageWithBaseClasses`
- if nothing got set pick the default `org.springframework.cloud.contract.verifier.tests` value
* Set `basePackageForTests`
* If `basePackageForTests` was not set, pick the package from `baseClassForTests`
* If `baseClassForTests` was not set, pick `packageWithBaseClasses`
* If nothing got set, pick the default value:
`org.springframework.cloud.contract.verifier.tests`
Related to
https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260].
See https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260] for more
detail.
==== New methods in TemplateProcessor
==== New Methods in TemplateProcessor
In order to add support for `fromRequest.path` some methods had to be added to the
`TemplateProcessor` interface.
In order to add support for `fromRequest.path`, the following methods had to be added to the
`TemplateProcessor` interface:
Related to
https://github.com/spring-cloud/spring-cloud-contract/issues/388[issue 388].
* `path()`
* `path(int index)`
See https://github.com/spring-cloud/spring-cloud-contract/issues/388[issue 388] for more
detail.
==== RestAssured 3.0
Rest Assured, used in the generated test classes, got bumped to `3.0`. If
you manually set versions of Spring Cloud Contract and the release train
you might see the following exception:
[source,bash]
----
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist
----
This exception will occur due to the fact that the tests got generated with
an old version of plugin and at test execution time you have an incompatible
version of the release train (and vice versa).
Done via https://github.com/spring-cloud/spring-cloud-contract/issues/267[issue 267]
[[cloud-verifier-1.2-2.0]]
=== 1.2.x -> 2.0.x
==== No Camel support

View File

@@ -10,16 +10,17 @@
= Spring Cloud Contract
_Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak,
Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer_
Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer_, Jay Bryant
{spring-cloud-version}
== Spring Cloud Contract
What you always need is confidence in pushing new features into a new application or service in a distributed system.
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, asserting that a contract is kept by producers
and consumers, for HTTP and message-based interactions.
You need confidence when pushing new features to a new application or service in a
distributed system. This project provides support for Consumer Driven Contracts and
service schemas in Spring applications (for both HTTP and message-based interactions),
covering a range of options for writing tests, publishing them as assets, and asserting
that a contract is kept by producers and consumers.
include::spring-cloud-contract-verifier.adoc[]
@@ -27,4 +28,4 @@ include::spring-cloud-wiremock.adoc[]
include::migrations.adoc[]
include::links.adoc[]
include::links.adoc[]

View File

@@ -4,18 +4,17 @@
== Spring Cloud Contract WireMock
Modules giving you the possibility to use
http://wiremock.org[WireMock] in a Spring Boot application. Check out the
The Spring Cloud Contract WireMock modules let you use http://wiremock.org[WireMock] in a
Spring Boot application. Check out the
https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples]
for more details.
If you have a Spring Boot application that uses Tomcat as an embedded
server, for example (the default with `spring-boot-starter-web`), then
you can simply add `spring-cloud-contract-wiremock` 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 behaviour using a Java API or via static JSON declarations as
part of your test. Here's a simple example:
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-contract-wiremock` to your classpath and add `@AutoConfigureWireMock` in
order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you
can register stub behavior using a Java API or via static JSON declarations as part of
your test. The following code shows an example:
[source,java,indent=0]
----
@@ -23,16 +22,20 @@ include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2]
----
To start the stub server on a different port use `@AutoConfigureWireMock(port=9999)` (for example), and for a random port use the value 0. The stub server port will be bindable in the test application context as "wiremock.server.port". 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, just like for normal Spring integration tests.
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.
=== Registering Stubs Automatically
If you use `@AutoConfigureWireMock` then it will register 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 a resource
pattern (ant-style) or a directory, in which case `**/*.json` is
appended. Example:
If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file
system or classpath (by default, from `file:src/test/resources/mappings`). You can
customize the locations using the `stubs` attribute in the annotation, which can be an
Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is
appended. The following code shows an example:
----
@RunWith(SpringRunner.class)
@@ -51,35 +54,32 @@ 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 behaviour you have to also specify a
files root as described next.
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.
=== Using Files to Specify the Stub Bodies
WireMock can read response bodies from files on the classpath or file
system. In that case you will 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 `src/test/resources/\__files` by
default. To customize this location you can set the `files` attribute
in the `@AutoConfigureWireMock` annotation to the location of the
parent directory (i.e. the place `__files` is a
subdirectory). You can use Spring resource notation to refer to
`file:...` or `classpath:...` locations (but generic URLs are not
supported). A list of values can be given and WireMock will resolve
the first file that exists when it needs to find a response body.
WireMock can read response bodies from files on the classpath or the file system. In that
case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a
(literal) `body`. The files are resolved relative to a root directory (by default,
`src/test/resources/\__files`). To customize this location you can set the `files`
attribute in the `@AutoConfigureWireMock` annotation to the location of the parent
directory (in other words, `__files` is a subdirectory). You can use Spring resource
notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not
supported. A list of values can be given, in which case WireMock resolves the first file
that exists when it needs to find a response body.
NOTE: when you configure the `files` root, then it affects the
automatic loading of stubs as well (they come from the root location
in a subdirectory called "mappings"). The value of `files` has no
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
effect on the stubs loaded explicitly from the `stubs` attribute.
=== Alternative: Using JUnit Rules
For a more conventional WireMock experience, using JUnit `@Rules` to
start and stop the server, just use the `WireMockSpring` convenience
class to obtain an `Options` instance:
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 followin example:
[source,java,indent=0]
----
@@ -87,18 +87,20 @@ include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.j
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2]
----
The use `@ClassRule` means that the server will shut down after all the methods in this class.
The `@ClassRule` means that the server shuts down after all the methods in this class
have been run.
=== Relaxed SSL Validation for Rest Template
WireMock allows you to stub a "secure" server with an "https" URL protocol. If your application wants to
contact that stub server in an integration test, then it will find that the SSL certificates are not
valid (it's the usual problem with self-installed certificates). The best option is often to just
re-configure the client to use "http", but if that's not open to you then you can ask Spring to configure
an HTTP client that ignores SSL validation errors (just for tests).
WireMock lets you stub a "secure" server with an "https" URL protocol. If your
application wants to contact that stub server in an integration test, it will find that
the SSL certificates are not valid (the usual problem with self-installed certificates).
The best option is often to re-configure the client to use "http". If that's not an
option, you can ask Spring to configure an HTTP client that ignores SSL validation errors
(do so only for tests, of course).
To make this work with minimum fuss you need to be using the Spring Boot `RestTemplateBuilder` in your app,
e.g.
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:
[source,java,indent=0]
----
@@ -108,10 +110,11 @@ e.g.
}
----
This is because the builder is passed through callbacks to initalize it, so the SSL validation can be set up
in the client at that point. This will happen automatically in your test if you are using the
`@AutoConfigureWireMock` annotation (or the stub runner). If you are using the JUnit `@Rule` approach you need
to add the `@AutoConfigureHttpClient` annotation as well:
You need `RestTemplateBuilder` because the builder is passed through callbacks to
initialize it, so the SSL validation can be set up in the client at that point. This
happens automatically in your test if you are using the `@AutoConfigureWireMock`
annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the
`@AutoConfigureHttpClient` annotation as well, as shown in the following example:
[source,java,indent=0]
----
@@ -127,48 +130,45 @@ public class WiremockHttpsServerApplicationTests {
}
----
If you are using `spring-boot-starter-test` then you will have the Apache HTTP client on the classpath and it will
be selected by the `RestTemplateBuilder` and configured to ignore SSL errors. If you are using the default `java.net`
client you don't need the annotation (but it won't do any harm). There is no support currently for other clients, but
it may be added in future releases.
If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the
classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL
errors. If you use the default `java.net` client, you do not need the annotation (but it
won't do any harm). There is no support currently for other clients, but it may be added
in future releases.
=== WireMock and Spring MVC Mocks
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a
Spring `MockRestServiceServer`. Here's an example:
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` is prepended to all mock calls, and the `stubs()`
method takes a stub path resource pattern as an argument. So in this
example the stub defined at `/stubs/resource.json` is loaded into the
mock server, so if the `RestTemplate` is asked to visit
`http://example.org/` it will get the responses as declared
there. More than one stub pattern can be specified, and each one can
be a directory (for a recursive list of all ".json"), or a fixed
filename (like in the example above) or an ant-style pattern. The JSON
format is the normal WireMock format which you can read about in the
WireMock website.
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 `http://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
http://wiremock.org/docs/stubbing/[WireMock website].
Currently we support Tomcat, Jetty and Undertow as Spring Boot
embedded servers, and Wiremock itself has "native" support for a
particular version of Jetty (currently 9.2). To use the native Jetty
you need to add the native wiremock dependencies and exclude the
Spring Boot container if there is one.
Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as
Spring Boot embedded servers, and Wiremock itself has "native" support for a particular
version of Jetty (currently 9.2). To use the native Jetty, you need to add the native
Wiremock dependencies and exclude the Spring Boot container (if there is one).
=== Generating Stubs using RestDocs
https://projects.spring.io/spring-restdocs[Spring RestDocs] can be
used to generate documentation (e.g. in asciidoctor format) for an
HTTP API with Spring MockMvc or Rest Assured. At the same time as you
generate documentation for your API, you can also generate WireMock
stubs, by using Spring Cloud Contract WireMock. Just write your normal
RestDocs test cases and use `@AutoConfigureRestDocs` to have stubs
automatically in the restdocs output directory. For example:
=== Generating Stubs using 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
Rest Assured. At the same time that you generate documentation for your API, you can also
generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your
normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be
automatically generated in the REST Docs output directory. The following code shows an
example:
[source,java,indent=0]
----
@@ -190,20 +190,19 @@ public class ApplicationTests {
}
----
From this test will be generated a WireMock stub at
"target/snippets/stubs/resource.json". It matches all GET requests to
the "/resource" path.
This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches
all GET requests to the "/resource" path.
Without any additional configuration this will create a stub with a
request matcher for the HTTP method and all headers except "host" and
"content-length". To match the request more precisely, for example to
match the body of a POST or PUT, we need to explicitly create a
request matcher. This will do two things: 1) create a stub that only
matches the way you specify, 2) assert that the request in the test
case also matches the same conditions.
Without any additional configuration, this tests creates a stub with a request matcher
for the HTTP method and all headers except "host" and "content-length". To match the
request more precisely (for example, to match the body of a POST or PUT), we need to
explicitly create a request matcher. Doing so has two effects:
The main entry point for this is `WireMockRestDocs.verify()` which can
be used as a substitute for the `document()` convenience method. For
* Creating a stub that matches only in the way you specify.
* Asserting that the request in the test case also matches the same conditions.
The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used
as a substitute for the `document()` convenience method, as shown in the following
example:
[source,java,indent=0]
@@ -228,15 +227,14 @@ public class ApplicationTests {
}
----
So this contract is saying: any valid POST with an "id" field will get
back an the same response as in this test. You can chain together
calls to `.jsonPath()` to add additional matchers. The
https://github.com/jayway/JsonPath[JayWay documentation] can help you
to get up to speed with JSON Path if it is unfamiliar to you.
This contract specifies that any valid POST with an "id" field receives the response
defined in this test. You can chain together calls to `.jsonPath()` to add additional
matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay
documentation] can help you get up to speed.
Instead of the `jsonPath` and `contentType` convenience methods, you
can also use the WireMock APIs to verify the request matches the
created stub. Example:
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:
[source,java,indent=0]
----
@@ -253,10 +251,9 @@ created stub. Example:
}
----
The WireMock API is rich - you can match headers, query parameters,
and request body by regex as well as by json path - so this can useful
to create stubs with a wider range of parameters. The above example
will generate a stub something like this:
The WireMock API is rich. You can match headers, query parameters, and request body by
regex as well as by JSON path. These features can be used to create stubs with a wider
range of parameters. The above example generates a stub resembling the following example:
.post-resource.json
[source,json]
@@ -280,42 +277,43 @@ will generate a stub something like this:
}
----
NOTE: You can use either the `wiremock()` method or the `jsonPath()`
and `contentType()` methods to create request matchers, but not both.
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.
On the consumer side, you can make the `resource.json` generated above
available on the classpath (by https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing stubs as JARs] for example).
After that, you can create a stub using WireMock in a
number of different ways, including as described above using
`@AutoConfigureWireMock(stubs="classpath:resource.json")`.
On the consumer side, you can make the `resource.json` generated earlier in this section
available on the classpath (by
https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing
stubs as JARs], for example). After that, you can create a stub using WireMock in a
number of different ways, including by using
`@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this
document.
=== Generating Contracts using RestDocs
=== Generating Contracts by Using REST Docs
Another thing that can be generated with Spring RestDocs is the Spring Cloud
Contract DSL file and documentation. If you combine that with Spring Cloud
WireMock then you're getting both the contracts and stubs.
You can also generate Spring Cloud Contract DSL files and documentation with Spring REST
Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts
and the stubs.
Why would you want to use this feature? Some people in the community asked questions
about situation in which they would like to move to DSL based contract definition
but they already have a lot of Spring MVC tests. Using this feature allows you to generate
the contract files that you can later modify and move to proper folders so that the
plugin picks them up.
about a situation in which they would like to move to DSL-based contract definition,
but they already have a lot of Spring MVC tests. Using this feature lets you generate
the contract files that you can later modify and move to folders (defined in your
configuration) so that the plugin finds them.
TIP: You might wonder why this functionality is in the WireMock module.
Come to think of it, it does make sense since it makes little sense to generate
only contracts and not generate the stubs. That's why we suggest to do both.
TIP: 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.
Let's imagine the following test:
Consider the following test:
[source,java]
----
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet]
----
This will lead in the creation of the stub as presented in the previous
section, contract will get generated and a documentation file too.
The preceding test creates the stub presented in the previous section, generating both
the contract and a documentation file.
The contract will be called `index.groovy` and look more like this.
The contract is called `index.groovy` and might look like the following example:
[source,groovy]
----
@@ -349,5 +347,5 @@ Contract.make {
}
----
the generated document (example for Asciidoc) will contain a formatted contract
(the location of this file would be `index/dsl-contract.adoc`).
The generated document (formatted in Asciidoc in this case) contains a formatted
contract. The location of this file would be `index/dsl-contract.adoc`.

File diff suppressed because it is too large Load Diff

View File

@@ -1,89 +1,110 @@
== Spring Cloud Contract Verifier Introduction
TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski (http://codearte.io[codearte.io])
TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski
(http://codearte.io[codearte.io])
Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped
with __Contract Definition Language__ (DSL). Contract definitions are used to produce following resources:
Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of
JVM-based applications. It moves TDD to the level of software architecture.
* JSON stub definitions to be used by WireMock when doing integration testing on the client code (__client tests__).
Test code must still be written by hand, test data is produced by Spring Cloud Contract Verifier.
* Messaging routes if you're using one. We're integrating with Spring Integration, Spring Cloud Stream, Spring AMQP and Apache Camel. You can however set your own integrations if you want to
* Acceptance tests (in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (__server tests__).
Full test is generated by Spring Cloud Contract Verifier.
Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract
definitions are used to produce the following resources:
Spring Cloud Contract Verifier moves TDD to the level of software architecture.
* JSON stub definitions to be used by WireMock when doing integration testing on the
client code (_client tests_). Test code must still be written by hand, and test data is
produced by Spring Cloud Contract Verifier.
* Messaging routes, if you're using a messaging service. We integrate with Spring
Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your
own integrations.
* Acceptance tests (in JUnit or Spock) are used to verify if server-side implementation
of the API is compliant with the contract (__server tests__). A full test is generated by
Spring Cloud Contract Verifier.
=== Why?
=== Why a Contract Verifier?
Let us assume that we have a system comprising of multiple microservices:
Assume that we have a system consisting of multiple microservices:
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture]
==== Testing issues
If we wanted to test the application in top left corner if it can communicate with other services then we could do one of two things:
If we wanted to test the application in top left corner to determine whether it can
communicate with other services, we could do one of two things:
- deploy all microservices and perform end to end tests
- mock other microservices in unit / integration tests
- Deploy all microservices and perform end-to-end tests.
- Mock other microservices in unit/integration tests.
Both have their advantages but also a lot of disadvantages. Let's focus on the latter.
Both have their advantages but also a lot of disadvantages.
*Deploy all microservices and perform end to end tests*
Advantages:
- simulates production
- tests real communication between services
- Simulates production.
- Tests real communication between services.
Disadvantages:
- to test one microservice we would have to deploy 6 microservices, a couple of databases etc.
- the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime).
- long to run
- very late feedback
- extremely hard to debug
- To test one microservice, we have to deploy 6 microservices, a couple of databases,
etc.
- The environment where the tests run is locked for a single suite of tests (nobody else
would be able to run the tests in the meantime).
- They take a long time to run.
- The feedback comes very late in the process.
- They are extremely hard to debug.
*Mock other microservices in unit / integration tests*
*Mock other microservices in unit/integration tests*
Advantages:
- very fast feedback
- no infrastructure requirements
- They provide very fast feedback.
- They have no infrastructure requirements.
Disadvantages:
- the implementor of the service creates stubs thus they might have nothing to do with the reality
- you can go to production with passing tests and failing production
- The implementor of the service creates stubs that might have nothing to do with
reality.
- You can go to production with passing tests and failing production.
To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need
to set up the whole world of microservices. If you work on stubs then the only applications you need are those that your application is using directly.
To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was
created. The main idea is to give you very fast feedback, without the need to set up the
whole world of microservices. If you work on stubs, then the only applications you need
are those that your application directly uses.
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services]
Spring Cloud Contract Verifier gives you the certainty that the stubs that you're using were created by the service that you're calling. Also if you can use them it means that they were
tested against the producer's side. In other words - you can trust those stubs.
Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were
created by the service that you're calling. Also, if you can use them, it means that they
were tested against the producer's side. In short, you can trust those stubs.
=== Purposes
The main purposes of Spring Cloud Contract Verifier with Stub Runner are:
- to ensure that WireMock / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do,
- to promote ATDD method and Microservices architectural style,
- to provide a way to publish changes in contracts that are immediately visible on both sides,
- to generate boilerplate test code used on the server side.
- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly
what the actual server-side implementation does.
- To promote ATDD method and Microservices architectural style.
- To provide a way to publish changes in contracts that are immediately visible on both
sides.
- To generate boilerplate test code to be used on the server side.
IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business features in the contracts.
Let's assume that we have a business use case of fraud check. If a user can be a fraud for 100 different reasons,
we would assume that you would create 2 contracts. One for the positive and one for the negative fraud case.
Contract tests are used to test contracts between applications and not to simulate full behaviour.
IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business
features in the contracts. Assume that we have a business use case of fraud check. If a
user can be a fraud for 100 different reasons, we would assume that you would create 2
contracts, one for the positive case and one for the negative case. Contract tests are
used to test contracts between applications and not to simulate full behavior.
=== How
=== How It Works
==== Define the contract
This section explores how Spring Cloud Contract Verifier with Stub Runner works.
As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract.
==== Defining the contract
Lets assume that wed like to send the request containing the id of the client and the amount he wants to borrow from us. Wed like to send it to the /fraudcheck url via the PUT method.
As consumers of services, we need to define what exactly we want to achieve. We need to
formulate our expectations. That is why we write contracts.
Assume that you want to send a request containing the ID of a client company and the
amount it wants to borrow from us. You also want to send it to the /fraudcheck url via
the PUT method.
[source,groovy,indent=0]
----
@@ -92,11 +113,11 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resource
==== Client Side
Spring Cloud Contract will generate stubs, which you can use during client side testing.
You will have a WireMock instance / Messaging route up and running that simulates the service Y.
Spring Cloud Contract generates stubs, which you can use during client-side testing.
You get a running WireMock instance/Messaging route that simulates the service.
You would like to feed that instance with a proper stub definition.
At some point in time you need to send a request to the Fraud Detection service.
At some point in time, you need to send a request to the Fraud Detection service.
[source,groovy,indent=0]
----
@@ -110,18 +131,20 @@ Annotate your test class with `@AutoConfigureStubRunner`. In the annotation prov
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----
After that, during the tests Spring Cloud Contract will automatically find the stubs (simulating the real service) in Maven repository and expose them on configured (or random) port.
After that, during the tests, Spring Cloud Contract automatically finds the stubs
(simulating the real service) in the Maven repository and exposes them on a configured
(or random) port.
==== Server Side
Being a service Y since you are developing your stub, you need to be sure that it's actually resembling your
concrete implementation. You can't have a situation where your stub acts in one way and your application on
production behaves in a different way.
Since you are developing your stub, you need to be sure that it actually resembles your
concrete implementation. You cannot have a situation where your stub acts in one way and
your application behaves in a different way, especially in production.
That's why from the provided stub acceptance tests will be generated that will ensure
that your application behaves in the same way as you define in your stub.
To ensure that your application behaves the way you define in your stub, tests are
generated from the stub you provide.
The autogenerated test would look like this:
The autogenerated test looks like this:
[source,java,indent=0]
----
@@ -146,26 +169,33 @@ public void validate_shouldMarkClientAsFraud() throws Exception {
}
----
=== Step by step guide to CDC
=== Step-by-step Guide to Consumer Driven Contracts (CDC)
Let's take an example of Fraud Detection and Loan Issuance process. The business scenario is such that we want to issue loans to people but don't want them to steal the money from us. The current implementation of our system grants loans to everybody.
Consider an example of Fraud Detection and the Loan Issuance process. The business
scenario is such that we want to issue loans to people but do not want them to steal from
us. The current implementation of our system grants loans to everybody.
Let's assume that the `Loan Issuance` is a client to the
`Fraud Detection` server. In the current sprint we are required to develop a new feature - if a client wants to borrow too much money then we mark him as fraud.
Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current
sprint, we must develop a new feature: if a client wants to borrow too much money, then
we mark the client as a fraud.
Technical remark - Fraud Detection will have artifact id `http-server`, Loan Issuance `http-client` and both have group id `com.example`.
Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan
Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`.
Social remark - both client and server development teams need to communicate directly and discuss changes while
going through the process. CDC is all about communication.
Social remark - both client and server development teams need to communicate directly and
discuss changes while going through the process. CDC is all about communication.
The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the client side code here].
The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server
side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the
client code here].
TIP: In this case the ownership of the contracts lays on the producer side. It means that physically
all the contract are present in the producer's repository
TIP: In this case, the producer owns the contracts. Physically, all the contract are
in the producer's repository.
==== Technical note
If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the following section to your
If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the
following section to your build:
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -181,98 +211,125 @@ include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags
==== Consumer side (Loan Issuance)
As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):
As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:
*start doing TDD by writing a test to your feature*
. Start doing TDD by writing a test for your feature.
. Write the missing implementation.
. Clone the Fraud Detection service repository locally.
. Define the contract locally in the repo of Fraud Detection service.
. Add the Spring Cloud Contract Verifier plugin.
. Run the integration tests.
. File a pull request.
. Create an initial implementation.
. Take over the pull request.
. Write the missing implementation.
. Deploy your app.
. Work online.
*Start doing TDD by writing a test for your feature.*
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0]
----
We've just written a test of our new feature. If a loan application for a big amount is received we should reject that loan application with some description.
Assume that you have written a test of your new feature. If a loan application for a big
amount is received, the system should reject that loan application with some description.
*write the missing implementation*
*Write the missing implementation.*
At some point in time you need to send a request to the Fraud Detection service. Let's assume that we'd like to send the request containing the id of the client and the amount he wants to borrow from us. We'd like to send it to the `/fraudcheck` url via the `PUT` method.
At some point in time, you need to send a request to the Fraud Detection service. Assume
that you need to send the request containing the ID of the client and the amount the
client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method.
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]
----
For simplicity we've hardcoded the port of the Fraud Detection service at `8080` and our application is running on `8090`.
For simplicity, the port of the Fraud Detection service is set to `8080`, and the
application runs on `8090`.
If we'd start the written test it would obviously break since we have no service running on port `8080`.
If you start the test at this point, it breaks, because no service currently runs on port
`8080`.
*clone the Fraud Detection service repository locally*
*Clone the Fraud Detection service repository locally.*
We'll start playing around with the server side contract. That's why we need to first clone it.
You can start by playing around with the server side contract. To do so, you must first
clone it.
[source,bash,indent=0]
----
git clone https://your-git-server.com/server-side.git local-http-server-repo
----
*define the contract locally in the repo of Fraud Detection service*
*Define the contract locally in the repo of Fraud Detection service.*
As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract.
As a consumer, you need to define what exactly you want to achieve. You need to formulate
your expectations. To do so, write the following contract:
IMPORTANT: We're placing the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder
is important cause we'll reference that folder in the producer's test base class name.
IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder
is important because the producer's test base class name references that folder.
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
----
The Contract is written using a statically typed Groovy DSL. You might be wondering what are those
`value(client(...), server(...))` parts. By using this notation Spring Cloud Contract allows you to
define parts of a JSON / URL / etc. which are dynamic. In case of an identifier or a timestamp you
don't want to hardcode a value. You want to allow some different ranges of values. That's why for
the consumer side you can set regular expressions matching those values. You can provide the body
either by means of a map notation or String with interpolations.
The Contract is written using a statically typed Groovy DSL. You might wonder what about
those `value(client(...), server(...))` parts. By using this notation, Spring Cloud
Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case
of an identifier or a timestamp, you need not hardcode a value. You want to allow some
different ranges of values. To enable ranges of values, you can set regular expressions
matching those values for the consumer side. You can provide the body by means of either
a map notation or String with interpolations.
https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_contract_dsl[Consult the docs
for more information.] We highly recommend using the map notation!
TIP: It's really important that you understand the map notation to set up contracts. Please read the
http://groovy-lang.org/json.html[Groovy docs regarding JSON]
TIP: You must understand the map notation in order to set up contracts. Please read the
http://groovy-lang.org/json.html[Groovy docs regarding JSON].
The aforementioned contract is an agreement between two sides that:
The previously shown contract is an agreement between two sides that:
- if an HTTP request is sent with
** a method `PUT` on an endpoint `/fraudcheck`
** JSON body with `client.id` matching the regular expression `[0-9]{10}` and `loanAmount` equal to `99999`
** and with a header `Content-Type` equal to `application/vnd.fraud.v1+json`
- then an HTTP response would be sent to the consumer that
** has status `200`
** contains JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and the `rejectionReason` field having value `Amount too high`
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`
- if an HTTP request is sent with all of
** a `PUT` method on the `/fraudcheck` endpoint,
** a JSON body with a `client.id` that matches the regular expression `[0-9]{10}` and
`loanAmount` equal to `99999`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`,
- then an HTTP response is sent to the consumer that
** has status `200`,
** contains a JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and
the `rejectionReason` field having value `Amount too high`,
** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`.
Once we're ready to check the API in practice in the integration tests we need to just install the stubs locally
Once you are ready to check the API in practice in the integration tests, you need to
install the stubs locally.
*add the Spring Cloud Contract Verifier plugin*
*Add the Spring Cloud Contract Verifier plugin.*
We can add either Maven or Gradle plugin - in this example we'll show how to add Maven. First we need to add the `Spring Cloud Contract` BOM.
We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven.
First, add the `Spring Cloud Contract` BOM.
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0]
----
Next, the `Spring Cloud Contract Verifier` Maven plugin
Next, add the `Spring Cloud Contract Verifier` Maven plugin
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----
Since the plugin was added we get the `Spring Cloud Contract Verifier` features which from the provided contracts:
Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which,
from the provided contracts:
- generate and run tests
- produce and install stubs
We don't want to generate tests since we, as consumers, want only to play with the stubs. That's why we need to skip the tests generation and execution. When we execute:
You do not want to generate tests since you, as the consumer, want only to play with the
stubs. You need to skip the test generation and execution. When you execute:
[source,bash,indent=0]
----
@@ -280,7 +337,7 @@ cd local-http-server-repo
./mvnw clean install -DskipTests
----
In the logs we'll see something like this:
In the logs, you see something like this:
[source,bash,indent=0]
----
@@ -298,41 +355,47 @@ In the logs we'll see something like this:
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----
This line is extremely important
The following line is extremely important:
[source,bash,indent=0]
----
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
----
It's confirming that the stubs of the `http-server` have been installed in the local repository.
It confirms that the stubs of the `http-server` have been installed in the local
repository.
*run the integration tests*
*Run the integration tests.*
In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic stub downloading you have to do the following in our consumer side project (`Loan Application service`).
In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic
stub downloading, you must do the following in your consumer side project (`Loan
Application service`):
Add the `Spring Cloud Contract` BOM
Add the `Spring Cloud Contract` BOM:
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0]
----
Add the dependency to `Spring Cloud Contract Stub Runner`
Add the dependency to `Spring Cloud Contract Stub Runner`:
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
----
Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. Also provide the offline work switch since you're playing with the collaborators offline (optional step).
Annotate your test class with `@AutoConfigureStubRunner`. In the annotation, provide the
`group-id` and `artifact-id` for the Stub Runner to download the stubs of your
collaborators. (Optional step) Because you're playing with the collaborators offline, you
can also provide the offline work switch.
[source,groovy,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
----
Now if you run your tests you'll see sth like this:
Now, when you run your tests, you see something like this:
[source,bash,indent=0]
----
@@ -345,21 +408,26 @@ Now if you run your tests you'll see sth like this:
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
----
Which means that Stub Runner has found your stubs and started a server for app with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of the stubs and with `stubs` classifier on port `8080`.
This output means that Stub Runner has found your stubs and started a server for your app
with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of
the stubs and with `stubs` classifier on port `8080`.
*file a PR*
*File a pull request.*
What we did until now is an iterative process. We can play around with the contract, install it locally and work on the consumer side until we're happy with the contract.
What you have done until now is an iterative process. You can play around with the
contract, install it locally, and work on the consumer side until the contract works as
you wish.
Once we're satisfied with the results and the test passes publish a PR to the server side. Currently the consumer side work is done.
Once you are satisfied with the results and the test passes, publish a pull request to
the server side. Currently, the consumer side work is done.
==== Producer side (Fraud Detection server)
As a developer of the Fraud Detection server (a server to the Loan Issuance service):
*initial implementation*
*Create an initial implementation.*
As a reminder here you can see the initial implementation
As a reminder, you can see the initial implementation here:
[source,java,indent=0]
----
@@ -368,7 +436,7 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com
}
----
*take over the PR*
*Take over the pull request.*
[source,bash,indent=0]
----
@@ -376,35 +444,37 @@ git checkout -b contract-change-pr master
git pull https://your-git-server.com/server-side-fork.git contract-change-pr
----
You have to add the dependencies needed by the autogenerated tests
You must add the dependencies needed by the autogenerated tests:
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
----
In the configuration of the Maven plugin we passed the `packageWithBaseClasses` property
In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property
[source,xml,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----
IMPORTANT: We've decided to use the "convention based" naming by setting the `packageWithBaseClasses` property.
That means that 2 last packages will be combined into a name of the base test class. In our case the contracts
were placed under `src/test/resources/contracts/fraud`. Since we don't have 2 packages starting from the `contracts`
folder we're picking only one which is `fraud`. We're adding the `Base` suffix and we're capitalizing `fraud`.
That gives us the `FraudBase` test class name.
IMPORTANT: This example uses "convention based" naming by setting the
`packageWithBaseClasses` property. Doing so means that the two last packages combine to
make the name of the base test class. In our case, the contracts were placed under
`src/test/resources/contracts/fraud`. Since you do not have two packages starting from
the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and
capitalize `fraud`. That gives you the `FraudBase` test class name.
That's because all the generated tests will extend that class. Over there you can set up your Spring Context or
whatever is necessary. In our case we're using http://rest-assured.io/[Rest Assured MVC] to start the server side `FraudDetectionController`.
All the generated tests extend that class. Over there, you can set up your Spring Context
or whatever is necessary. In this case, use http://rest-assured.io/[Rest Assured MVC] to
start the server side `FraudDetectionController`.
[source,java,indent=0]
----
include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[]
----
Now, if you run the `./mvnw clean install` you would get sth like this:
Now, if you run the `./mvnw clean install`, you get something like this:
[source,bash,indent=0]
----
@@ -414,7 +484,9 @@ Tests in error:
ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
----
That's because you have a new contract from which a test was generated and it failed since you haven't implemented the feature. The autogenerated test would look like this:
This error occurs because you have a new contract from which a test was generated and it
failed since you have not implemented the feature. The auto-generated test would look
like this:
[source,java,indent=0]
----
@@ -439,13 +511,19 @@ public void validate_shouldMarkClientAsFraud() throws Exception {
}
----
As you can see all the `producer()` parts of the Contract that were present in the `value(consumer(...), producer(...))` blocks got injected into the test.
As you can see, all the `producer()` parts of the Contract that were present in the
`value(consumer(...), producer(...))` blocks got injected into the test.
What's important here to note is that on the producer side we also are doing TDD. We have expectations in form of a test. This test is shooting a request to our own application to an URL, headers and body defined in the contract. It also is expecting very precisely defined values in the response. In other words you have is your `red` part of `red`, `green` and `refactor`. Time to convert the `red` into the `green`.
Note that, on the producer side, you are also doing TDD. The expectations are expressed
in the form of a test. This test sends a request to our own application with the URL,
headers, and body defined in the contract. It also is expecting precisely defined values
in the response. In other words, you have the `red` part of `red`, `green`, and
`refactor`. It is time to convert the `red` into the `green`.
*write the missing implementation*
*Write the missing implementation.*
Now since we now what is the expected input and expected output let's write the missing implementation.
Because you know the expected input and expected output, you can write the missing
implementation:
[source,java,indent=0]
----
@@ -455,11 +533,13 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com
}
----
If we execute `./mvnw clean install` again the tests will pass. Since the `Spring Cloud Contract Verifier` plugin adds the tests to the `generated-test-sources` you can actually run those tests from your IDE.
When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud
Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can
actually run those tests from your IDE.
*deploy your app*
*Deploy your app.*
Once you've finished your work it's time to deploy your change. First merge the branch
Once you finish your work, you can deploy your change. First, merge the branch:
[source,bash,indent=0]
----
@@ -468,13 +548,14 @@ git merge --no-ff contract-change-pr
git push origin master
----
Then we assume that your CI would run sth like `./mvnw clean deploy` which would publish both the application and the stub artifcats.
Your CI might run something like `./mvnw clean deploy`, which would publish both the
application and the stub artifacts.
==== Consumer side (Loan Issuance) final step
==== Consumer Side (Loan Issuance) Final Step
As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):
*merge branch to master*
*Merge branch to master.*
[source,bash,indent=0]
----
@@ -482,30 +563,33 @@ git checkout master
git merge --no-ff contract-change-pr
----
*work online*
*Work online.*
Now you can disable the offline work for Spring Cloud Contract Stub Runner and provide where the repository with your stubs is placed. At this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory.
You can switch off the value of the `workOffline` parameter in your annotation. Below you can see an
example of achieving the same by changing the properties.
Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate
where the repository with your stubs is located. At this moment the stubs of the server
side are automatically downloaded from Nexus/Artifactory. You can switch off the value of
the `workOffline` parameter in your annotation. The following code shows an example of
achieving the same thing by changing the properties.
[source,yaml,indent=0]
----
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]
----
And that's it!
That's it!
=== Dependencies
The best way to add the dependencies is to just use the proper `starter` dependency.
The best way to add dependencies is to use the proper `starter` dependency.
For `stub-runner` use `spring-cloud-starter-stub-runner` and when you're using a plugin just add
For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add
`spring-cloud-starter-contract-verifier`.
=== Additional links
=== Additional Links
Below you can find some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some can be outdated since the Spring Cloud Contract Verifier project
is under constant development.
Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note
that some may be outdated, because the Spring Cloud Contract Verifier project is under
constant development.
==== Spring Cloud Contract video
@@ -522,4 +606,5 @@ video::sAAklvxmPmk[youtube,start=538,width=640,height=480]
=== Samples
Here you can find some https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples].
You can find some samples at
https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples].

View File

@@ -1,25 +1,27 @@
== Spring Cloud Contract Verifier Messaging
Spring Cloud Contract Verifier allows you to verify your application that uses messaging as means of communication.
All of our integrations are working with Spring but you can also create one yourself and use it.
Spring Cloud Contract Verifier lets you verify applications that uses messaging as a
means of communication. All of the integrations shown in this document work with Spring,
but you can also create one of your own and use that.
=== Integrations
You can use one of the four integration configurations:
You can use one of the following four integration configurations:
- Apache Camel
- Spring Integration
- Spring Cloud Stream
- Spring AMQP
* Apache Camel
* Spring Integration
* Spring Cloud Stream
* Spring AMQP
Since we're using Spring Boot then if you have added one of the aforementioned libraries
to the classpath then automatically all the messaging configuration will be set up.
Since we use Spring Boot, if you have added one of these libraries to the classpath, all
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 Verifier will not work.
generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not
work.
IMPORTANT: If you want to use Spring Cloud Stream remember to add a
`org.springframework.cloud:spring-cloud-stream-test-support` dependency.
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 here:
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -37,15 +39,16 @@ IMPORTANT: If you want to use Spring Cloud Stream remember to add a
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
----
=== Manual Integration Testing
The main interface used by the tests is the `org.springframework.cloud.contract.verifier.messaging.MessageVerifier`.
It defines how to send and receive messages. You can create your own implementation to achieve the
same goal.
The main interface used by the tests is
`org.springframework.cloud.contract.verifier.messaging.MessageVerifier`.
It defines how to send and receive messages. You can create your own implementation to
achieve the same goal.
In the a test you can inject a `ContractVerifierMessageExchange` to send and receive messages that follow the contract.
Then add `@AutoConfigureMessageVerifier` to your test, e.g.
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:
[source,java,indent=0]
----
@@ -60,38 +63,38 @@ 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.
NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the
messaging configuration, so you only need the one annotation.
=== Publisher side test generation
=== Publisher-Side Test Generation
Having the `input` or `outputMessage` sections in your DSL will result in creation of tests on the publisher's side. By default
JUnit tests will be created, however there is also a possibility to create Spock tests.
Having the `input` or `outputMessage` sections in your DSL results in creation of tests
on the publisher's side. By default, JUnit tests are created. However, there is also a
possibility to create Spock tests.
There are 3 main scenarios that we should take into consideration:
- Scenario 1: there is no input message that produces an output one. The output message is triggered by a component
inside the application (e.g. scheduler)
- Scenario 2: the input message triggers an output message
- Scenario 3: the input message is consumed and there is no output message
* Scenario 1: There is no input message that produces an output message. The output
message is triggered by a component inside the application (for example, scheduler).
* Scenario 2: The input message triggers an output message.
* Scenario 3: The input message is consumed and there is no output message.
IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different meanings for different
messaging implementations. For *Stream* and *Integration* it's first resolved as a `destination` of a channel, and then if
there is no such `destination` it's resolved as a channel name. For *Camel* that's a certain component (e.x. `jms`).
IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different
meanings for different messaging implementations. For *Stream* and *Integration* it is
first resolved as a `destination` of a channel. Then, if there is no such `destination`
it is resolved as a channel name. For *Camel*, that's a certain component (for example,
`jms`).
Example for Camel:
==== Scenario 1: No Input Message
==== Scenario 1 (no input message)
For the given contract:
Here is an example for Camel. For the given contract:
[source,groovy]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_dsl]
----
The following JUnit test will be created:
The following JUnit test is created:
[source,groovy]
----
@@ -105,16 +108,16 @@ And the following Spock test would be created:
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_test]
----
==== Scenario 2 (output triggered by input)
==== Scenario 2: Output Triggered by Input
For the given contract:
Here is an example for Camel. For the given contract:
[source,groovy]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_dsl]
----
The following JUnit test will be created:
The following JUnit test is created:
[source,groovy]
----
@@ -128,16 +131,16 @@ And the following Spock test would be created:
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_spock]
----
==== Scenario 3 (no output message)
==== Scenario 3: No Output Message
For the given contract:
Here is an example for Camel. For the given contract:
[source,groovy]
----
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl]
----
The following JUnit test will be created:
The following JUnit test is created:
[source,groovy]
----
@@ -151,12 +154,14 @@ And the following Spock test would be created:
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_spock]
----
=== Consumer Stub Side generation
=== Consumer Stub Generation
Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it's parsed on the consumer side
and proper stubbed routes are created.
Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with
a stub. Then it is parsed on the consumer side and proper stubbed routes are created.
For more information please consult the Stub Runner Messaging sections.
For more information, see
https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[the
Stub Runner Messaging sections].
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven

View File

@@ -1,15 +1,43 @@
== Spring Cloud Contract Verifier Setup
You can set up Spring Cloud Contract Verifier in either of two ways
* <<gradle-project,As a Gradle project>>
* <<maven-project,As a Maven project>>
[[gradle-project]]
=== Gradle Project
To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the
following sections:
* <<gradle-prerequisites>>
* <<gradle-add-gradle-plugin>>
* <<gradle-and-rest-assured>>
* <<gradle-snapshot-versions>>
* <<gradle-add-stubs>>
* <<gradle-default-setup>>
* <<gradle-configure-plugin>>
* <<gradle-configuration-options>>
* <<gradle-single-base-class>>
* <<gradle-different-base-classes>>
* <<gradle-invoking-generated-tests>>
* <<gradle-consumer>>
[[gradle-prerequisites]]
==== Prerequisites
In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin.
In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a
Gradle or a Maven plugin.
WARNING: If you want to use Spock in your projects you have to add separately
the `spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock docs for more information]
WARNING: If you want to use Spock in your projects, you must add separately the
`spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock
docs for more information]
==== Add gradle plugin with dependencies
[[gradle-add-gradle-plugin]]
==== Add Gradle Plugin with Dependencies
To add a Gradle plugin with dependencies, use code similar to this:
[source,groovy,indent=0]
----
@@ -41,10 +69,11 @@ dependencies {
}
----
[[gradle-and-rest-assured]]
==== Gradle and Rest Assured 2.0
By default Rest Assured 3.x is added to the classpath. However in order to give the users the
opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath.
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:
[source,groovy,indent=0]
----
@@ -68,26 +97,31 @@ depenendencies {
}
----
That way the plugin will automatically see that Rest Assured 2.x is present on the classpath
and will modify the imports accordingly.
That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
and modifies the imports accordingly.
==== Snapshot versions for Gradle
[[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:
Add the additional snapshot repository to your build.gradle to use snapshot versions,
which are automatically uploaded after every successful build, as shown here:
[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 `src/test/resources/contracts` directory.
By default, Spring Cloud Contract Verifier is looking for stubs in the
`src/test/resources/contracts` directory.
Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test.
We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
So with following structure
The directory containing stub definitions is treated as a class name, and each stub
definition is treated as a single test. Spring Cloud Contract Verifier assumes that it
contains at least one level of directories that are to be used as the test class name.
If more than one level of nested directories is present, all except the last one is used
as the package name. For example, with following structure:
[source,groovy,indent=0]
----
@@ -95,18 +129,24 @@ src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy
----
Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService`
with two methods:
- `shouldCreateUser()`
- `shouldReturnUser()`
==== Run plugin
[[gradle-run-plugin]]
==== Run the Plugin
Plugin registers itself to be invoked before `check` task. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateContractTests` task.
The plugin registers itself to be invoked before a `check` task. If you want it to be
part of your build process, you need to do nothing more. If you just want to generate
tests, invoke the `generateContractTests` task.
==== Default setup
[[gradle-default-setup]]
==== Default Setup
Default Gradle Plugin setup creates the following Gradle part of the build (it's a pseudocode)
The default Gradle Plugin setup creates the following Gradle part of the build (in
pseudocode):
[source,groovy,indent=0]
----
@@ -156,9 +196,11 @@ publishing {
}
----
==== Configure plugin
[[gradle-configure-plugin]]
==== Configure Plugin
To change default configuration just add `contracts` snippet to your Gradle config
To change the default configuration, add a `contracts` snippet to your Gradle config, as
shown here:
[source,groovy,indent=0]
----
@@ -169,100 +211,141 @@ contracts {
}
----
==== Configuration options
[[gradle-configuration-options]]
==== Configuration Options
- **testMode** - defines mode for acceptance tests. By default MockMvc which is based on Spring's MockMvc. It can also be changed to **JaxRsClient** or to **Explicit** for real HTTP calls.
- **imports** - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []
- **staticImports** - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []
- **basePackageForTests** - specifies base package for all generated tests. If not set the value will be picked from `baseClassForTests`'s package and from
`packageWithBaseClasses`. If neither of these are set then the value will be set to `org.springframework.cloud.contract.verifier.tests`
- **baseClassForTests** - base class for all generated tests. By default `spock.lang.Specification` if using Spock tests.
- **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over **baseClassForTests**.
- **baseClassMappings** - explicitly map contract package to a FQN of a base class. Takes precedence over **packageWithBaseClasses** and **baseClassForTests**.
- **ruleClassForTests** - specifies Rule which should be added to generated test classes.
- **ignoredFiles** - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []
- **contractsDslDir** - directory containing contracts written using the GroovyDSL. By default `$rootDir/src/test/resources/contracts`
- **generatedTestSourcesDir** - test source directory where tests generated from Groovy DSL should be placed. By default `$buildDir/generated-test-sources/contractVerifier`
- **stubsOutputDir** - dir where the generated WireMock stubs from Groovy DSL should be placed
- **targetFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
* *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 *JaxRsClient* or to
*Explicit* for real HTTP calls.
* *imports*: Creates an array with imports that should be included in generated tests
(for example ['org.myorg.Matchers']). By default, it creates an empty array.
* *staticImports*: Creates an array with static imports that should be included in
generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty
array.
* *basePackageForTests*: Specifies the base package for all generated tests. If not set,
the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`.
If neither of these values are set, then the value is set to
`org.springframework.cloud.contract.verifier.tests`.
* *baseClassForTests*: Creates a base class for all generated tests. By default, if you
use Spock classes, the class is `spock.lang.Specification`.
* *packageWithBaseClasses*: Defines a package where all the base classes reside. This
setting takes precedence over *baseClassForTests*.
* *baseClassMappings*: Explicitly maps a contract package to a FQN of a base class. This
setting takes precedence over *packageWithBaseClasses* and *baseClassForTests*.
* *ruleClassForTests*: Specifies a rule that should be added to the generated test
classes.
* *ignoredFiles*: Uses an `Antmatcher` to allow defining stub files for which processing
should be skipped. By default, it is an empty array.
* *contractsDslDir*: Specifies the directory containing contracts written using the
GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`.
* *generatedTestSourcesDir*: Specifies the test source directory where tests generated
from the Groovy DSL should be placed. By default its value is
`$buildDir/generated-test-sources/contractVerifier`.
* *stubsOutputDir*: Specifies the directory where the generated WireMock stubs from
the Groovy DSL should be placed.
* *targetFramework*: Specifies the target test framework to be used. Currently, Spock and
JUnit are supported with JUnit being the default framework.
The following properties are used when you want to provide where the JAR with contract lays
The following properties are used when you want to specify the location of the JAR
containing the contracts:
* *contractDependency*: Specifies the Dependency that provides
`groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency`
closure to set it up.
* *contractsPath*: Specifies the path to the jar. If contract dependencies are
downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash
separated. Otherwise, it scans contracts under the provided directory.
* *contractsWorkOffline*: Specifies whether to download the dependencies each time, so
that you can work online. In other words, it specifies whether to reuses the local Maven
repo.
- **contractDependency** - the Dependency that provides `groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` closure to set it up
- **contractsPath** - if contract deps are downloaded will default to `groupid/artifactid` where `groupid` will be slash separated. Otherwise will scan contracts under provided directory
- **contractsWorkOffline** - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo)
[[gradle-single-base-class]]
==== Single Base Class for All Tests
==== Single base class for all tests
When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified.
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.
[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]
----
In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class
should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server.
If you use `Explicit` mode, you can use a base class to initialize the whole tested app
as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this
base class should also contain a `protected WebTarget webTarget` field. Right now, the
only option to test the JAX-RS API is to start a web server.
==== Different base classes for contracts
[[gradle-different-base-classes]]
==== 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:
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 the `packageWithBaseClasses`
* Provide explicit mapping via `baseClassMappings`
*Convention*
*By Convention*
The convention is such that if you have a contract under e.g. `src/test/resources/contract/foo/bar/baz/` and provide the value of the `packageWithBaseClasses` property
to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. In other words we take last two parts of package
if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage in the `contracts` closure:
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:
[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]
----
*Mapping*
*By Mapping*
You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract.
Let's take a look at the following example:
You can manually map a regular expression of the contract's package to fully qualified
name of the base class for the matched contract. You have to provide a list called
`baseClassMappings` that consists `baseClassMapping` objects that takes a
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
[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 under
- `src/test/resources/contract/com/`
- `src/test/resources/contract/foo/`
By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide
the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
==== Invoking generated tests
By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed.
(You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests
generated from `src/test/resources/contract/com/` contracts extend the
`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`.
To ensure that provider side is complaint with defined contracts, you need to invoke:
[[gradle-invoking-generated-tests]]
==== Invoking Generated Tests
To ensure that the provider side is compliant with defined contracts, you need to invoke:
[source,bash,indent=0]
----
./gradlew generateContractTests test
----
==== Spring Cloud Contract Verifier on consumer side
[[gradle-consumer]]
==== Spring Cloud Contract Verifier on the Consumer Side
In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. If you don't want to use Stub Runner then you need to copy contracts stored in
`src/test/resources/contracts` and generate WireMock json stubs using:
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:
[source,bash,indent=0]
----
./gradlew generateClientStubs
----
Note that `stubsOutputDir` option has to be set for stub generation to work.
NOTE: The `stubsOutputDir` option has to be set for stub generation to work.
When present, json stubs can be used in consumer automated tests.
When present, JSON stubs can be used in automated tests of consuming a service.
[source,groovy,indent=0]
----
@@ -289,32 +372,54 @@ class LoanApplicationServiceSpec extends Specification {
}
----
Underneath LoanApplication makes a call to FraudDetection service. This request is handled by WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a
WireMock server configured with stubs generated by Spring Cloud Contract Verifier.
=== Using in your Maven project
[[maven-project]]
=== Maven Project
To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the
following sections:
* <<maven-add-plugin>>
* <<maven-rest-assured>>
* <<maven-snapshot-versions>>
* <<maven-add-stubs>>
* <<maven-run-plugin>>
* <<maven-configure-plugin>>
* <<maven-configuration-options>>
* <<maven-single-base>>
* <<maven-different-base>>
* <<maven-invoking-generated-tests>>
* <<maven-sts>>
* <<maven-consumer>>
[[maven-add-plugin]]
==== Add maven plugin
Add the Spring Cloud Contract BOM
Add the Spring Cloud Contract BOM in a fashion similar to this:
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_bom,indent=0]
----
Next, the `Spring Cloud Contract Verifier` Maven plugin
Next, add the `Spring Cloud Contract Verifier` Maven plugin:
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
----
You can read more in the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin Docs]
You can read more in the
https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring
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 in order to give the users the
opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath.
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:
[source,groovy,indent=0]
----
@@ -365,24 +470,29 @@ opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpa
</dependencies>
----
That way the plugin will automatically see that Rest Assured 3.x is present on the classpath
and will modify the imports accordingly.
That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath
and modifies the imports accordingly.
[[maven-snapshot-versions]]
==== Snapshot versions for Maven
For Snapshot / Milestone versions you have to add the following section to your `pom.xml`
For Snapshot and Milestone versions, you have to add the following section to your
`pom.xml`, as shown here:
[source,xml,indent=0]
----
include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
----
[[maven-add-stubs]]
==== Add stubs
By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory.
Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test.
We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
So with following structure
By default, Spring Cloud Contract Verifier is looking for stubs in the
`src/test/resources/contracts` directory. The directory containing stub definitions is
treated as a class name, and each stub definition is treated as a single test. We assume
that it contains at least one directory to be used as test class name. If there is more
than one level of nested directories, all except the last one is used as package name.
For example, with following structure:
[source,groovy,indent=0]
----
@@ -390,17 +500,24 @@ src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy
----
Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
- `shouldCreateUser()`
- `shouldReturnUser()`
Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService`
with two methods
* `shouldCreateUser()`
* `shouldReturnUser()`
[[maven-run-plugin]]
==== Run plugin
Plugin goal `generateTests` is assigned to be invoked in phase `generate-test-sources`. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateTests` goal.
The plugin goal `generateTests` is assigned to be invoked in the phase called
`generate-test-sources`. If you want it to be part of your build process, you need not do
anything. If you just want to generate tests, invoke the `generateTests` goal.
[[maven-configure-plugin]]
==== Configure plugin
To change default configuration just add `configuration` section to plugin definition or `execution` definition.
To change the default configuration, just add a `configuration` section to the plugin
definition or the `execution` definition, as shown here:
[source,xml,indent=0]
----
@@ -423,44 +540,69 @@ To change default configuration just add `configuration` section to plugin defin
</plugin>
----
==== Important configuration options
[[maven-configuration-options]]
==== Configuration Options
- **testMode** - defines mode for acceptance tests. By default `MockMvc` which is based on Spring's MockMvc. It can also be changed to `JaxRsClient` or to `Explicit` for real HTTP calls.
- **basePackageForTests** - specifies base package for all generated tests. If not set the value will be picked from `baseClassForTests`'s package and from
`packageWithBaseClasses`. If neither of these are set then the value will be set to `org.springframework.cloud.contract.verifier.tests`
- **ruleClassForTests** - specifies Rule which should be added to generated test classes.
- **baseClassForTests** - base class for generated tests. By default `spock.lang.Specification` if using Spock tests.
- **contractsDirectory** - directory containing contracts written using the GroovyDSL. By default `/src/test/resources/contracts`.
- **testFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
- **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay.
The convention is such that if you have a contract under `src/test/resources/contract/foo/bar/baz/` and provide the value of this property
to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. Takes precedence
over **baseClassForTests**
- **baseClassMappings** - list of base class mappings that where you have to provide `contractPackageRegex` which is checked
against the package in which the contract lays and `baseClassFQN` that maps to fully qualified name of the base class for the matched
contract. If you have a contract under `src/test/resources/contract/foo/bar/baz/` and map the property `.*` -> `com.example.base.BaseClass` then
the test class generated from these contracts will extend `com.example.base.BaseClass`. Takes precedence over **packageWithBaseClasses**
and **baseClassForTests**.
* *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 *JaxRsClient* or to
*Explicit* for real HTTP calls.
* *basePackageForTests*: Specifies the base package for all generated tests. If not set,
the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`.
If neither of these values are set, then the value is set to
`org.springframework.cloud.contract.verifier.tests`.
* *ruleClassForTests*: Specifies a rule that should be added to the generated test
classes.
* *baseClassForTests*: Creates a base class for all generated tests. By default, if you
use Spock classes, the class is `spock.lang.Specification`.
* *contractsDirectory*: Specifies a directory containing contracts written with the
GroovyDSL. The default directory is `/src/test/resources/contracts`.
* *testFramework*: Specifies the target test framework to be used. Currently, Spock and
JUnit are supported with JUnit being the default framework
* *packageWithBaseClasses*: Defines a package where all the base classes reside. This
setting takes precedence over *baseClassForTests*. The convention is such that, if you
have a contract under (for example) `src/test/resources/contract/foo/bar/baz/` and set
the value of the `packageWithBaseClasses` property to `com.example.base`, then Spring
Cloud Contract Verifier assumes that there is a `BarBazBase` class under the
`com.example.base` package. In other words, the system takes the last two parts of the
package, if they exist, and forms a class with a `Base` suffix.
* *baseClassMappings*: Specifies a list of base class mappings that provide
`contractPackageRegex`, which is checked against the package where the contract is
located, and `baseClassFQN`, which maps to the fully qualified name of the base class for
the matched contract. For example, if you have a contract under
`src/test/resources/contract/foo/bar/baz/` and map the property
`.* -> com.example.base.BaseClass`, then the test class generated from these contracts
extends `com.example.base.BaseClass`. This setting takes precedence over
*packageWithBaseClasses* and *baseClassForTests*.
If you want to download your contract definitions from a Maven repository you can use
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** - path to concrete contracts in the JAR with packaged contracts. Defaults to `groupid/artifactid` where `gropuid` is slash separated.
- **contractsWorkOffline** - if the dependencies should be downloaded or local Maven only should be reused
- **contractsRepositoryUrl** - *DEPRECATED PROPERTY - please use the `contractRepository` closure* - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones
- **contractRepository** - closure where you can define properties related to repository with contracts
* **username** - username to be used to connect to the repo
* **password** - username to be used to connect to the repo
* **proxyHost** - proxy host to be used to connect to the repo
* **proxyPort** - proxy port to be used to connect to the repo
* **cacheDownloadedContracts** - if you want to reuse download JARs that contain contract definitions.
We cache only non-snapshot, explicitly provided versions (e.g. `+` or `1.0.0.BUILD-SNAPSHOT` won't get cached).
By default this feature is turned on.
* *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.
* *contractsWorkOffline*: Dictates whether the dependencies should be downloaded or the
local Maven artifacts should be reused.
* *contractsRepositoryUrl*: *DEPRECATED PROPERTY - please use the `contractRepository`
closure*: URL to a repo with the artifacts that have contracts. If it is not provided,
use the current Maven ones.
* *contractRepository* - Lets you use a closure where you can define properties related
to repository with contracts.
* *username*: The user name to be used to connect to the repo.
* *password*: The password to be used to connect to the repo.
* *proxyHost*: The proxy host to be used to connect to the repo.
* *proxyPort*: The proxy port to be used to connect to the repo.
* *cacheDownloadedContracts* - Specifies whether to reuse downloaded JARs that contain
contract definitions.
==== Single base class for all tests
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.
When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests.
In this class you need to point to endpoint which should be verified.
[[maven-single-base]]
==== 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.
[source,groovy,indent=0]
----
@@ -477,51 +619,64 @@ class MvcSpec extends Specification {
}
----
In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server.
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 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.
[[maven-different-base]]
==== 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:
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 the `packageWithBaseClasses`
* provide explicit mapping via `baseClassMappings`
*Convention*
*By Convention*
The convention is such that if you have a contract under e.g. `src/test/resources/contract/hello/v1/` and provide the value of the `packageWithBaseClasses` property
to `hello` then we will assume that there is a `HelloV1Base` class under `hello` package. In other words we take last two parts of package
if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage:
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:
[source,xml,indent=0]
----
include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[tags=convention,indent=0]
----
*Mapping*
*By Mapping*
You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract.
You have to provide a list `baseClassMappings` of `baseClassMapping` that takes a `contractPackageRegex` to `baseClassFQN` mapping.
Let's take a look at the following example:
You can manually map a regular expression of the contract's package to fully qualified
name of the base class for the matched contract. You have to provide a list called
`baseClassMappings` that consists `baseClassMapping` objects that takes a
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
[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]
----
Let's assume that you have contracts under
- `src/test/resources/contract/com/`
- `src/test/resources/contract/foo/`
By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide
the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
Assume that you have contracts under these two locations:
* `src/test/resources/contract/com/`
* `src/test/resources/contract/foo/`
By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed.
(You can also provide the `packageWithBaseClasses` as a fallback.) That way, the tests
generated from `src/test/resources/contract/com/` contracts extend the
`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`.
[[maven-invoking-generated-tests]]
==== Invoking generated tests
Spring Cloud Contract Maven Plugin generates verification code into directory `/generated-test-sources/contractVerifier` and attach this directory to `testCompile` goal.
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:
For Groovy Spock code, use the following:
[source,xml,indent=0]
----
@@ -555,17 +710,17 @@ For Groovy Spock code use:
</plugin>
----
To ensure that provider side is complaint with defined contracts, you need to invoke `mvn generateTest test`
==== FAQ with Maven Plugin
To ensure that provider side is compliant with defined contracts, you need to invoke
`mvn generateTest test`.
[[maven-sts]]
==== Maven Plugin and STS
In case you see the following exception while using STS
If you see the following exception while using STS:
image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception]
when you click on the marker you should see sth like this
When you click on the error marker you should see something like this:
[source,bash]
----
@@ -578,7 +733,7 @@ when you click on the marker you should see sth like this
org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
----
In order to fix this issue just provide the following section in your `pom.xml`
In order to fix this issue, provide the following section in your `pom.xml`:
[source,xml]
----
@@ -616,19 +771,20 @@ In order to fix this issue just provide the following section in your `pom.xml`
</build>
----
==== Spring Cloud Contract Verifier on consumer side
[[maven-consumer]]
==== Spring Cloud Contract Verifier on the Consumer Side
You can actually use the Spring Cloud Contract Verifier also for the consumer side!
You can use the plugin so that it only converts the contracts and generates the stubs.
To achieve that you need to configure Spring Cloud Contract Verifier plugin in exactly
the same way as in case of provider. You need to copy contracts stored in
`src/test/resources/contracts` and generate WireMock json stubs using:
`mvn generateStubs` command. By default generated WireMock mapping is
stored in directory `target/mappings`. Your project should create from
this generated mappings additional artifact with classifier `stubs` for
easy deploy to maven repository.
You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use
the plugin so that it only converts the contracts and generates the stubs. To achieve
that, you need to configure Spring Cloud Contract Verifier plugin in exactly the same way
as you would for a provider. You need to copy contracts stored in
`src/test/resources/contracts` and generate WireMock JSON stubs using the
`mvn generateStubs` command. By default, the generated WireMock mapping is stored in a
directory named `target/mappings`. From these generated mappings, your project should
create additional artifacts with a classifier of `stubs` for easy deployment to the maven
repository.
Sample configuration:
Here is a sample configuration:
[source,xml,indent=0]
----
@@ -647,7 +803,7 @@ Sample configuration:
</plugin>
----
When present, json stubs can be used in consumer automated tests.
When present, JSON stubs can be used in consumer automated tests, as shown here:
[source,groovy,indent=0]
----
@@ -672,38 +828,16 @@ public class LoanApplicationServiceTests {
}
}
----
`LoanApplication` makes a call to the `FraudDetection` service. This request is handled
by a WireMock server configured with stubs generated by the Spring Cloud Contract
Verifier.
Underneath `LoanApplication` makes a call to the `FraudDetection` service. This request is handled by
a WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
=== Stubs and Transitive Dependencies
=== Scenarios
It's possible to handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to proper naming convention while creating your contracts. The convention requires to include order number followed by the underscore.
[source,indent=0]
----
my_contracts_dir\
scenario1\
1_login.groovy
2_showCart.groovy
3_logout.groovy
----
Such tree will cause Spring Cloud Contract Verifier generating WireMock's scenario with name `scenario1` and three steps:
- login marked as `Started` pointing to:
- showCart marked as `Step1` pointing to:
- logout marked as `Step2` which will close the scenario.
More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html]
Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.
=== Stubs and transitive dependencies
The Maven and Gradle plugin that we're created are adding the tasks that create the stubs jar for you. What can be problematic
is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact
even though you have a couple of different jars, all of them share one pom:
The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One
problem that arises is that, when reusing the stubs, you can mistakenly import all of
that stub's dependencies. When building a Maven artifact, even though you have a couple
of different jars, all of them share one pom:
[source,bash,indent=0]
----
@@ -718,18 +852,53 @@ even though you have a couple of different jars, all of them share one pom:
└── ...
----
There are three possibilities of working with those dependencies so as not to have any issues with transitive dependencies.
There are three possibilities of working with those dependencies so as not to have any
issues with transitive dependencies:
* Mark all application dependencies as optional
* Create a separate artifactid for the stubs
* Exclude dependencies on the consumer side
*Mark all application dependencies as optional*
If in the `github-webhook` application we would mark all of our dependencies as optional, when you include the
`github-webhook` stubs in another application (or when that dependency gets downloaded by Stub Runner) then, since
all of the depenencies are optional, they will not get downloaded.
If, in the `github-webhook` application, you mark all of your dependencies as optional,
when you include the `github-webhook` stubs in another application (or when that
dependency gets downloaded by Stub Runner) then, since all of the dependencies are
optional, they will not get downloaded.
*Create a separate artifactid for stubs*
*Create a separate `artifactid` for the stubs*
If you create a separate artifactid then you can set it up in whatever way you wish. For example by having no dependencies at all.
If you create a separate `artifactid`, then you can set it up in whatever way you wish.
For example, you might decide to have no dependencies at all.
*Exclude dependencies on the consumer side*
As a consumer, if you add the stub dependency to your classpath you can explicitly exclude the unwanted dependencies.
As a consumer, if you add the stub dependency to your classpath, you can explicitly
exclude the unwanted dependencies.
=== Scenarios
You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to
stick to the proper naming convention while creating your contracts. The convention
requires including an order number followed by an underscore, as shown in this example:
[source,indent=0]
----
my_contracts_dir\
scenario1\
1_login.groovy
2_showCart.groovy
3_logout.groovy
----
Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a
name of `scenario1` and the three following steps:
. login marked as `Started` pointing to...
. showCart marked as `Step1` pointing to...
. logout marked as `Step2` which will close the scenario.
More details about WireMock scenarios can be found at
http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html]
Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

View File

@@ -1,16 +1,17 @@
== Spring Cloud Contract Stub Runner
One of the issues that you could have encountered while using Spring Cloud Contract Verifier was to pass the generated WireMock JSON stubs from the server side to the client side (or various clients).
The same takes place in terms of client side generation for messaging.
One of the issues that you might encounter while using Spring Cloud Contract Verifier is
passing the generated WireMock JSON stubs from the server side to the client side (or to
various clients). The same takes place in terms of client-side generation for messaging.
Copying the JSON files / setting the client side for messaging manually is out of the question.
That's why we'll introduce Spring Cloud Contract Stub Runner that can download and run the stubs
automatically for you.
Copying the JSON files and setting the client side for messaging manually is out of the
question. That is why we introduced Spring Cloud Contract Stub Runner. It can
automatically download and run the stubs for you.
=== Snapshot versions
Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:
Add the additional snapshot repository to your `build.gradle` file to use snapshot
versions, which are automatically uploaded after every successful build:
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -24,16 +25,18 @@ include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0]
----
=== 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 would be to centralize the way stubs are kept. For example, you can
keep them as jars in a Maven repository.
TIP: For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to.
TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize
it if you want to.
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
----
<!-- First disable the default jar setup in the properties section-->
<!-- First disable the default jar setup in the properties section -->
include::{samples_url}/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0]
<!-- Next add the assembly plugin to your build -->
@@ -53,56 +56,59 @@ include::{stubrunner_core_path}/README.adoc[]
=== Common
==== Common properties for JUnit and Spring
This section briefly describes common properties, including:
Some of the properties that are repetitive can be set using system properties or configuration properties (for Spring). Here are their names with their default values:
* <<common-properties-junit-spring>>
* <<stub-runner-stub-ids>>
[[common-properties-junit-spring]]
==== 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:
[frame="topbot",options="header"]
|===============
| Property name | Default value | Description
|stubrunner.minPort|10000| Minimal value of a port for a started WireMock with stubs
|stubrunner.maxPort|15000| Minimal value of a port for a started WireMock with stubs
|stubrunner.repositoryRoot|| Maven repo url. If blank then will call the local maven repo
|stubrunner.classifier|stubs| Default classifier for the stub artifacts
|stubrunner.workOffline|false| If true then will not contact any remote repositories to download stubs
|stubrunner.ids|| Array of Ivy notation stubs to download
|stubrunner.username|| Optional username to access the tool that stores the JARs with stubs
|stubrunner.password|| Optional password to access the tool that stores the JARs with stubs
|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs per each consumer instead of registering all stubs for every consumer
|stubrunner.consumerName|| If you want to use stubs per consumer and want to override the consumer name just change this value
|stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs.
|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs.
|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo.
|stubrunner.classifier|stubs| Default classifier for the stub artifacts.
|stubrunner.workOffline|false| If true, then do not contact any remote repositories to
download stubs.
|stubrunner.ids|| Array of Ivy notation stubs to download.
|stubrunner.username|| Optional username to access the tool that stores the JARs with
stubs.
|stubrunner.password|| Optional password to access the tool that stores the JARs with
stubs.
|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for
each consumer instead of registering all stubs for every consumer.
|stubrunner.consumerName|| If you want to use a stub for each consumer and want to
override the consumer name just change this value.
|===============
==== Stub runner stubs ids
[[stub-runner-stub-ids]]
==== Stub Runner Stubs IDs
You can provide the stubs to download via the `stubrunner.ids` system property. They follow the following pattern:
You can provide the stubs to download via the `stubrunner.ids` system property. They
follow this pattern:
[source,java,indent=0]
----
groupId:artifactId:version:classifier:port
----
`version`, `classifier` and `port` are optional.
Note that `version`, `classifier` and `port` are optional.
* If you don't provide the `port` then a random one will be picked
* If you don't provide the `classifier` then the default one will be taken. (NOTE that you can pass an empty classifier like this `groupId:artifactId:version:`)
* If you don't provide the `version` then the `+` will be passed and the latest one will be downloaded
* If you do not provide the `port`, a random one will be picked.
* If you do not provide the `classifier`, the default is used. (Note that you can
pass an empty classifier this way: `groupId:artifactId:version:`).
* If you do not provide the `version`, then the `+` will be passed and the latest one is
downloaded.
Where `port` means the port of the WireMock server.
`port` means the port of the WireMock server.
IMPORTANT: Starting from version 1.0.4 as a version you can provide a range of versions that you would like
the Stub Runner to take into consideration. You can read more about the https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning ranges here].
Taken from http://download.eclipse.org/aether/aether-core/0.9.0/apidocs/org/eclipse/aether/util/version/GenericVersionScheme.html[Aether Docs]:
> This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments. The characters '-', '_', and '.' as well as the mere
> transitions from digit to letter and vice versa delimit the version segments. Delimiters are treated as equivalent.
>
> Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and case-insensitively. However, the following qualifier strings are
> recognized and treated specially: "alpha" = "a" < "beta" = "b" < "milestone" = "m" < "cr" = "rc" < "snapshot" < "final" = "ga" < "sp". All of those well-known qualifiers
> are considered smaller/older than other strings. An empty segment/string is equivalent to 0.
>
> In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to denote the smallest/greatest version having a given prefix.
> For example, "1.2.min" denotes the smallest version in the 1.2 line, "1.2.max" denotes the greatest version in the 1.2 line. A version range of the form "[M.N.*]" is short for "[M.N.min, M.N.max]".
>
> Numbers and strings are considered incomparable against each other. Where version segments of different kind would collide, comparison will instead assume that the previous
> segments are padded with trailing 0 or "ga" segments, respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1".
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].

View File

@@ -1,12 +1,13 @@
== Stub Runner for Messaging
Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box
Stub Runner can run the published stubs in memory. It can integrate with the following
frameworks:
- Spring Integration
- Spring Cloud Stream
- Spring AMQP
* Spring Integration
* Spring Cloud Stream
* Spring AMQP
It also provides points of entry to integrate with any other solution on the market.
It also provides entry points to integrate with any other solution on the market.
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
@@ -15,39 +16,48 @@ That way the only remaining framework is Spring AMQP.
=== Stub triggering
To trigger a message it's enough to use the `StubTrigger` interface:
To trigger a message, use the `StubTrigger` interface:
[source,groovy]
----
include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java[lines=16..-1]
----
For convenience the `StubFinder` interface extends `StubTrigger` so it's enough to use only one in your tests.
For convenience, the `StubFinder` interface extends `StubTrigger`, so you only need one
or the other in your tests.
`StubTrigger` gives you the following options to trigger a message:
==== Trigger by label
* <<trigger-label>>
* <<trigger-group-artifact-ids>>
* <<trigger-artifact-ids>>
* <<trigger-all-messages>>
[[trigger-label]]
==== Trigger by 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]
----
==== Trigger by group and artifact ids
[[trigger-group-artifact-ids]]
==== Trigger by Group and Artifact Ids
[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_group_artifact,indent=0]
----
==== Trigger by artifact ids
[[trigger-artifact-ids]]
==== Trigger by Artifact Ids
[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_artifact,indent=0]
----
==== Trigger all messages
[[trigger-all-messages]]
==== Trigger All Messages
[source,groovy]
----
@@ -58,4 +68,4 @@ include::{tests_path}/spring-cloud-contract-stub-runner-integration/README.adoc[
include::{tests_path}/spring-cloud-contract-stub-runner-stream/README.adoc[]
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/README.adoc[]
include::{tests_path}/spring-cloud-contract-stub-runner-amqp/README.adoc[]

View File

@@ -1,35 +1,36 @@
=== Stub Runner Spring AMQP
Spring Cloud Contract Verifier Stub Runner's messaging module provides an easy way to integrate with Spring AMQP's Rabbit Template.
For the provided artifacts it will automatically download the stubs and register the required
routes.
Spring Cloud Contract Verifier Stub Runner's messaging module provides an easy way to
integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it
automatically downloads the stubs and registers the required routes.
The integration tries to work standalone, that is without interaction with a running RabbitMQ message broker.
It expects a `RabbitTemplate` on the application context and uses it as a spring boot test `@SpyBean`.
Thus it can use the mockito spy functionality to verify and introspect messages sent by the application.
The integration tries to work standalone (that is, without interaction with a running
RabbitMQ message broker). It expects a `RabbitTemplate` on the application context and
uses it as a spring boot test named `@SpyBean`. As a result, it can use the mockito spy
functionality to verify and inspect messages sent by the application.
On the message consumer side, it considers all `@RabbitListener` annotated endpoints as well as all `SimpleMessageListenerContainer`s on the application context.
On the message consumer side, the stub runner considers all `@RabbitListener` annotated
endpoints and all `SimpleMessageListenerContainer` objects on the application context.
As messages are usually sent to exchanges in AMQP the message contract contains the exchange name as the destination.
Message listeners on the other side are bound to queues. Bindings connect an exchange to a queue.
If message contracts are triggered the Spring AMQP stub runner integration will look for bindings on the application context that match this exchange.
Then it collects the queues from the Spring exchanges and tries to find messages listeners bound to these queues.
The message is triggered to all matching message listeners.
As messages are usually sent to exchanges in AMQP, the message contract contains the
exchange name as the destination. Message listeners on the other side are bound to
queues. Bindings connect an exchange to a queue. If message contracts are triggered, the
Spring AMQP stub runner integration looks for bindings on the application context that
match this exchange. Then it collects the queues from the Spring exchanges and tries to
find message listeners bound to these queues. The message is triggered for all matching
message listeners.
==== Adding it to the project
==== Adding the Runner to the Project
It's enough to have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and set the property `stubrunner.amqp.enabled=true`.
Remember to annotate your test class with `@AutoConfigureStubRunner`.
You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and
set the property `stubrunner.amqp.enabled=true`. Remember to annotate your test class
with `@AutoConfigureStubRunner`.
IMPORTANT: If you already have Stream and Integration on the classpath you need
to disable them explicitly via `stubrunner.stream.enabled=false` and `stubrunner.integration.enabled=false`
properties
IMPORTANT: If you already have Stream and Integration on the classpath, you need
to disable them explicitly by setting the `stubrunner.stream.enabled=false` and
`stubrunner.integration.enabled=false` properties.
==== Examples
===== Stubs structure
Let us assume that we have the following Maven repository with a deployed stubs for the
Assume that you have the following Maven repository with a deployed stubs for the
`spring-cloud-contract-amqp-test` application.
[source,bash,indent=0]
@@ -46,7 +47,7 @@ Let us assume that we have the following Maven repository with a deployed stubs
└── maven-metadata-local.xml
----
And the stubs contain the following structure:
Further assume that the stubs contain the following structure:
[source,bash,indent=0]
----
@@ -56,14 +57,14 @@ And the stubs contain the following structure:
└── shouldProduceValidPersonData.groovy
----
Let's consider the following contract:
Consider the following contract:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0]
----
and the following Spring configuration:
Now consider the following Spring configuration:
[source,yaml]
----
@@ -72,41 +73,46 @@ include::src/test/resources/application.yml[]
===== Triggering the message
So to trigger a message using the contract above we'll use the `StubTrigger` interface as follows.
To trigger a message using the contract above, use the `StubTrigger` interface as
follows:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
The message has the destination `contract-test.exchange` so the Spring AMQP stub runner integration looks for bindings related to this exchange.
The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner
integration looks for bindings related to this exchange.
[source,java]
----
include::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`.
So the following listener definition is a match and is invoked with the contract message.
The binding definition binds the queue `test.queue`. As a result, the following listener
definition is matched and invoked with the contract message.
[source,java]
----
include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0]
----
Also, the following annotated listener represents a match and would be invoked.
Also, the following annotated listener matches and is invoked:
[source,java]
----
include::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`.
NOTE: The message is directly handed over to the `onMessage` method of the
`MessageListener` associated with the matching `SimpleMessageListenerContainer`.
===== Spring AMQP Test Configuration
In order to avoid that Spring AMQP is trying to connect to a running broker during our tests we configure a mock `ConnectionFactory`.
In order to avoid Spring AMQP trying to connect to a running broker during our tests
configure a mock `ConnectionFactory`.
To disable the mocked ConnectionFactory set the property `stubrunner.amqp.mockConnection=false`
To disable the mocked ConnectionFactory, set the following property:
`stubrunner.amqp.mockConnection=false`
[source,yaml]
----

View File

@@ -3,25 +3,22 @@
=== Stub Runner Integration
Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to integrate with Spring Integration.
For the provided artifacts it will automatically download the stubs and register the required
routes.
Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to
integrate with Spring Integration. For the provided artifacts, it automatically downloads
the stubs and registers the required routes.
==== Adding it to the project
==== Adding the Runner to the Project
It's enough to have both Spring Integration and Spring Cloud Contract Stub Runner on classpath.
Remember to annotate your test class with `@AutoConfigureStubRunner`.
You can have both Spring Integration and Spring Cloud Contract Stub Runner on the
classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`.
==== Disabling the functionality
If you need to disable this functionality just pass `stubrunner.integration.enabled=false` property.
If you need to disable this functionality, set the
`stubrunner.integration.enabled=false` property.
==== Examples
===== Stubs structure
Let us assume that we have the following Maven repository with a deployed stubs for the
`integrationService` application.
Assume that you have the following Maven repository with deployed stubs for the
`integrationService` application:
[source,bash,indent=0]
----
@@ -39,7 +36,7 @@ Let us assume that we have the following Maven repository with a deployed stubs
└── maven-metadata-local.xml
----
And the stubs contain the following structure:
Further assume the stubs contain the following structure:
[source,bash,indent=0]
----
@@ -53,14 +50,14 @@ And the stubs contain the following structure:
└── mappings
----
Let's consider the following contracts (let' number it with *1*):
Consider the following contracts (numbered *1*):
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
----
and number *2*
Now consider *2*:
[source,groovy]
----
@@ -74,56 +71,66 @@ and the following Spring Integration Route:
include::src/test/resources/integration-context.xml[lines=1;18..-1]
----
These examples lend themselves to three scenarios:
* <<integration-scenario-1>>
* <<integration-scenario-2>>
* <<integration-scenario-3>>
[[integration-scenario-1]]
===== Scenario 1 (no input message)
So as to trigger a message via the `return_book_1` label we'll use the `StubTigger` interface as follows
To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as
follows:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
Next we'll want to listen to the output of the message sent to `{output_name}`
To listen to the output of the message sent to `{output_name}`:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0]
----
And the received message would pass the following assertions
The received message would pass the following assertions:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0]
----
[[integration-scenario-1]]
===== 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::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0]
----
Next we'll want to listen to the output of the message sent to `{output_name}`
To listen to the output of the message sent to `{output_name}`:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0]
----
And the received message would pass the following assertions
The received message passes the following assertions:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0]
----
[[integration-scenario-3]]
===== Scenario 3 (input with no output)
Since the route is set for you it's enough to just send a message to the `{input_name}` destination.
Since the route is set for you, you can send a message to the `{input_name}` destination:
[source,groovy]
----

View File

@@ -1,15 +1,15 @@
=== Stub Runner Stream
Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to integrate with Spring Stream.
For the provided artifacts it will automatically download the stubs and register the required
routes.
Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to
integrate with Spring Stream. For the provided artifacts, it automatically downloads the
stubs and registers the required routes.
WARNING: In Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings are resolved
first as a `destination` of a channel, and then if there is no such `destination` it's resolved as a
channel name.
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
destination is resolved as a channel name.
IMPORTANT: If you want to use Spring Cloud Stream remember to add a
`org.springframework.cloud:spring-cloud-stream-test-support` dependency.
IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on
`org.springframework.cloud:spring-cloud-stream-test-support`.
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
.Maven
@@ -27,21 +27,18 @@ IMPORTANT: If you want to use Spring Cloud Stream remember to add a
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
----
==== Adding it to the project
==== Adding the Runner to the Project
It's enough to have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on classpath.
Remember to annotate your test class with `@AutoConfigureStubRunner`.
You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the
classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`.
==== Disabling the functionality
If you need to disable this functionality just pass `stubrunner.stream.enabled=false` property.
If you need to disable this functionality, set the `stubrunner.stream.enabled=false`
property.
==== Examples
===== Stubs structure
Let us assume that we have the following Maven repository with a deployed stubs for the
`streamService` application.
Assume that you have the following Maven repository with a deployed stubs for the
`streamService` application:
[source,bash,indent=0]
----
@@ -59,7 +56,7 @@ Let us assume that we have the following Maven repository with a deployed stubs
└── maven-metadata-local.xml
----
And the stubs contain the following structure:
Further assume the stubs contain the following structure:
[source,bash,indent=0]
----
@@ -73,77 +70,89 @@ And the stubs contain the following structure:
└── mappings
----
Let's consider the following contracts (let' number it with *1*):
Consider the following contracts (numbered *1*):
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
----
and number *2*
Now consider *2*:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0]
----
and the following Spring configuration:
Now consider the following Spring configuration:
[source,yaml]
----
include::src/test/resources/application.yml[]
----
These examples lend themselves to three scenarios:
* <<stream-scenario-1>>
* <<stream-scenario-2>>
* <<stream-scenario-3>>
[[stream-scenario-1]]
===== Scenario 1 (no input message)
So as to trigger a message via the `return_book_1` label we'll use the `StubTrigger` interface as follows
To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as
follows:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0]
----
Next we'll want to listen to the output of the message sent to a channel whose `destination` is `returnBook`
To listen to the output of the message sent to a channel whose `destination` is
`returnBook`:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0]
----
And the received message would pass the following assertions
The received message passes the following assertions:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0]
----
[[stream-scenario-2]]
===== Scenario 2 (output triggered by input)
Since the route is set for you it's enough to just send a message to the `bookStorage` `destination`.
Since the route is set for you, you can send a message to the `bookStorage`
`destination`:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0]
----
Next we'll want to listen to the output of the message sent to `returnBook`
To listen to the output of the message sent to `returnBook`:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0]
----
And the received message would pass the following assertions
The received message passes the following assertions:
[source,groovy]
----
include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0]
----
[[stream-scenario-3]]
===== 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:
[source,groovy]
----