Merge branch 'Buzzardo-new_docs'
fixes gh-1140 fixes gh-1157
This commit is contained in:
@@ -1,15 +1,8 @@
|
||||
:branch: master
|
||||
image::https://badges.gitter.im/Join%20Chat.svg[Gitter, link="https://gitter.im/spring-cloud/spring-cloud-contract?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"]
|
||||
image::https://codecov.io/gh/spring-cloud/spring-cloud-contract/branch/{branch}/graph/badge.svg["codecov", link="https://codecov.io/gh/spring-cloud/spring-cloud-contract"]
|
||||
image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg["CircleCI", link="https://circleci.com/gh/spring-cloud/spring-cloud-contract"]
|
||||
:introduction_url: ../../../..
|
||||
:verifier_core_path: {introduction_url}/spring-cloud-contract-verifier
|
||||
|
||||
== Spring Cloud Contract
|
||||
|
||||
You always need confidence when pushing new features into a new application or service in
|
||||
a distributed system. To that end, this project provides support for Consumer-driven
|
||||
Contracts and service schemas in Spring applications, covering a range of options for
|
||||
a distributed system. To that end, this project provides support for consumer-driven
|
||||
contracts and service schemas in Spring applications, covering a range of options for
|
||||
writing tests, publishing them as assets, and asserting that a contract is kept by
|
||||
producers and consumers -- for both HTTP and message-based interactions.
|
||||
|
||||
@@ -19,13 +12,12 @@ If you prefer to learn about the project by doing some tutorials, you can check
|
||||
workshops under
|
||||
https://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link].
|
||||
|
||||
== Documentation
|
||||
== Project page
|
||||
|
||||
You can read more about Spring Cloud Contract Verifier by reading the
|
||||
{documentation_url}[docs]
|
||||
You can read more about Spring Cloud Contract by going to https://spring.io/projects/spring-cloud-contract[the project page]
|
||||
|
||||
== Contributing
|
||||
|
||||
include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/docs/src/main/asciidoc/contributing.adoc[]
|
||||
|
||||
include::building.adoc[]
|
||||
include::_building.adoc[]
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
:core_path: ../../..
|
||||
:plugins_path: ../../../spring-cloud-contract-tools
|
||||
:doctype: book
|
||||
:idprefix:
|
||||
:idseparator: -
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:tabsize: 4
|
||||
:numbered:
|
||||
:sectanchors:
|
||||
:sectnums:
|
||||
:icons: font
|
||||
:hide-uri-scheme:
|
||||
:docinfo: shared,private
|
||||
|
||||
:sc-ext: java
|
||||
:project-full-name: Spring Cloud Contract
|
||||
|
||||
// project-specific attributes
|
||||
:core_path: {project-root}
|
||||
:plugins_path: {project-root}/spring-cloud-contract-tools
|
||||
:converters_path: {plugins_path}/spring-cloud-contract-converters
|
||||
:verifier_root_path: {core_path}/spring-cloud-contract-verifier
|
||||
:contract_spec_path: {core_path}/specs/spring-cloud-contract-spec-java
|
||||
@@ -12,20 +29,9 @@
|
||||
:standalone_pact_path: {samples_path}/standalone/pact
|
||||
:standalone_restdocs_path: {samples_path}/standalone/restdocs
|
||||
:tests_path: {core_path}/tests
|
||||
:samples_branch: 2.1.x
|
||||
:samples_branch: 2.2.x
|
||||
:samples_url: https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/{samples_branch}
|
||||
:introduction_url: ${core_path}/../../
|
||||
|
||||
include::verifier_introduction.adoc[]
|
||||
|
||||
include::verifier_faq.adoc[]
|
||||
|
||||
include::verifier_setup.adoc[]
|
||||
|
||||
include::verifier_messaging.adoc[]
|
||||
|
||||
include::verifier_stubrunner.adoc[]
|
||||
|
||||
include::verifier_stubrunner_msg.adoc[]
|
||||
|
||||
include::verifier_contract.adoc[]
|
||||
:samples_code: https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/
|
||||
:doc_samples: {core_path}/samples/wiremock-jetty
|
||||
:wiremock_tests: {core_path}/spring-cloud-contract-wiremock
|
||||
:introduction_url: {core_path}
|
||||
107
docs/src/main/asciidoc/_building.adoc
Normal file
107
docs/src/main/asciidoc/_building.adoc
Normal file
@@ -0,0 +1,107 @@
|
||||
== How to Build Spring Cloud Contract
|
||||
|
||||
IMPORTANT: You need to have all the necessary Groovy plugins
|
||||
installed for your IDE to properly resolve the sources. For example, in
|
||||
Intellij IDEA, having both the Eclipse Groovy Compiler Plugin and the GMavenPlus Intellij
|
||||
Plugin results in properly imported project.
|
||||
|
||||
IMPORTANT: Spring Cloud Contract builds Docker images. Remember to
|
||||
have Docker installed.
|
||||
|
||||
IMPORTANT: If you want to run the build in offline mode, you must have Maven 3.5.2+ installed.
|
||||
|
||||
=== Project structure
|
||||
|
||||
The following listing shows the Spring Cloud Contract folder structure:
|
||||
|
||||
```
|
||||
├── config
|
||||
├── docker
|
||||
├── samples
|
||||
├── scripts
|
||||
├── specs
|
||||
├── spring-cloud-contract-dependencies
|
||||
├── spring-cloud-contract-shade
|
||||
├── spring-cloud-contract-starters
|
||||
├── spring-cloud-contract-stub-runner
|
||||
├── spring-cloud-contract-stub-runner-boot
|
||||
├── spring-cloud-contract-tools
|
||||
├── spring-cloud-contract-verifier
|
||||
├── spring-cloud-contract-wiremock
|
||||
└── tests
|
||||
```
|
||||
|
||||
The following list describes each of the top-level folders in the project structure:
|
||||
|
||||
- `config`: Folder contains setup for Spring Cloud Release Tools automated release process
|
||||
- `docker`: Folder contains docker images
|
||||
- `samples`: Folder contains test samples together with standalone ones used also to build documentation
|
||||
- `scripts`: Contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
|
||||
- `specs`: Contains specifications for the Contract DSL.
|
||||
- `spring-cloud-contract-dependencies`: Contains Spring Cloud Contract BOM
|
||||
- `spring-cloud-contract-shade`: Shaded dependencies used by the plugins
|
||||
- `spring-cloud-contract-starters`: Contains Spring Cloud Contract Starters
|
||||
- `spring-cloud-contract-spec`: Contains specification modules (contains concept of a Contract)
|
||||
- `spring-cloud-contract-stub-runner`: Contains Stub Runner related modules
|
||||
- `spring-cloud-contract-stub-runner-boot`: Contains Stub Runner Boot app
|
||||
- `spring-cloud-contract-tools`: Gradle and Maven plugin for `Spring Cloud Contract Verifier`
|
||||
- `spring-cloud-contract-verifier`: Core of the `Spring Cloud Contract Verifier` functionality
|
||||
- `spring-cloud-contract-wiremock`: All WireMock related functionality
|
||||
- `tests`: Integration tests for different messaging technologies
|
||||
|
||||
=== Commands
|
||||
|
||||
To build the core functionality together with the Maven Plugin, you can run the following
|
||||
command:
|
||||
|
||||
```
|
||||
./mvnw clean install -P integration
|
||||
```
|
||||
|
||||
Calling that function builds the core, the Maven plugin, and the Gradle plugin and runs
|
||||
end-to_end tests on the
|
||||
standalone samples in the proper order (both for Maven and Gradle).
|
||||
|
||||
To build only the Gradle Plugin, you can run the following commands:
|
||||
|
||||
```
|
||||
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
|
||||
./gradlew clean build
|
||||
```
|
||||
|
||||
=== Helpful scripts
|
||||
|
||||
We provide a couple of helpful scripts to build the project.
|
||||
|
||||
To build the project in parallel (by default, it uses four cores, but you can change it),
|
||||
run the following command:
|
||||
|
||||
```
|
||||
./scripts/parallelBuild.sh
|
||||
```
|
||||
|
||||
To use eight 8 cores, run thke following command:
|
||||
|
||||
```
|
||||
CORES=8 ./scripts/parallelBuild.sh
|
||||
```
|
||||
|
||||
To build the project without any integration tests (by default, this uses one core), run
|
||||
the following command:
|
||||
|
||||
```
|
||||
./scripts/noIntegration.sh
|
||||
```
|
||||
|
||||
To use eight cores, run the following command:
|
||||
|
||||
```
|
||||
CORES=8 ./scripts/noIntegration.sh
|
||||
```
|
||||
|
||||
To generate the documentation (for both the root project and the maven plugin), run the
|
||||
following command:
|
||||
|
||||
```
|
||||
./scripts/generateDocs.sh
|
||||
```
|
||||
1376
docs/src/main/asciidoc/_project-features-contract.adoc
Normal file
1376
docs/src/main/asciidoc/_project-features-contract.adoc
Normal file
File diff suppressed because it is too large
Load Diff
425
docs/src/main/asciidoc/_project-features-flows.adoc
Normal file
425
docs/src/main/asciidoc/_project-features-flows.adoc
Normal file
@@ -0,0 +1,425 @@
|
||||
[[feature-integrations]]
|
||||
== Integrations
|
||||
include::_attributes.adoc[]
|
||||
|
||||
[[features-jax-rs]]
|
||||
=== JAX-RS
|
||||
|
||||
The Spring Cloud Contract supports the JAX-RS 2 Client API. The base class needs
|
||||
to define `protected WebTarget webTarget` and server initialization. The only option for
|
||||
testing JAX-RS API is to start a web server. Also, a request with a body needs to have a
|
||||
content type be set. Otherwise, the default of `application/octet-stream` gets used.
|
||||
|
||||
In order to use JAX-RS mode, use the following settings:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
testMode == 'JAXRSCLIENT'
|
||||
----
|
||||
|
||||
The following example shows a generated test API:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0]
|
||||
----
|
||||
|
||||
[[feature-webflux]]
|
||||
=== WebFlux with WebTestClient
|
||||
|
||||
You can work with WebFlux by using WebTestClient. The following listing shows how to
|
||||
configure WebTestClient as the test mode:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<testMode>WEBTESTCLIENT</testMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
contracts {
|
||||
testMode = 'WEBTESTCLIENT'
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows how to set up a WebTestClient base class and RestAssured
|
||||
for WebFlux:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
|
||||
import org.junit.Before;
|
||||
|
||||
public abstract class BeerRestBase {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
RestAssuredWebTestClient.standaloneSetup(
|
||||
new ProducerController(personToCheck -> personToCheck.age >= 20));
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
TIP: The `WebTestClient` mode is faster than the `EXPLICIT` mode.
|
||||
|
||||
[[feature-webflux-explicit]]
|
||||
=== WebFlux with Explicit Mode
|
||||
|
||||
You can also use WebFlux with the explicit mode in your generated tests
|
||||
to work with WebFlux. The following example shows how to configure using explicit mode:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<testMode>EXPLICIT</testMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
contracts {
|
||||
testMode = 'EXPLICIT'
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows how to set up a base class and RestAssured for Web Flux:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=annotations,indent=0]
|
||||
|
||||
// your tests go here
|
||||
|
||||
// in this config class you define all controllers and mocked services
|
||||
include::{samples_url}/producer_webflux/src/test/java/com/example/BeerRestBase.java[tags=config,indent=0]
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
[[features-context-paths]]
|
||||
=== Working with Context Paths
|
||||
|
||||
Spring Cloud Contract supports context paths.
|
||||
|
||||
[IMPORTANT]
|
||||
=====
|
||||
The only change needed to fully support context paths is the switch on the
|
||||
producer side. Also, the autogenerated tests must use explicit mode. The consumer
|
||||
side remains untouched. In order for the generated test to pass, you must use explicit
|
||||
mode. The following example shows how to set the test mode to `EXPLICIT`:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<testMode>EXPLICIT</testMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
contracts {
|
||||
testMode = 'EXPLICIT'
|
||||
}
|
||||
----
|
||||
====
|
||||
=====
|
||||
|
||||
That way, you generate a test that does not use MockMvc. It means that you generate
|
||||
real requests and you need to set up your generated test's base class to work on a real
|
||||
socket.
|
||||
|
||||
Consider the following contract:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0]
|
||||
----
|
||||
|
||||
The following example shows how to set up a base class and RestAssured:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_baseclass,indent=0]
|
||||
----
|
||||
|
||||
If you do it this way:
|
||||
|
||||
* All of your requests in the autogenerated tests are sent to the real endpoint with your
|
||||
context path included (for example, `/my-context-path/url`).
|
||||
* Your contracts reflect that you have a context path. Your generated stubs also have
|
||||
that information (for example, in the stubs, you have to call `/my-context-path/url`).
|
||||
|
||||
[[features-rest-docs]]
|
||||
=== Working with REST Docs
|
||||
|
||||
You can use https://projects.spring.io/spring-restdocs[Spring REST Docs] to generate
|
||||
documentation (for example, in Asciidoc format) for an HTTP API with Spring MockMvc,
|
||||
`WebTestClient`, or RestAssured. At the same time that you generate documentation for your API, you can also
|
||||
generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your
|
||||
normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be
|
||||
automatically generated in the REST Docs output directory.
|
||||
|
||||
[plantuml, rest-docs, png]
|
||||
----
|
||||
"API Producer"->"API Producer": Add Spring Cloud Contract (SCC) \nStub Runner dependency
|
||||
"API Producer"->"API Producer": Set up stub jar assembly
|
||||
"API Producer"->"API Producer": Write and set up REST Docs tests
|
||||
"API Producer"->"Build": Run build
|
||||
"Build"->"REST Docs": Generate API \ndocumentation
|
||||
"REST Docs"->"SCC": Generate stubs from the \nREST Docs tests
|
||||
"REST Docs"->"SCC": Generate contracts from the \nREST Docs tests
|
||||
"Build"->"Build": Assemble stubs jar with \nstubs and contracts
|
||||
"Build"->"Nexus / Artifactory": Upload contracts \nand stubs and the project arifact
|
||||
"Build"->"API Producer": Build successful
|
||||
"API Consumer"->"API Consumer": Add SCC Stub Runner \ndependency
|
||||
"API Consumer"->"API Consumer": Write a SCC Stub Runner \nbased contract test
|
||||
"SCC Stub Runner"->"Nexus / Artifactory": Test asks for [API Producer] stubs
|
||||
"Nexus / Artifactory"->"SCC Stub Runner": Fetch the [API Producer] stubs
|
||||
"SCC Stub Runner"->"SCC Stub Runner": Run in memory\n HTTP server stubs
|
||||
"API Consumer"->"SCC Stub Runner": Send a request \nto the HTTP server stub
|
||||
"SCC Stub Runner"->"API Consumer": Communication is correct
|
||||
----
|
||||
|
||||
The following example uses `MockMvc`:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureMockMvc
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(get("/resource"))
|
||||
.andExpect(content().string("Hello World"))
|
||||
.andDo(document("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
This test generates a WireMock stub at `target/snippets/stubs/resource.json`. It matches
|
||||
all `GET` requests to the `/resource` path. The same example with `WebTestClient` (used
|
||||
for testing Spring WebFlux applications) would be as follows:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureWebTestClient
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private WebTestClient client;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
client.get().uri("/resource").exchange()
|
||||
.expectBody(String.class).isEqualTo("Hello World")
|
||||
.consumeWith(document("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
Without any additional configuration, these tests create a stub with a request matcher
|
||||
for the HTTP method and all headers except `host` and `content-length`. To match the
|
||||
request more precisely (for example, to match the body of a POST or PUT), we need to
|
||||
explicitly create a request matcher. Doing so has two effects:
|
||||
|
||||
* Creating a stub that matches only in the way you specify.
|
||||
* Asserting that the request in the test case also matches the same conditions.
|
||||
|
||||
The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used
|
||||
as a substitute for the `document()` convenience method, as the following
|
||||
example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureMockMvc
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(post("/resource")
|
||||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(verify().jsonPath("$.id")
|
||||
.stub("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The preceding contract specifies that any valid POST with an `id` field receives the response
|
||||
defined in this test. You can chain together calls to `.jsonPath()` to add additional
|
||||
matchers. If JSON Path is unfamiliar, the https://github.com/jayway/JsonPath[JayWay
|
||||
documentation] can help you get up to speed. The `WebTestClient` version of this test
|
||||
has a similar `verify()` static helper that you insert in the same place.
|
||||
|
||||
Instead of the `jsonPath` and `contentType` convenience methods, you can also use the
|
||||
WireMock APIs to verify that the request matches the created stub, as the
|
||||
following example shows:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(post("/resource")
|
||||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(verify()
|
||||
.wiremock(WireMock.post(
|
||||
urlPathEquals("/resource"))
|
||||
.withRequestBody(matchingJsonPath("$.id"))
|
||||
.stub("post-resource"));
|
||||
}
|
||||
----
|
||||
|
||||
The WireMock API is rich. You can match headers, query parameters, and the request body by
|
||||
regex as well as by JSON path. You can use these features to create stubs with a wider
|
||||
range of parameters. The preceding example generates a stub resembling the following example:
|
||||
|
||||
.post-resource.json
|
||||
[source,json]
|
||||
----
|
||||
{
|
||||
"request" : {
|
||||
"url" : "/resource",
|
||||
"method" : "POST",
|
||||
"bodyPatterns" : [ {
|
||||
"matchesJsonPath" : "$.id"
|
||||
}]
|
||||
},
|
||||
"response" : {
|
||||
"status" : 200,
|
||||
"body" : "Hello World",
|
||||
"headers" : {
|
||||
"X-Application-Context" : "application:-1",
|
||||
"Content-Type" : "text/plain"
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()`
|
||||
methods to create request matchers, but you cannot use both approaches.
|
||||
|
||||
On the consumer side, you can make the `resource.json` generated earlier in this section
|
||||
available on the classpath (by
|
||||
<<features-stub-runner-publishing-stubs-as-jars>>, for example). After that, you can create a stub that uses WireMock in a
|
||||
number of different ways, including by using
|
||||
`@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this
|
||||
document.
|
||||
|
||||
[[features-rest-docs-contracts]]
|
||||
==== Generating Contracts with REST Docs
|
||||
|
||||
You can also generate Spring Cloud Contract DSL files and documentation with Spring REST
|
||||
Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts
|
||||
and the stubs.
|
||||
|
||||
Why would you want to use this feature? Some people in the community asked questions
|
||||
about a situation in which they would like to move to DSL-based contract definition,
|
||||
but they already have a lot of Spring MVC tests. Using this feature lets you generate
|
||||
the contract files that you can later modify and move to folders (defined in your
|
||||
configuration) so that the plugin finds them.
|
||||
|
||||
NOTE: You might wonder why this functionality is in the WireMock module. The functionality
|
||||
is there because it makes sense to generate both the contracts and the stubs.
|
||||
|
||||
Consider the following test:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet]
|
||||
----
|
||||
====
|
||||
|
||||
The preceding test creates the stub presented in the previous section, generating both
|
||||
the contract and a documentation file.
|
||||
|
||||
The contract is called `index.groovy` and might resemble the following example:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
import org.springframework.cloud.contract.spec.Contract
|
||||
|
||||
Contract.make {
|
||||
request {
|
||||
method 'POST'
|
||||
url '/foo'
|
||||
body('''
|
||||
{"foo": 23 }
|
||||
''')
|
||||
headers {
|
||||
header('''Accept''', '''application/json''')
|
||||
header('''Content-Type''', '''application/json''')
|
||||
}
|
||||
}
|
||||
response {
|
||||
status OK()
|
||||
body('''
|
||||
bar
|
||||
''')
|
||||
headers {
|
||||
header('''Content-Type''', '''application/json;charset=UTF-8''')
|
||||
header('''Content-Length''', '''3''')
|
||||
}
|
||||
testMatchers {
|
||||
jsonPath('$[?(@.foo >= 20)]', byType())
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The generated document (formatted in Asciidoc in this case) contains a formatted
|
||||
contract. The location of this file would be `index/dsl-contract.adoc`.
|
||||
1015
docs/src/main/asciidoc/_project-features-messaging.adoc
Normal file
1015
docs/src/main/asciidoc/_project-features-messaging.adoc
Normal file
File diff suppressed because it is too large
Load Diff
916
docs/src/main/asciidoc/_project-features-stubrunner.adoc
Normal file
916
docs/src/main/asciidoc/_project-features-stubrunner.adoc
Normal file
@@ -0,0 +1,916 @@
|
||||
[[features-stub-runner]]
|
||||
== Spring Cloud Contract Stub Runner
|
||||
|
||||
One of the issues that you might encounter while using Spring Cloud Contract Verifier is
|
||||
passing the generated WireMock JSON stubs from the server side to the client side (or to
|
||||
various clients). The same takes place in terms of client-side generation for messaging.
|
||||
|
||||
Copying the JSON files and setting the client side for messaging manually is out of the
|
||||
question. That is why we introduced Spring Cloud Contract Stub Runner. It can
|
||||
automatically download and run the stubs for you.
|
||||
|
||||
[[features-stub-runner-snapshot-versions]]
|
||||
=== Snapshot Versions
|
||||
|
||||
You can add the additional snapshot repository to your `build.gradle` file to use snapshot
|
||||
versions, which are automatically uploaded after every successful build, as follows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-publishing-stubs-as-jars]]
|
||||
=== Publishing Stubs as JARs
|
||||
|
||||
The easiest approach to publishing stubs as jars is to centralize the way stubs are kept.
|
||||
For example, you can keep them as jars in a Maven repository.
|
||||
|
||||
TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize
|
||||
it if you want to.
|
||||
|
||||
The following example shows how to publish stubs as jars:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<!-- 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 -->
|
||||
include::{samples_url}/producer_with_restdocs/pom.xml[tags=assembly,indent=0]
|
||||
|
||||
<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
|
||||
include::{samples_url}/producer_with_restdocs/src/assembly/stub.xml[indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-core]]
|
||||
=== Stub Runner Core
|
||||
|
||||
The stub runner core runs stubs for service collaborators. Treating stubs as contracts of
|
||||
services lets you use stub-runner as an implementation of
|
||||
https://martinfowler.com/articles/consumerDrivenContracts.html[Consumer-driven Contracts].
|
||||
|
||||
Stub Runner lets you automatically download the stubs of the provided dependencies (or
|
||||
pick those from the classpath), start WireMock servers for them, and feed them with proper
|
||||
stub definitions. For messaging, special stub routes are defined.
|
||||
|
||||
[[features-stub-runner-retrieving]]
|
||||
==== Retrieving stubs
|
||||
|
||||
You can pick from the following options of acquiring stubs:
|
||||
|
||||
- Aether-based solution that downloads JARs with stubs from Artifactory or Nexus
|
||||
- Classpath-scanning solution that searches the classpath with a pattern to retrieve stubs
|
||||
- Writing your own implementation of the `org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder` for full customization
|
||||
|
||||
The latter example is described in the <<advanced.adoc#customization-custom-stub-runner, Custom Stub Runner>> section.
|
||||
|
||||
[[features-stub-runner-downloading-stub]]
|
||||
===== Downloading Stubs
|
||||
|
||||
You can control the downloading of stubs with the `stubsMode` switch. It picks value from the
|
||||
`StubRunnerProperties.StubsMode` enumeration. You can use the following options:
|
||||
|
||||
- `StubRunnerProperties.StubsMode.CLASSPATH` (default value): Picks stubs from the classpath
|
||||
- `StubRunnerProperties.StubsMode.LOCAL`: Picks stubs from a local storage (for example, `.m2`)
|
||||
- `StubRunnerProperties.StubsMode.REMOTE`: Picks stubs from a remote location
|
||||
|
||||
The following example picks stubs from a local location:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-classpath-scanning]]
|
||||
===== Classpath scanning
|
||||
|
||||
If you set the `stubsMode` property to `StubRunnerProperties.StubsMode.CLASSPATH`
|
||||
(or set nothing since `CLASSPATH` is the default value), the classpath is scanned.
|
||||
Consider the following example:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids = {
|
||||
"com.example:beer-api-producer:+:stubs:8095",
|
||||
"com.example.foo:bar:1.0.0:superstubs:8096"
|
||||
})
|
||||
----
|
||||
====
|
||||
|
||||
You can add the dependencies to your classpath, as follows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<dependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>beer-api-producer-restdocs</artifactId>
|
||||
<classifier>stubs</classifier>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>*</groupId>
|
||||
<artifactId>*</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.example.thing1</groupId>
|
||||
<artifactId>thing2</artifactId>
|
||||
<classifier>superstubs</classifier>
|
||||
<version>1.0.0</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>*</groupId>
|
||||
<artifactId>*</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
|
||||
transitive = false
|
||||
}
|
||||
testCompile("com.example.thing1:thing2:1.0.0:superstubs") {
|
||||
transitive = false
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Then the specified locations on your classpath get scanned. For `com.example:beer-api-producer-restdocs`,
|
||||
the following locations are scanned:
|
||||
|
||||
- /META-INF/com.example/beer-api-producer-restdocs/**/*.*
|
||||
- /contracts/com.example/beer-api-producer-restdocs/**/*.*
|
||||
- /mappings/com.example/beer-api-producer-restdocs/**/*.*
|
||||
|
||||
For `com.example.thing1:thing2`, the following locations are scanned:
|
||||
|
||||
- /META-INF/com.example.thing1/thing2/**/*.*
|
||||
- /contracts/com.example.thing1/thing2/**/*.*
|
||||
- /mappings/com.example.thing1/thing2/**/*.*
|
||||
|
||||
TIP: You have to explicitly provide the group and artifact IDs when you package the
|
||||
producer stubs.
|
||||
|
||||
To achieve proper stub packaging, the producer would set up the contracts as follows:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
└── src
|
||||
└── test
|
||||
└── resources
|
||||
└── contracts
|
||||
└── com.example
|
||||
└── beer-api-producer-restdocs
|
||||
└── nested
|
||||
└── contract3.groovy
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
By using the https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/pom.xml[Maven `assembly` plugin] or
|
||||
https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/{samples_branch}/producer_with_restdocs/build.gradle[Gradle Jar] task, you have to create the following
|
||||
structure in your stubs jar:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
└── META-INF
|
||||
└── com.example
|
||||
└── beer-api-producer-restdocs
|
||||
└── 2.0.0
|
||||
├── contracts
|
||||
│ └── nested
|
||||
│ └── contract2.groovy
|
||||
└── mappings
|
||||
└── mapping.json
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
By maintaining this structure, the classpath gets scanned and you can profit from the messaging or
|
||||
HTTP stubs without the need to download artifacts.
|
||||
|
||||
[[features-stub-runner-configuring-http-server-stubs]]
|
||||
===== Configuring HTTP Server Stubs
|
||||
|
||||
Stub Runner has a notion of a `HttpServerStub` that abstracts the underlying
|
||||
concrete implementation of the HTTP server (for example, WireMock is one of the implementations).
|
||||
Sometimes, you need to perform some additional tuning (which is concrete for the given implementation) of the stub servers.
|
||||
To do that, Stub Runner gives you
|
||||
the `httpServerStubConfigurer` property that is available in the annotation and the
|
||||
JUnit rule and is accessible through system properties, where you can provide
|
||||
your implementation of the `org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer`
|
||||
interface. The implementations can alter
|
||||
the configuration files for the given HTTP server stub.
|
||||
|
||||
Spring Cloud Contract Stub Runner comes with an implementation that you
|
||||
can extend for WireMock:
|
||||
`org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer`.
|
||||
In the `configure` method,
|
||||
you can provide your own custom configuration for the given stub. The use
|
||||
case might be starting WireMock for the given artifact ID, on an HTTPS port. The following
|
||||
example shows how to do so:
|
||||
|
||||
.WireMockHttpServerStubConfigurer implementation
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer]
|
||||
----
|
||||
====
|
||||
|
||||
You can then reuse it with the `@AutoConfigureStubRunner` annotation, as follows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=annotation]
|
||||
----
|
||||
====
|
||||
|
||||
Whenever an HTTPS port is found, it takes precedence over the HTTP port.
|
||||
|
||||
[[features-stub-runner-running-stubs]]
|
||||
==== Running stubs
|
||||
|
||||
This section describes how to run stubs. It contains the following topics:
|
||||
|
||||
* <<features-stub-runner-http-stubs>>
|
||||
* <<features-stub-runner-viewing>>
|
||||
* <<features-stub-runner-messaging>>
|
||||
|
||||
[[features-stub-runner-http-stubs]]
|
||||
===== HTTP Stubs
|
||||
|
||||
Stubs are defined in JSON documents, whose syntax is defined in http://wiremock.org/stubbing.html[WireMock documentation]
|
||||
|
||||
The following example defines a stub in JSON:
|
||||
|
||||
====
|
||||
[source,javascript,indent=0]
|
||||
----
|
||||
{
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "/ping"
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"body": "pong",
|
||||
"headers": {
|
||||
"Content-Type": "text/plain"
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-viewing]]
|
||||
===== Viewing Registered Mappings
|
||||
|
||||
Every stubbed collaborator exposes a list of defined mappings under the `__/admin/` endpoint.
|
||||
|
||||
You can also use the `mappingsOutputFolder` property to dump the mappings to files.
|
||||
For the annotation-based approach, it would resembling the following example:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
|
||||
mappingsOutputFolder = "target/outputmappings/")
|
||||
----
|
||||
====
|
||||
|
||||
For the JUnit approach, it resembles the following example:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
|
||||
.repoRoot("https://some_url")
|
||||
.downloadStub("a.b.c", "loanIssuance")
|
||||
.downloadStub("a.b.c:fraudDetectionServer")
|
||||
.withMappingsOutputFolder("target/outputmappings")
|
||||
----
|
||||
====
|
||||
|
||||
Then, if you check out the `target/outputmappings` folder, you would see the following structure;
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
.
|
||||
├── fraudDetectionServer_13705
|
||||
└── loanIssuance_12255
|
||||
----
|
||||
====
|
||||
|
||||
That means that there were two stubs registered. `fraudDetectionServer` was registered at port `13705`
|
||||
and `loanIssuance` at port `12255`. If we take a look at one of the files, we would see (for WireMock)
|
||||
the mappings available for the given server:
|
||||
|
||||
====
|
||||
[source,json]
|
||||
----
|
||||
[{
|
||||
"id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
|
||||
"request" : {
|
||||
"url" : "/name",
|
||||
"method" : "GET"
|
||||
},
|
||||
"response" : {
|
||||
"status" : 200,
|
||||
"body" : "fraudDetectionServer"
|
||||
},
|
||||
"uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
|
||||
},
|
||||
...
|
||||
]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-messaging]]
|
||||
===== Messaging Stubs
|
||||
|
||||
Depending on the provided Stub Runner dependency and the DSL, the messaging routes are automatically set up.
|
||||
|
||||
[[features-stub-runner-junit]]
|
||||
=== Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
|
||||
|
||||
Stub Runner comes with a JUnit rule that lets you can download and run stubs for a given
|
||||
group and artifact ID, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=classrule]
|
||||
----
|
||||
====
|
||||
|
||||
A `StubRunnerExtension` is also available for JUnit 5. `StubRunnerRule` and
|
||||
`StubRunnerExtension` work in a very similar fashion. After the rule or extension is
|
||||
executed, Stub Runner connects to your Maven repository and, for the given list of
|
||||
dependencies, tries to:
|
||||
|
||||
- Download them
|
||||
- Cache them locally
|
||||
- Unzip them to a temporary folder
|
||||
- Start a WireMock server for each Maven dependency on a random port from the provided
|
||||
range of ports or the provided port
|
||||
- Feed the WireMock server with all JSON files that are valid WireMock definitions
|
||||
- Send messages (remember to pass an implementation of `MessageVerifier` interface)
|
||||
|
||||
Stub Runner uses the https://wiki.eclipse.org/Aether[Eclipse Aether] mechanism to download the Maven dependencies.
|
||||
Check their https://wiki.eclipse.org/Aether[docs] for more information.
|
||||
|
||||
Since the `StubRunnerRule` and `StubRunnerExtension` implement the `StubFinder` they let
|
||||
you find the started stubs, as the following example shows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubFinder.java[lines=16..-1]
|
||||
----
|
||||
====
|
||||
|
||||
The following examples provide more detail about using Stub Runner:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.spock
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleSpec.groovy[tags=classrule]
|
||||
----
|
||||
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.junit 4
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleJUnitTest.java[tags=test]
|
||||
----
|
||||
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.junit 5
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/java/org/springframework/cloud/contract/stubrunner/junit/StubRunnerJUnit5ExtensionTests.java[tags=extension]
|
||||
----
|
||||
====
|
||||
|
||||
See the <<features-stub-runner-common-properties-junit-spring>> for more information on
|
||||
how to apply global configuration of Stub Runner.
|
||||
|
||||
IMPORTANT: To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the
|
||||
`MessageVerifier` interface to the rule builder (for example, `rule.messageVerifier(new MyMessageVerifier())`).
|
||||
If you do not do this, then, whenever you try to send a message, an exception is thrown.
|
||||
|
||||
[[features-stub-runner-rule-maven-settings]]
|
||||
==== Maven Settings
|
||||
|
||||
The stub downloader honors Maven settings for a different local repository folder.
|
||||
Authentication details for repositories and profiles are currently not taken into account,
|
||||
so you need to specify it by using the properties mentioned above.
|
||||
|
||||
[[features-stub-runner-rule-fixed-ports]]
|
||||
==== Providing Fixed Ports
|
||||
|
||||
You can also run your stubs on fixed ports. You can do it in two different ways.
|
||||
One is to pass it in the properties, and the other is to use the fluent API of
|
||||
JUnit rule.
|
||||
|
||||
[[features-stub-runner-rule-fluent-api]]
|
||||
==== Fluent API
|
||||
|
||||
When using the `StubRunnerRule` or `StubRunnerExtension`, you can add a stub to download
|
||||
and then pass the port for the last downloaded stub. The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=classrule_with_port]
|
||||
----
|
||||
====
|
||||
|
||||
For the preceding example, the following test is valid:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/junit/StubRunnerRuleCustomPortJUnitTest.java[tags=test_with_port]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-rule-spring]]
|
||||
==== Stub Runner with Spring
|
||||
|
||||
Stub Runner with Spring sets up Spring configuration of the Stub Runner project.
|
||||
|
||||
By providing a list of stubs inside your configuration file, Stub Runner automatically downloads
|
||||
and registers in WireMock the selected stubs.
|
||||
|
||||
If you want to find the URL of your stubbed dependency, you can autowire the `StubFinder` interface and use
|
||||
its methods, as follows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=test]
|
||||
----
|
||||
====
|
||||
|
||||
Doing so depends on the following configuration file:
|
||||
|
||||
====
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/resources/application-test.yml[tags=test]
|
||||
----
|
||||
====
|
||||
|
||||
Instead of using the properties, you can also use the properties inside the `@AutoConfigureStubRunner`.
|
||||
The following example achieves the same result by setting values on the annotation:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=autoconfigure]
|
||||
----
|
||||
|
||||
Stub Runner Spring registers environment variables in the following manner
|
||||
for every registered WireMock server. The following example shows Stub Runner IDs for
|
||||
`com.example:thing1` and `com.example:thing2`:
|
||||
|
||||
- `stubrunner.runningstubs.thing1.port`
|
||||
- `stubrunner.runningstubs.com.example.thing1.port`
|
||||
- `stubrunner.runningstubs.thing2.port`
|
||||
- `stubrunner.runningstubs.com.example.thing2.port`
|
||||
|
||||
You can reference these values in your code.
|
||||
|
||||
You can also use the `@StubRunnerPort` annotation to inject the port of a running stub.
|
||||
The value of the annotation can be the `groupid:artifactid` or just the `artifactid`.
|
||||
The following example works shows Stub Runner IDs for
|
||||
`com.example:thing1` and `com.example:thing2`.
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@StubRunnerPort("thing1")
|
||||
int thing1Port;
|
||||
@StubRunnerPort("com.example:thing2")
|
||||
int thing2Port;
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-cloud]]
|
||||
=== Stub Runner Spring Cloud
|
||||
|
||||
Stub Runner can integrate with Spring Cloud.
|
||||
|
||||
For real life examples, see:
|
||||
|
||||
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer[The producer app sample]
|
||||
- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_with_discovery[The consumer app sample]
|
||||
|
||||
[[features-stub-runner-cloud-stubbing-discovery]]
|
||||
==== Stubbing Service Discovery
|
||||
|
||||
The most important feature of `Stub Runner Spring Cloud` is the fact that it stubs:
|
||||
|
||||
- `DiscoveryClient`
|
||||
- `Ribbon` `ServerList`
|
||||
|
||||
That means that, regardless of whether you use Zookeeper, Consul, Eureka, or anything
|
||||
else, you do not need that in your tests. We are starting WireMock instances of your
|
||||
dependencies and we are telling your application, whenever you use `Feign`, to load a
|
||||
balanced `RestTemplate` or `DiscoveryClient` directly, to call those stubbed servers
|
||||
instead of calling the real Service Discovery tool.
|
||||
|
||||
For example, the following test passes:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerSpringCloudAutoConfigurationSpec.groovy[tags=test]
|
||||
----
|
||||
====
|
||||
|
||||
Note that the preceding example requires the following configuration file:
|
||||
|
||||
====
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/resources/application.yml[tags=ids]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-cloud-stubbing-profiles]]
|
||||
===== Test Profiles and Service Discovery
|
||||
|
||||
In your integration tests, you typically do not want to call either a discovery service (such as Eureka)
|
||||
or Config Server. That is why you create an additional test configuration in which you want to disable
|
||||
these features.
|
||||
|
||||
Due to certain limitations of https://github.com/spring-cloud/spring-cloud-commons/issues/156[`spring-cloud-commons`],
|
||||
to achieve this, you have to disable these properties
|
||||
in a static block such as the following example (for Eureka):
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
//Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
|
||||
static {
|
||||
System.setProperty("eureka.client.enabled", "false");
|
||||
System.setProperty("spring.cloud.config.failFast", "false");
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-additional-config]]
|
||||
==== Additional Configuration
|
||||
|
||||
You can match the `artifactId` of the stub with the name of your application by using the `stubrunner.idsToServiceIds:` map.
|
||||
You can disable Stub Runner Ribbon support by setting `stubrunner.cloud.ribbon.enabled` to `false`
|
||||
You can disable Stub Runner support by setting `stubrunner.cloud.enabled` to `false`
|
||||
|
||||
TIP: By default, all service discovery is stubbed. This means that, regardless of whether you have
|
||||
an existing `DiscoveryClient`, its results are ignored. However, if you want to reuse it, you can set
|
||||
`stubrunner.cloud.delegate.enabled` to `true`, and then your existing `DiscoveryClient` results are
|
||||
merged with the stubbed ones.
|
||||
|
||||
The default Maven configuration used by Stub Runner can be tweaked either
|
||||
by setting the following system properties or by setting the corresponding environment variables:
|
||||
|
||||
- `maven.repo.local`: Path to the custom maven local repository location
|
||||
- `org.apache.maven.user-settings`: Path to custom maven user settings location
|
||||
- `org.apache.maven.global-settings`: Path to maven global settings location
|
||||
|
||||
[[features-stub-runner-boot]]
|
||||
=== Using the Stub Runner Boot Application
|
||||
|
||||
Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to
|
||||
trigger the messaging labels and to access WireMock servers.
|
||||
|
||||
One of the use cases is to run some smoke (end-to-end) tests on a deployed application.
|
||||
You can check out the https://github.com/spring-cloud/spring-cloud-pipelines[Spring Cloud Pipelines]
|
||||
project for more information.
|
||||
|
||||
[[features-stub-runner-boot-server]]
|
||||
===== Stub Runner Server
|
||||
|
||||
To use the Stub Runner Server, add the following dependency:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
compile "org.springframework.cloud:spring-cloud-starter-stub-runner"
|
||||
----
|
||||
====
|
||||
|
||||
Then annotate a class with `@EnableStubRunnerServer`, build a fat jar, and it is ready to work.
|
||||
|
||||
For the properties, see the <<features-stub-runner-rule-spring,Stub Runner Spring>> section.
|
||||
|
||||
[[features-stub-runner-boot-how-fat-jar]]
|
||||
===== Stub Runner Server Fat Jar
|
||||
|
||||
You can download a standalone JAR from Maven (for example, for version 2.0.1.RELEASE)
|
||||
by running the following commands:
|
||||
|
||||
====
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
|
||||
$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...
|
||||
----
|
||||
====
|
||||
|
||||
[[features-stub-runner-boot-how-cli]]
|
||||
===== Spring Cloud CLI
|
||||
|
||||
Starting from the `1.4.0.RELEASE` version of the https://cloud.spring.io/spring-cloud-cli[Spring Cloud CLI]
|
||||
project, you can start Stub Runner Boot by running `spring cloud stubrunner`.
|
||||
|
||||
In order to pass the configuration, you can create a `stubrunner.yml` file in the current working directory,
|
||||
in a subdirectory called `config`, or in `~/.spring-cloud`. The file could resemble the following
|
||||
example for running stubs installed locally:
|
||||
|
||||
|
||||
.stubrunner.yml
|
||||
====
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
stubrunner:
|
||||
stubsMode: LOCAL
|
||||
ids:
|
||||
- com.example:beer-api-producer:+:9876
|
||||
----
|
||||
====
|
||||
|
||||
Then you can call `spring cloud stubrunner` from your terminal window to start
|
||||
the Stub Runner server. It is available at port `8750`.
|
||||
|
||||
[[features-stub-runner-boot-endpoints]]
|
||||
==== Endpoints
|
||||
|
||||
Stub Runner Boot offers two endpoints:
|
||||
|
||||
* <<features-stub-runner-boot-endpoints-http>>
|
||||
* <<features-stub-runner-boot-endpoints-messaging>>
|
||||
|
||||
[[features-stub-runner-boot-endpoints-http]]
|
||||
===== HTTP
|
||||
|
||||
For HTTP, Stub Runner Boot makes the following endpoints available:
|
||||
|
||||
- GET `/stubs`: Returns a list of all running stubs in `ivy:integer` notation
|
||||
- GET `/stubs/{ivy}`: Returns a port for the given `ivy` notation (when calling the endpoint `ivy` can also be `artifactId` only)
|
||||
|
||||
[[features-stub-runner-boot-endpoints-messaging]]
|
||||
===== Messaging
|
||||
|
||||
For Messaging, Stub Runner Boot makes the following endpoints available:
|
||||
|
||||
- GET `/triggers`: Returns a list of all running labels in `ivy : [ label1, label2 ...]` notation
|
||||
- POST `/triggers/{label}`: Runs a trigger with `label`
|
||||
- POST `/triggers/{ivy}/{label}`: Runs a trigger with a `label` for the given `ivy` notation
|
||||
(when calling the endpoint, `ivy` can also be `artifactId` only)
|
||||
|
||||
[[features-stub-runner-boot-endpoints-example]]
|
||||
==== Example
|
||||
|
||||
The following example shows typical usage of Stub Runner Boot:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/server/StubRunnerBootSpec.groovy[tags=boot_usage]
|
||||
----
|
||||
|
||||
[[features-stub-runner-boot-service-discovery]]
|
||||
==== Stub Runner Boot with Service Discovery
|
||||
|
||||
One way to use Stub Runner Boot is to use it as a feed of stubs for "`smoke tests`". What does that mean?
|
||||
Assume that you do not want to deploy 50 microservices to a test environment in order
|
||||
to see whether your application works. You have already executed a suite of tests during the build process,
|
||||
but you would also like to ensure that the packaging of your application works. You can
|
||||
deploy your application to an environment, start it, and run a couple of tests on it to see whether
|
||||
it works. We can call those tests "`smoke tests`", because their purpose is to check only a handful
|
||||
of testing scenarios.
|
||||
|
||||
The problem with this approach is thatm if you use microservices, you most likely also
|
||||
use a service discovery tool. Stub Runner Boot lets you solve this issue by starting the
|
||||
required stubs and registering them in a service discovery tool. Consider the following example of
|
||||
such a setup with Eureka (assume that Eureka is already running):
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka]
|
||||
----
|
||||
====
|
||||
|
||||
We want to start a Stub Runner Boot server (`@EnableStubRunnerServer`), enable the Eureka client (`@EnableEurekaClient`),
|
||||
and have the stub runner feature turned on (`@AutoConfigureStubRunner`).
|
||||
|
||||
Now assume that we want to start this application so that the stubs get automatically registered.
|
||||
We can do so by running the application with `java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar`, where
|
||||
`${SYSTEM_PROPS}` contains the following list of properties:
|
||||
|
||||
====
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/serverexamples/StubRunnerBootEurekaExample.java[tags=stubrunnereureka_args]
|
||||
----
|
||||
====
|
||||
|
||||
That way, your deployed application can send requests to started WireMock servers through service
|
||||
discovery. Most likely, points 1 through 3 could be set by default in `application.yml`, because they are not
|
||||
likely to change. That way, you can provide only the list of stubs to download whenever you start
|
||||
the Stub Runner Boot.
|
||||
|
||||
[[features-stub-runner-stubs-per-consumer]]
|
||||
=== Consumer-Driven Contracts: Stubs Per Consumer
|
||||
|
||||
There are cases in which two consumers of the same endpoint want to have two different responses.
|
||||
|
||||
TIP: This approach also lets you immediately know which consumer uses which part of your API.
|
||||
You can remove part of a response that your API produces and see which of your autogenerated tests
|
||||
fails. If none fails, you can safely delete that part of the response, because nobody uses it.
|
||||
|
||||
Consider the following example of a contract defined for the producer called `producer`,
|
||||
which has two consumers (`foo-consumer` and `bar-consumer`):
|
||||
|
||||
====
|
||||
.Consumer `foo-service`
|
||||
[source,groovy]
|
||||
----
|
||||
request {
|
||||
url '/foo'
|
||||
method GET()
|
||||
}
|
||||
response {
|
||||
status OK()
|
||||
body(
|
||||
foo: "foo"
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
.Consumer `bar-service`
|
||||
[source,groovy]
|
||||
----
|
||||
request {
|
||||
url '/bar'
|
||||
method GET()
|
||||
}
|
||||
response {
|
||||
status OK()
|
||||
body(
|
||||
bar: "bar"
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
You cannot produce two different responses for the same request. That is why you can properly package the
|
||||
contracts and then profit from the `stubsPerConsumer` feature.
|
||||
|
||||
On the producer side, the consumers can have a folder that contains contracts related only to them.
|
||||
By setting the `stubrunner.stubs-per-consumer` flag to `true`, we no longer register all stubs but only those that
|
||||
correspond to the consumer application's name. In other words, we scan the path of every stub and,
|
||||
if it contains a subfolder with name of the consumer in the path, only then is it registered.
|
||||
|
||||
On the `foo` producer side the contracts would look like this
|
||||
|
||||
[source,bash]
|
||||
----
|
||||
.
|
||||
└── contracts
|
||||
├── bar-consumer
|
||||
│ ├── bookReturnedForBar.groovy
|
||||
│ └── shouldCallBar.groovy
|
||||
└── foo-consumer
|
||||
├── bookReturnedForFoo.groovy
|
||||
└── shouldCallFoo.groovy
|
||||
----
|
||||
|
||||
The `bar-consumer` consumer can either set the `spring.application.name` or the `stubrunner.consumer-name` to `bar-consumer`
|
||||
Alternatively, you can set the test as follows:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerSpec.groovy[tags=test]
|
||||
...
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Then only the stubs registered under a path that contains `bar-consumer` in its name (that is, those from the
|
||||
`src/test/resources/contracts/bar-consumer/some/contracts/...` folder) are allowed to be referenced.
|
||||
|
||||
You can also set the consumer name explicitly, as follows:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/cloud/StubRunnerStubsPerConsumerWithConsumerNameSpec.groovy[tags=test]
|
||||
...
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Then only the stubs registered under a path that contains the `foo-consumer` in its name (that is, those from the
|
||||
`src/test/resources/contracts/foo-consumer/some/contracts/...` folder) are allowed to be referenced.
|
||||
|
||||
See https://github.com/spring-cloud/spring-cloud-contract/issues/224[issue 224] for more
|
||||
information about the reasons behind this change.
|
||||
|
||||
[[features-stub-runner-common]]
|
||||
=== Common Properties
|
||||
|
||||
This section briefly describes common properties, including:
|
||||
|
||||
* <<features-stub-runner-common-properties-junit-spring>>
|
||||
* <<features-stub-runner-stub-runner-stub-ids>>
|
||||
|
||||
[[features-stub-runner-common-properties-junit-spring]]
|
||||
==== Common Properties for JUnit and Spring
|
||||
|
||||
You can set repetitive properties by using system properties or Spring configuration
|
||||
properties. The following table shows their names with their default values:
|
||||
|
||||
[frame="topbot",options="header"]
|
||||
|===============
|
||||
| Property name | Default value | Description
|
||||
|stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs.
|
||||
|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs.
|
||||
|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local Maven repo.
|
||||
|stubrunner.classifier|stubs| Default classifier for the stub artifacts.
|
||||
|stubrunner.stubsMode|CLASSPATH| The way you want to fetch and register the stubs
|
||||
|stubrunner.ids|| Array of Ivy notation stubs to download.
|
||||
|stubrunner.username|| Optional username to access the tool that stores the JARs with
|
||||
stubs.
|
||||
|stubrunner.password|| Optional password to access the tool that stores the JARs with
|
||||
stubs.
|
||||
|stubrunner.stubsPerConsumer|`false`| Set to `true` if you want to use different stubs for
|
||||
each consumer instead of registering all stubs for every consumer.
|
||||
|stubrunner.consumerName|| If you want to use a stub for each consumer and want to
|
||||
override the consumer name, change this value.
|
||||
|===============
|
||||
|
||||
[[features-stub-runner-stub-runner-stub-ids]]
|
||||
==== Stub Runner Stubs IDs
|
||||
|
||||
You can set the stubs to download in the `stubrunner.ids` system property. They
|
||||
use the following pattern:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
groupId:artifactId:version:classifier:port
|
||||
----
|
||||
====
|
||||
|
||||
Note that `version`, `classifier`, and `port` are optional.
|
||||
|
||||
* If you do not provide the `port`, a random one is picked.
|
||||
* If you do not provide the `classifier`, the default is used. (Note that you can
|
||||
pass an empty classifier this way: `groupId:artifactId:version:`).
|
||||
* If you do not provide the `version`, then `+` is passed, and the latest one is
|
||||
downloaded.
|
||||
|
||||
`port` means the port of the WireMock server.
|
||||
|
||||
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].
|
||||
192
docs/src/main/asciidoc/_project-features-wiremock.adoc
Normal file
192
docs/src/main/asciidoc/_project-features-wiremock.adoc
Normal file
@@ -0,0 +1,192 @@
|
||||
[[features-wiremock]]
|
||||
== Spring Cloud Contract WireMock
|
||||
include::_attributes.adoc[]
|
||||
|
||||
The Spring Cloud Contract WireMock modules let you use https://github.com/tomakehurst/wiremock[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 (which is
|
||||
the default with `spring-boot-starter-web`), you can add
|
||||
`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock`
|
||||
to use Wiremock in your tests. Wiremock runs as a stub server, and you
|
||||
can register stub behavior by using a Java API or by using static JSON declarations as part of
|
||||
your test. The following code shows an example:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1]
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2]
|
||||
----
|
||||
====
|
||||
|
||||
To start the stub server on a different port, use (for example),
|
||||
`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub
|
||||
server port can be bound in the test application context with the "wiremock.server.port"
|
||||
property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to
|
||||
your test application context, where it is cached between methods and classes
|
||||
having the same context. The same is true for Spring integration tests. Also, you can
|
||||
inject a bean of type `WireMockServer` into your test.
|
||||
|
||||
[[features-wiremock-registering-stubs]]
|
||||
=== Registering Stubs Automatically
|
||||
|
||||
If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file
|
||||
system or classpath (by default, from `file:src/test/resources/mappings`). You can
|
||||
customize the locations byusing the `stubs` attribute in the annotation, which can be an
|
||||
Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is
|
||||
appended. The following code shows an example:
|
||||
|
||||
====
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureWireMock(stubs="classpath:/stubs")
|
||||
public class WiremockImportApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private Service service;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
|
||||
If you use Spring Cloud Contract's default stub jars, your
|
||||
stubs are stored in the `/META-INF/group-id/artifact-id/versions/mappings/` folder.
|
||||
If you want to register all stubs from that location, from all embedded JARs, you can use
|
||||
the following syntax:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs]
|
||||
----
|
||||
====
|
||||
|
||||
[[features-wiremock-using-files]]
|
||||
=== Using Files to Specify the Stub Bodies
|
||||
|
||||
WireMock can read response bodies from files on the classpath or the file system. In the
|
||||
case of the file system, you can see in the JSON DSL that the response has a `bodyFileName` instead of a
|
||||
(literal) `body`. The files are resolved relative to a root directory (by default,
|
||||
`src/test/resources/\__files`). To customize this location, you can set the `files`
|
||||
attribute in the `@AutoConfigureWireMock` annotation to the location of the parent
|
||||
directory (in other words, `__files` is a subdirectory). You can use Spring resource
|
||||
notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not
|
||||
supported. A list of values can be given -- in which case, WireMock resolves the first file
|
||||
that exists when it needs to find a response body.
|
||||
|
||||
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.
|
||||
|
||||
[[features-wiremock-junit-rule]]
|
||||
=== Alternative: Using JUnit Rules
|
||||
|
||||
For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop
|
||||
the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options`
|
||||
instance, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1]
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2]
|
||||
----
|
||||
====
|
||||
|
||||
The `@ClassRule` means that the server shuts down after all the methods in this class
|
||||
have been run.
|
||||
|
||||
[[features-wiremock-relaxed-ssl]]
|
||||
=== Relaxed SSL Validation for Rest Template
|
||||
|
||||
WireMock lets you stub a "`secure`" server with an `https` URL protocol. If your
|
||||
application wants to contact that stub server in an integration test, it will find that
|
||||
the SSL certificates are not valid (the usual problem with self-installed certificates).
|
||||
The best option is often to re-configure the client to use `http`. If that is not an
|
||||
option, you can ask Spring to configure an HTTP client that ignores SSL validation errors
|
||||
(do so only for tests, of course).
|
||||
|
||||
To make this work with minimum fuss, you need to use the Spring Boot
|
||||
`RestTemplateBuilder` in your application, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Bean
|
||||
public RestTemplate restTemplate(RestTemplateBuilder builder) {
|
||||
return builder.build();
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
You need `RestTemplateBuilder` because the builder is passed through callbacks to
|
||||
initialize it, so the SSL validation can be set up in the client at that point. This
|
||||
happens automatically in your test if you use the `@AutoConfigureWireMock`
|
||||
annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the
|
||||
`@AutoConfigureHttpClient` annotation as well, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest("app.baseUrl=https://localhost:6443")
|
||||
@AutoConfigureHttpClient
|
||||
public class WiremockHttpsServerApplicationTests {
|
||||
|
||||
@ClassRule
|
||||
public static WireMockClassRule wiremock = new WireMockClassRule(
|
||||
WireMockSpring.options().httpsPort(6443));
|
||||
...
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use `spring-boot-starter-test`, you have the Apache HTTP client on the
|
||||
classpath, and it is selected by the `RestTemplateBuilder` and configured to ignore SSL
|
||||
errors. If you use the default `java.net` client, you do not need the annotation (but it
|
||||
does no harm). There is currently no support for other clients, but it may be added
|
||||
in future releases.
|
||||
|
||||
To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled`
|
||||
property to `false`.
|
||||
|
||||
[[features-wiremock-spring-mvc-mocks]]
|
||||
=== WireMock and Spring MVC Mocks
|
||||
|
||||
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
|
||||
a Spring `MockRestServiceServer`. The following code shows an example:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test]
|
||||
----
|
||||
====
|
||||
|
||||
The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub
|
||||
path resource pattern as an argument. In the preceding example, the stub defined at
|
||||
`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to
|
||||
visit `https://example.org/`, it gets the responses as being declared at that URL. More
|
||||
than one stub pattern can be specified, and each one can be a directory (for a recursive
|
||||
list of all `.json`), a fixed filename (as in the preceding example), or an Ant-style
|
||||
pattern. The JSON format is the normal WireMock format, which you can read about at the
|
||||
https://wiremock.org/docs/stubbing/[WireMock website].
|
||||
|
||||
Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as
|
||||
Spring Boot embedded servers, and Wiremock itself has "`native`" support for a particular
|
||||
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).
|
||||
413
docs/src/main/asciidoc/advanced.adoc
Normal file
413
docs/src/main/asciidoc/advanced.adoc
Normal file
@@ -0,0 +1,413 @@
|
||||
[[contract-customization]]
|
||||
= Spring Cloud Contract customization
|
||||
include::_attributes.adoc[]
|
||||
|
||||
In this section, we describe how to customize various parts of Spring Cloud Contract.
|
||||
|
||||
[[customization-customization]]
|
||||
== DSL Customization
|
||||
|
||||
IMPORTANT: This section is valid only for the Groovy DSL
|
||||
|
||||
You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in
|
||||
the remainder of this section.
|
||||
|
||||
[[customization-extending]]
|
||||
=== Extending the DSL
|
||||
|
||||
You can provide your own functions to the DSL. The key requirement for this feature is to
|
||||
maintain the static compatibility. Later in this document, you can see examples of:
|
||||
|
||||
* Creating a JAR with reusable classes.
|
||||
* Referencing of these classes in the DSLs.
|
||||
|
||||
You can find the full example
|
||||
https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here].
|
||||
|
||||
[[customization-extending-common-jar]]
|
||||
=== Common JAR
|
||||
|
||||
The following examples show three classes that can be reused in the DSLs.
|
||||
|
||||
`PatternUtils` contains functions used by both the consumer and the producer.
|
||||
The following listing shows the `PatternUtils` class:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
include::{samples_url}/common/src/main/java/com/example/PatternUtils.java[]
|
||||
----
|
||||
====
|
||||
|
||||
`ConsumerUtils` contains functions used by the consumer.
|
||||
The following listing shows the `ConsumerUtils` class:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[]
|
||||
----
|
||||
====
|
||||
|
||||
`ProducerUtils` contains functions used by the producer.
|
||||
The following listing shows the `ProducerUtils` class:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[]
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-test-dep]]
|
||||
=== Adding a Test Dependency in the Project's Dependencies
|
||||
|
||||
To add a test dependency in the project's dependencies, you must first add the common jar
|
||||
dependency as a test dependency. Because your contracts files
|
||||
are available on the test resources path, the common jar classes automatically become
|
||||
visible in your Groovy files. The following examples show how to test the dependency:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-plugin-dep]]
|
||||
=== Adding a Test Dependency in the Plugin's Dependencies
|
||||
|
||||
Now, you must add the dependency for the plugin to reuse at runtime, as the
|
||||
following example shows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
include::{samples_url}/producer/pom.xml[tags=test_dep_in_plugin,indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-referencing]]
|
||||
=== Referencing Classes in DSLs
|
||||
|
||||
You can now reference your classes in your DSL, as the following example shows:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
IMPORTANT: You can set the Spring Cloud Contract plugin up by setting `convertToYaml` to
|
||||
`true`. That way, you do NOT have to add the dependency with the extended functionality
|
||||
to the consumer side, since the consumer side uses YAML contracts instead of Groovy contracts.
|
||||
|
||||
[[customization-wiremock]]
|
||||
== WireMock Customization
|
||||
|
||||
In this section, we show how to customize the way you work with https://wiremock.org[WireMock].
|
||||
|
||||
[[customization-wiremock-extension]]
|
||||
=== Registering Your Own WireMock Extension
|
||||
|
||||
WireMock lets you register custom extensions. By default, Spring Cloud Contract registers
|
||||
the transformer, which lets you reference a request from a response. If you want to
|
||||
provide your own extensions, you can register an implementation of the
|
||||
`org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions` interface.
|
||||
Since we use the `spring.factories` extension approach, you can create an entry in
|
||||
`META-INF/spring.factories` file similar to the following:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{stubrunner_core_path}/src/test/resources/META-INF/spring.factories[indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows a custom extension:
|
||||
|
||||
.TestWireMockExtensions.groovy
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/wiremock/TestWireMockExtensions.groovy[indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
IMPORTANT: Remember to override the `applyGlobally()` method and set it to `false` if you
|
||||
want the transformation to be applied only for a mapping that explicitly requires it.
|
||||
|
||||
[[customization-wiremock-configuration]]
|
||||
=== Customization of WireMock Configuration
|
||||
|
||||
You can register a bean of type `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer`
|
||||
to customize the WireMock configuration (for example, to add custom transformers).
|
||||
The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1]
|
||||
// perform your customization here
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2]
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-pluggable-architecture]]
|
||||
== Using the Pluggable Architecture
|
||||
|
||||
You may encounter cases where your contracts have been defined in other formats,
|
||||
such as YAML, RAML, or PACT. In those cases, you still want to benefit from the automatic
|
||||
generation of tests and stubs. You can add your own implementation for generating both
|
||||
tests and stubs. Also, you can customize the way tests are generated (for example, you
|
||||
can generate tests for other languages) and the way stubs are generated (for example, you
|
||||
can generate stubs for other HTTP server implementations).
|
||||
|
||||
[[customization-custom-contract-converter]]
|
||||
=== Custom Contract Converter
|
||||
|
||||
The `ContractConverter` interface lets you register your own implementation of a contract
|
||||
structure converter. The following code listing shows the `ContractConverter` interface:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
include::{contract_spec_path}/src/main/java/org/springframework/cloud/contract/spec/ContractConverter.java[indent=0,lines=17..-1]
|
||||
----
|
||||
====
|
||||
|
||||
Your implementation must define the condition on which it should start the
|
||||
conversion. Also, you must define how to perform that conversion in both directions.
|
||||
|
||||
IMPORTANT: Once you create your implementation, you must create a
|
||||
`/META-INF/spring.factories` file in which you provide the fully qualified name of your
|
||||
implementation.
|
||||
|
||||
The following example shows a typical `spring.factories` file:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
org.springframework.cloud.contract.spec.ContractConverter=\
|
||||
org.springframework.cloud.contract.verifier.converter.YamlContractConverter
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-custom-test-generator]]
|
||||
=== Using the Custom Test Generator
|
||||
|
||||
If you want to generate tests for languages other than Java or you are not happy with the
|
||||
way the verifier builds Java tests, you can register your own implementation.
|
||||
|
||||
The `SingleTestGenerator` interface lets you register your own implementation. The
|
||||
following code listing shows the `SingleTestGenerator` interface:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.java[indent=0,lines=17..-1]
|
||||
----
|
||||
====
|
||||
|
||||
Again, you must provide a `spring.factories` file, such as the one shown in the following
|
||||
example:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
|
||||
com.example.MyGenerator
|
||||
----
|
||||
====
|
||||
|
||||
[[customization-custom-stub-generator]]
|
||||
=== Using the Custom Stub Generator
|
||||
|
||||
If you want to generate stubs for stub servers other than WireMock, you can plug in your
|
||||
own implementation of the `StubGenerator` interface. The following code listing shows the
|
||||
`StubGenerator` interface:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.java[indent=0,lines=16..-1]
|
||||
----
|
||||
====
|
||||
|
||||
Again, you must provide a `spring.factories` file, such as the one shown in the following
|
||||
example:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
The default implementation is the WireMock stub generation.
|
||||
|
||||
TIP: You can provide multiple stub generator implementations. For example, from a single
|
||||
DSL, you can produce both WireMock stubs and Pact files.
|
||||
|
||||
[[customization-custom-stub-runner]]
|
||||
=== Using the Custom Stub Runner
|
||||
|
||||
If you decide to use a custom stub generation, you also need a custom way of running
|
||||
stubs with your different stub provider.
|
||||
|
||||
Assume that you use https://github.com/dreamhead/moco[Moco] to build your stubs and that
|
||||
you have written a stub generator and placed your stubs in a JAR file.
|
||||
|
||||
In order for Stub Runner to know how to run your stubs, you have to define a custom
|
||||
HTTP Stub server implementation, which might resemble the following example:
|
||||
|
||||
====
|
||||
[source,groovy]
|
||||
----
|
||||
include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1]
|
||||
----
|
||||
====
|
||||
|
||||
Then you can register it in your `spring.factories` file, as the following
|
||||
example shows:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
org.springframework.cloud.contract.stubrunner.HttpServerStub=\
|
||||
org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub
|
||||
----
|
||||
====
|
||||
|
||||
Now you can run stubs with Moco.
|
||||
|
||||
IMPORTANT: If you do not provide any implementation, the default (WireMock)
|
||||
implementation is used. If you provide more than one, the first one on the list is used.
|
||||
|
||||
[[customization-custom-stub-downloader]]
|
||||
=== Using the Custom Stub Downloader
|
||||
|
||||
You can customize the way your stubs are downloaded by creating an implementation of the
|
||||
`StubDownloaderBuilder` interface, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
package com.example;
|
||||
|
||||
class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
|
||||
|
||||
@Override
|
||||
public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
|
||||
return new StubDownloader() {
|
||||
@Override
|
||||
public Map.Entry<StubConfiguration, File> downloadAndUnpackStubJar(
|
||||
StubConfiguration config) {
|
||||
File unpackedStubs = retrieveStubs();
|
||||
return new AbstractMap.SimpleEntry<>(
|
||||
new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
|
||||
config.getClassifier()), unpackedStubs);
|
||||
}
|
||||
|
||||
File retrieveStubs() {
|
||||
// here goes your custom logic to provide a folder where all the stubs reside
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Then you can register it in your `spring.factories` file, as the following
|
||||
example shows:
|
||||
|
||||
====
|
||||
[source]
|
||||
----
|
||||
# Example of a custom Stub Downloader Provider
|
||||
org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
|
||||
com.example.CustomStubDownloaderBuilder
|
||||
----
|
||||
====
|
||||
|
||||
Now you can pick a folder with the source of your stubs.
|
||||
|
||||
IMPORTANT: If you do not provide any implementation, the default (scanning the classpath) is used.
|
||||
If you provide the `stubsMode = StubRunnerProperties.StubsMode.LOCAL` or
|
||||
`stubsMode = StubRunnerProperties.StubsMode.REMOTE`, the Aether implementation is used
|
||||
If you provide more than one, the first one on the list is used.
|
||||
|
||||
[[scm-stub-downloader]]
|
||||
=== Using the SCM Stub Downloader
|
||||
|
||||
Whenever the `repositoryRoot` starts with a SCM protocol
|
||||
(currently, we support only `git://`), the stub downloader tries
|
||||
to clone the repository and use it as a source of contracts
|
||||
to generate tests or stubs.
|
||||
|
||||
Through environment variables, system properties, or properties set
|
||||
inside the plugin or the contracts repository configuration, you can
|
||||
tweak the downloader's behavior. The following table describes the available
|
||||
properties:
|
||||
|
||||
.SCM Stub Downloader properties
|
||||
|====
|
||||
|Type of a property |Name of the property | Description
|
||||
|
|
||||
* `git.branch` (plugin prop)
|
||||
|
||||
* `stubrunner.properties.git.branch` (system prop)
|
||||
|
||||
* `STUBRUNNER_PROPERTIES_GIT_BRANCH` (env prop)
|
||||
|master
|
||||
|Which branch to checkout
|
||||
|
||||
|
|
||||
* `git.username` (plugin prop)
|
||||
|
||||
* `stubrunner.properties.git.username` (system prop)
|
||||
|
||||
* `STUBRUNNER_PROPERTIES_GIT_USERNAME` (env prop)
|
||||
|
|
||||
|Git clone username
|
||||
|
||||
|
|
||||
* `git.password` (plugin prop)
|
||||
|
||||
* `stubrunner.properties.git.password` (system prop)
|
||||
|
||||
* `STUBRUNNER_PROPERTIES_GIT_PASSWORD` (env prop)
|
||||
|
|
||||
|Git clone password
|
||||
|
||||
|
|
||||
* `git.no-of-attempts` (plugin prop)
|
||||
|
||||
* `stubrunner.properties.git.no-of-attempts` (system prop)
|
||||
|
||||
* `STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS` (env prop)
|
||||
|10
|
||||
|Number of attempts to push the commits to `origin`
|
||||
|
||||
|
|
||||
* `git.wait-between-attempts` (Plugin prop)
|
||||
|
||||
* `stubrunner.properties.git.wait-between-attempts` (system prop)
|
||||
|
||||
* `STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS` (env prop)
|
||||
|1000
|
||||
|Number of milliseconds to wait between attempts to push the commits to `origin`
|
||||
|====
|
||||
@@ -1,101 +0,0 @@
|
||||
== How to build it
|
||||
|
||||
IMPORTANT: You need to have all the necessary Groovy plugins
|
||||
installed for your IDE to properly resolve the sources. For example in
|
||||
Intellij IDEA having both Eclipse Groovy Compiler Plugin & GMavenPlus Intellij Plugin
|
||||
results in properly imported project.
|
||||
|
||||
IMPORTANT: Spring Cloud Contract builds Docker images. Remember to
|
||||
have Docker installed.
|
||||
|
||||
IMPORTANT: If you want to run the build in offline mode, you have to have Maven 3.5.2+ installed.
|
||||
|
||||
=== Project structure
|
||||
|
||||
Here you can find the Spring Cloud Contract folder structure
|
||||
|
||||
```
|
||||
├── config
|
||||
├── docker
|
||||
├── samples
|
||||
├── scripts
|
||||
├── specs
|
||||
├── spring-cloud-contract-dependencies
|
||||
├── spring-cloud-contract-shade
|
||||
├── spring-cloud-contract-starters
|
||||
├── spring-cloud-contract-stub-runner
|
||||
├── spring-cloud-contract-stub-runner-boot
|
||||
├── spring-cloud-contract-tools
|
||||
├── spring-cloud-contract-verifier
|
||||
├── spring-cloud-contract-wiremock
|
||||
└── tests
|
||||
```
|
||||
|
||||
- `config` - folder contains setup for Spring Cloud Release Tools automated release process
|
||||
- `docker` - folder contains docker images
|
||||
- `samples` - folder contains test samples together with standalone ones used also to build documentation
|
||||
- `scripts` - contains scripts to build and test `Spring Cloud Contract` with Maven, Gradle and standalone projects
|
||||
- `specs` - contains specifications for the Contract DSL.
|
||||
- `spring-cloud-contract-dependencies` - contains Spring Cloud Contract BOM
|
||||
- `spring-cloud-contract-shade` - shaded dependencies used by the plugins
|
||||
- `spring-cloud-contract-starters` - contains Spring Cloud Contract Starters
|
||||
- `spring-cloud-contract-spec` - contains specification modules (contains concept of a Contract)
|
||||
- `spring-cloud-contract-stub-runner` - contains Stub Runner related modules
|
||||
- `spring-cloud-contract-stub-runner-boot` - contains Stub Runner Boot app
|
||||
- `spring-cloud-contract-tools` - Gradle and Maven plugin for `Spring Cloud Contract Verifier`
|
||||
- `spring-cloud-contract-verifier` - core of the `Spring Cloud Contract Verifier` functionality
|
||||
- `spring-cloud-contract-wiremock` - all WireMock related functionality
|
||||
- `tests` - integration tests for different messaging technologies
|
||||
|
||||
=== Commands
|
||||
|
||||
To build the core functionality together with Maven Plugin you can run
|
||||
|
||||
```
|
||||
./mvnw clean install -P integration
|
||||
```
|
||||
|
||||
Calling that function will build core, Maven plugin, Gradle plugin and run end to end tests on the
|
||||
standalone samples in proper order (both for Maven and Gradle).
|
||||
|
||||
To build the Gradle Plugin only
|
||||
|
||||
```
|
||||
cd spring-cloud-contract-tools/spring-cloud-contract-gradle-plugin
|
||||
./gradlew clean build
|
||||
```
|
||||
|
||||
=== Helpful scripts
|
||||
|
||||
We're providing a couple of helpful scripts to build the project.
|
||||
|
||||
To build the project in parallel (by default uses 4 cores but you can change it)
|
||||
|
||||
```
|
||||
./scripts/parallelBuild.sh
|
||||
```
|
||||
|
||||
and with 8 cores
|
||||
|
||||
```
|
||||
CORES=8 ./scripts/parallelBuild.sh
|
||||
```
|
||||
|
||||
To build the project without any integration tests (by default uses 1 core)
|
||||
|
||||
```
|
||||
./scripts/noIntegration.sh
|
||||
```
|
||||
|
||||
and with 8 cores
|
||||
|
||||
```
|
||||
CORES=8 ./scripts/noIntegration.sh
|
||||
```
|
||||
|
||||
To generate the documentation (both the root one and the maven plugin one)
|
||||
|
||||
```
|
||||
./scripts/generateDocs.sh
|
||||
```
|
||||
|
||||
275
docs/src/main/asciidoc/docker-project.adoc
Normal file
275
docs/src/main/asciidoc/docker-project.adoc
Normal file
@@ -0,0 +1,275 @@
|
||||
[[docker]]
|
||||
= Docker Project
|
||||
include::_attributes.adoc[]
|
||||
|
||||
In this section, we publish a `springcloud/spring-cloud-contract` Docker image
|
||||
that contains a project that generates tests and runs them in `EXPLICIT` mode
|
||||
against a running application.
|
||||
|
||||
TIP: The `EXPLICIT` mode means that the tests generated from contracts send
|
||||
real requests and not the mocked ones.
|
||||
|
||||
We also publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
|
||||
that starts the standalone version of Stub Runner.
|
||||
|
||||
[[docker-intro]]
|
||||
== A Short Introduction to Maven, JARs and Binary storage
|
||||
|
||||
Since non-JVM projects can use the Docker image, it is good to
|
||||
explain the basic terms behind Spring Cloud Contract packaging defaults.
|
||||
|
||||
Parts of the following definitions were taken from the https://maven.apache.org/glossary.html[Maven Glossary]:
|
||||
|
||||
- `Project`: Maven thinks in terms of projects. Projects
|
||||
are all you build. Those projects follow a well defined
|
||||
“Project Object Model”. Projects can depend on other projects,
|
||||
in which case the latter are called “dependencies”. A project may
|
||||
consistent of several subprojects. However, these subprojects are still
|
||||
treated equally as projects.
|
||||
- `Artifact`: An artifact is something that is either produced or used
|
||||
by a project. Examples of artifacts produced by Maven for a project
|
||||
include JAR files and source and binary distributions. Each artifact
|
||||
is uniquely identified by a group ID and an artifact ID that is
|
||||
unique within a group.
|
||||
- `JAR`: JAR stands for Java ARchive. Its format is based on
|
||||
the ZIP file format. Spring Cloud Contract packages the contracts and generated
|
||||
stubs in a JAR file.
|
||||
- `GroupId`: A group ID is a universally unique identifier for a project.
|
||||
While this is often just the project name (for example, `commons-collections`),
|
||||
it is helpful to use a fully-qualified package name to distinguish it
|
||||
from other projects with a similar name (for example, `org.apache.maven`).
|
||||
Typically, when published to the Artifact Manager, the `GroupId` gets
|
||||
slash separated and forms part of the URL. For example, for a group ID of `com.example`
|
||||
and an artifact ID of `application`, the result would be `/com/example/application/`.
|
||||
- `Classifier`: The Maven dependency notation looks as follows:
|
||||
`groupId:artifactId:version:classifier`. The classifier is an additional suffix
|
||||
passed to the dependency -- for example, `stubs` or `sources`. The same dependency
|
||||
(for example, `com.example:application`) can produce multiple artifacts that
|
||||
differ from each other with the classifier.
|
||||
- `Artifact manager`: When you generate binaries, sources, or packages, you would
|
||||
like them to be available for others to download, reference, or reuse. In the case
|
||||
of the JVM world, those artifacts are generally JARs. For Ruby, those artifacts are gems.
|
||||
For Docker, those artifacts are Docker images. You can store those artifacts
|
||||
in a manager. Examples of such managers include https://jfrog.com/artifactory/[Artifactory]
|
||||
or https://www.sonatype.org/nexus/[Nexus].
|
||||
|
||||
[[docker-how-it-works]]
|
||||
== Generating Tests on the Producer Side
|
||||
|
||||
The image searches for contracts under the `/contracts` folder.
|
||||
The output from running the tests is available in the
|
||||
`/spring-cloud-contract/build` folder (useful for debugging
|
||||
purposes).
|
||||
|
||||
You can mount your contracts and pass the environment variables.
|
||||
The image then:
|
||||
|
||||
- Generates the contract tests
|
||||
- Runs the tests against the provided URL
|
||||
- Generates the https://github.com/tomakehurst/wiremock[WireMock] stubs
|
||||
- Publishes the stubs to a Artifact Manager (optional - turned on by default)
|
||||
|
||||
[[docker-env-vars]]
|
||||
=== Environment Variables
|
||||
|
||||
The Docker image requires some environment variables to point to
|
||||
your running application, to the Artifact manager instance, and so on.
|
||||
The following list describes the environment variables:
|
||||
|
||||
- `PROJECT_GROUP`: Your project's group ID. Defaults to `com.example`.
|
||||
- `PROJECT_VERSION`: Your project's version. Defaults to `0.0.1-SNAPSHOT`.
|
||||
- `PROJECT_NAME`: Your project's artifact id. Defaults to `example`.
|
||||
- `PRODUCER_STUBS_CLASSIFIER`: Archive classifier used for generated producer stubs. Defaults to `stubs`.
|
||||
- `REPO_WITH_BINARIES_URL`: URL of your Artifact Manager. Defaults to `http://localhost:8081/artifactory/libs-release-local`,
|
||||
which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally.
|
||||
- `REPO_WITH_BINARIES_USERNAME`: (optional) Username when the Artifact Manager is secured. Defaults to `admin`.
|
||||
- `REPO_WITH_BINARIES_PASSWORD`: (optional) Password when the Artifact Manager is secured. Defaults to `password`.
|
||||
- `PUBLISH_ARTIFACTS`: If set to `true`, publishes the artifact to binary storage. Defaults to `true`.
|
||||
|
||||
These environment variables are used when contracts lay in an external repository. To enable
|
||||
this feature, you must set the `EXTERNAL_CONTRACTS_ARTIFACT_ID` environment variable.
|
||||
|
||||
- `EXTERNAL_CONTRACTS_GROUP_ID`: Group ID of the project with contracts. Defaults to `com.example`
|
||||
- `EXTERNAL_CONTRACTS_ARTIFACT_ID`: Artifact ID of the project with contracts.
|
||||
- `EXTERNAL_CONTRACTS_CLASSIFIER`: Classifier of the project with contracts. Empty by default.
|
||||
- `EXTERNAL_CONTRACTS_VERSION`: Version of the project with contracts. Defaults to `+`, equivalent to picking the latest.
|
||||
- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`: URL of your Artifact Manager. It defaults to
|
||||
the value of `REPO_WITH_BINARIES_URL` environment variable.
|
||||
If that is not set, it defaults to `http://localhost:8081/artifactory/libs-release-local`,
|
||||
which is the default URL of https://jfrog.com/artifactory/[Artifactory] running locally.
|
||||
- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME`: (optional) Username if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`
|
||||
requires authentication. It defaults to `REPO_WITH_BINARIES_USERNAME`. If that is not set, it defaults to `admin`.
|
||||
- `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD`: (optional) Password if the `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`
|
||||
requires authentication. It defaults to `REPO_WITH_BINARIES_PASSWORD`. If that is not set, it defaults to `password`.
|
||||
- `EXTERNAL_CONTRACTS_PATH`: Path to contracts for the given project, inside the project with contracts.
|
||||
Defaults to slash-separated `EXTERNAL_CONTRACTS_GROUP_ID` concatenated with `/` and `EXTERNAL_CONTRACTS_ARTIFACT_ID`. For example,
|
||||
for group id `cat-server-side.dog` and artifact id `fish`, would result in `cat/dog/fish` for the contracts path.
|
||||
- `EXTERNAL_CONTRACTS_WORK_OFFLINE`; If set to `true`, retrieves the artifact with contracts
|
||||
from the container's `.m2`. Mount your local `.m2` as a volume available at the container's `/root/.m2` path.
|
||||
|
||||
WARNING: You must not set both `EXTERNAL_CONTRACTS_WORK_OFFLINE` and `EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL`.
|
||||
|
||||
The following environment variables are used when tests are executed:
|
||||
|
||||
- `APPLICATION_BASE_URL`: URL against which tests should be run.
|
||||
Remember that it has to be accessible from the Docker container (for example, `localhost`
|
||||
does not work)
|
||||
- `APPLICATION_USERNAME`: (optional) Username for basic authentication to your application.
|
||||
- `APPLICATION_PASSWORD`: (optional) Password for basic authentication to your application.
|
||||
|
||||
[[docker-example-of-usage]]
|
||||
=== Example of Usage
|
||||
|
||||
In this section, we explore a simple MVC application. To get started, clone the following
|
||||
git repository and cd to the resulting directory, by running the following commands:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
|
||||
$ cd bookstore
|
||||
----
|
||||
====
|
||||
|
||||
The contracts are available in the `/contracts` folder.
|
||||
|
||||
Since we want to run tests, we can run the following command:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
$ npm test
|
||||
----
|
||||
====
|
||||
|
||||
However, for learning purposes, we split it into pieces, as follows:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
# Stop docker infra (nodejs, artifactory)
|
||||
$ ./stop_infra.sh
|
||||
# Start docker infra (nodejs, artifactory)
|
||||
$ ./setup_infra.sh
|
||||
|
||||
# Kill & Run app
|
||||
$ pkill -f "node app"
|
||||
$ nohup node app &
|
||||
|
||||
# Prepare environment variables
|
||||
$ SC_CONTRACT_DOCKER_VERSION="..."
|
||||
$ APP_IP="192.168.0.100"
|
||||
$ APP_PORT="3000"
|
||||
$ ARTIFACTORY_PORT="8081"
|
||||
$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
|
||||
$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
|
||||
$ CURRENT_DIR="$( pwd )"
|
||||
$ CURRENT_FOLDER_NAME=${PWD##*/}
|
||||
$ PROJECT_VERSION="0.0.1.RELEASE"
|
||||
|
||||
# Execute contract tests
|
||||
$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
|
||||
|
||||
# Kill app
|
||||
$ pkill -f "node app"
|
||||
----
|
||||
====
|
||||
|
||||
Through bash scripts, the following happens:
|
||||
|
||||
- The infrastructure (MongoDb and Artifactory) is set up.
|
||||
In a real-life scenario, you would run the NodeJS application
|
||||
with a mocked database. In this example, we want to show how we can
|
||||
benefit from Spring Cloud Contract in very little time.
|
||||
- Due to those constraints, the contracts also represent the
|
||||
stateful situation.
|
||||
** The first request is a `POST` that causes data to get inserted to the database.
|
||||
** The second request is a `GET` that returns a list of data with 1 previously inserted element.
|
||||
- The NodeJS application is started (on port `3000`).
|
||||
- The contract tests are generated through Docker, and tests
|
||||
are run against the running application.
|
||||
** The contracts are taken from `/contracts` folder.
|
||||
** The output of the test execution is available under
|
||||
`node_modules/spring-cloud-contract/output`.
|
||||
- The stubs are uploaded to Artifactory. You can find them in
|
||||
http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ .
|
||||
The stubs are at http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.
|
||||
|
||||
[[docker-stubrunner]]
|
||||
== Running Stubs on the Consumer Side
|
||||
|
||||
This section describes how to use Docker on the consumer side to fetch and run stubs.
|
||||
|
||||
We publish a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
|
||||
that starts the standalone version of Stub Runner.
|
||||
|
||||
[[docker-stubrunner-env-vars]]
|
||||
=== Environment Variables
|
||||
|
||||
You can run the docker image and pass any of the <<project-features.adoc#features-stub-runner-common-properties-junit-spring, Common Properties for JUnit and Spring>>
|
||||
as environment variables. The convention is that all the
|
||||
letters should be upper case.
|
||||
The dot (`.`) should be replaced with underscore (`_`) characters. For example,
|
||||
the `stubrunner.repositoryRoot` property should be represented
|
||||
as a `STUBRUNNER_REPOSITORY_ROOT` environment variable.
|
||||
|
||||
[[docker-stubrunner-example]]
|
||||
=== Example of Usage
|
||||
|
||||
We want to use the stubs created in this <<docker-server-side>> step.
|
||||
Assume that we want to run the stubs on port `9876`. You can see the NodeJS code
|
||||
by cloning the repository and changing to the directory indicated in the following commands:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
|
||||
$ cd bookstore
|
||||
----
|
||||
====
|
||||
|
||||
Now we can run the Stub Runner Boot application with the stubs, by running the following
|
||||
commands:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
# Provide the Spring Cloud Contract Docker version
|
||||
$ SC_CONTRACT_DOCKER_VERSION="..."
|
||||
# The IP at which the app is running and Docker container can reach it
|
||||
$ APP_IP="192.168.0.100"
|
||||
# Spring Cloud Contract Stub Runner properties
|
||||
$ STUBRUNNER_PORT="8083"
|
||||
# Stub coordinates 'groupId:artifactId:version:classifier:port'
|
||||
$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
|
||||
$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
|
||||
# Run the docker with Stub Runner Boot
|
||||
$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
|
||||
----
|
||||
====
|
||||
|
||||
When the preceding commands run,
|
||||
|
||||
- A standalone Stub Runner application gets started.
|
||||
- It downloads the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876`.
|
||||
- It gets downloads from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local`.
|
||||
- After a whil, Stub Runner is running on port `8083`.
|
||||
- The stubs are running at port `9876`.
|
||||
|
||||
On the server side, we built a stateful stub. We can use curl to assert
|
||||
that the stubs are setup properly. To do so, run the following commands:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
# let's execute the first request (no response is returned)
|
||||
$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
|
||||
# Now time for the second request
|
||||
$ curl -X GET http://localhost:9876/api/books
|
||||
# You will receive contents of the JSON
|
||||
----
|
||||
====
|
||||
|
||||
IMPORTANT: If you want use the stubs that you have built locally, on your host,
|
||||
you should set the `-e STUBRUNNER_STUBS_MODE=LOCAL` environment variable and mount
|
||||
the volume of your local m2 (`-v "${HOME}/.m2/:/root/.m2:ro"`).
|
||||
128
docs/src/main/asciidoc/documentation-overview.adoc
Normal file
128
docs/src/main/asciidoc/documentation-overview.adoc
Normal file
@@ -0,0 +1,128 @@
|
||||
[[documentation]]
|
||||
= Spring Cloud Contract Documentation
|
||||
include::_attributes.adoc[]
|
||||
|
||||
This section provides a brief overview of {project-full-name} reference documentation. It serves
|
||||
as a map for the rest of the document.
|
||||
|
||||
|
||||
|
||||
[[contract-documentation-about]]
|
||||
== About the Documentation
|
||||
|
||||
The {project-full-name} reference guide is available as
|
||||
|
||||
* {docs-url}/html[Multi-page HTML]
|
||||
* {docs-url}/htmlsingle[Single-page HTML]
|
||||
* {docs-url}/pdf/{project-name}.pdf[PDF]
|
||||
|
||||
Copies of this document may be made for your own use and for distribution to others,
|
||||
provided that you do not charge any fee for such copies and further provided that each
|
||||
copy contains this Copyright Notice, whether distributed in print or electronically.
|
||||
|
||||
|
||||
|
||||
[[documentation-getting-help]]
|
||||
== Getting Help
|
||||
If you have trouble with {project-full-name}, we would like to help.
|
||||
|
||||
* Try the <<howto.adoc#howto, How-to documents>>. They provide solutions to the most
|
||||
common questions.
|
||||
* Learn the {project-full-name} basics. If you are
|
||||
starting out with {project-full-name}, try one of the https://spring.io/guides[guides].
|
||||
* Ask a question. We monitor https://stackoverflow.com[stackoverflow.com] for questions
|
||||
tagged with https://stackoverflow.com/tags/{project-name}[`{project-name}`].
|
||||
* Report bugs with {project-full-name} at https://github.com/spring-cloud/{project-name}/issues.
|
||||
* Chat with us at http://https://gitter.im/spring-cloud/{project-name}[{project-full-name} Gitter]
|
||||
|
||||
NOTE: All of {project-full-name} is open source, including the documentation. If you find
|
||||
problems with the docs or if you want to improve them, please {github-code}[get
|
||||
involved].
|
||||
|
||||
|
||||
[[contract-documentation-first-steps]]
|
||||
== First Steps
|
||||
If you are getting started with {project-full-name} or 'Spring' in general, start with
|
||||
<<getting-started.adoc#getting-started, the following topics>>:
|
||||
|
||||
* *From scratch:*
|
||||
<<getting-started.adoc#getting-started-introducing-{project-name}, Overview>> |
|
||||
<<getting-started.adoc#getting-started-three-second-tour, Three-second Tour>> |
|
||||
<<getting-started.adoc#getting-started-first-application, First application>>
|
||||
* *Tutorial:*
|
||||
<<getting-started.adoc#getting-started-cdc, Introduction>> |
|
||||
<<getting-started.adoc#consumer-side-loan-issuance, Consumer, Part 1>> |
|
||||
<<getting-started.adoc#producer-side-fraud-detection-server, Producer>> |
|
||||
<<getting-started.adoc#consumer-side-loan-issuance-final-step, Consumer, Part 2>>
|
||||
|
||||
|
||||
|
||||
== Working with {project-full-name}
|
||||
Ready to actually start using {project-full-name}? <<using.adoc#using, We have
|
||||
you covered>>:
|
||||
|
||||
* *Provider contract testing:*
|
||||
|
||||
** <<using.adoc#flows-provider-nexus,Provider contract testing with stubs in Nexus or Artifactory>>
|
||||
** <<using.adoc#flows-provider-git,Provider contract testing with stubs in Git>>
|
||||
** <<using.adoc#flows-provider-non-spring,Provider contract testing with stubs in Artifactory for a non-Spring application>>
|
||||
** <<using.adoc#flows-provider-non-jvm,Provider contract testing with stubs in Artifactory in non JVM world>>
|
||||
** <<using.adoc#flows-provider-rest-docs,Provider contract testing with REST Docs and stubs in Nexus / Artifactory>>
|
||||
|
||||
* *Consumer-Driven contract testing:*
|
||||
** <<using.adoc#flows-cdc-contracts-producer,Consumer Driven Contracts with contracts on the producer side>>
|
||||
** <<using.adoc#flows-cdc-contracts-external,Consumer Driven Contracts with contracts in external repo>>
|
||||
** <<using.adoc#flows-cdc-contracts-stubs-git,Consumer Driven Contracts with contracts on the producer side, pushed to git>>
|
||||
|
||||
TIP: We talk about *Provider Contracts* when it is the producer of the API that defines the contracts and
|
||||
publishes it for all its consumers to use. This approach is useful for producers that cannot
|
||||
directly collaborate with their consumers -- for example, when there are too many consumers or
|
||||
the consumers are external (do not work within the same company).
|
||||
|
||||
TIP: We use the term, *Consumer-Driven Contracts*, to refer to workflows where the consumers of an API
|
||||
play a vital role in the process of creating the contracts. We recommended this approach, because it is easy
|
||||
to implement when both producer and consumer teams work for the same organizations and the number
|
||||
of consumers is not extremely large.
|
||||
|
||||
== Learning about {project-full-name} Features
|
||||
Need more details about {project-full-name}'s core features?
|
||||
<<project-features.adoc#features, The following content is for you>>:
|
||||
|
||||
* *Core Features:*
|
||||
<<project-features.adoc#contract-dsl, Contract DSL>> |
|
||||
<<project-features.adoc#features-http, Contracts for HTTP>> |
|
||||
<<project-features.adoc#features-messaging, Contracts for Messaging>>
|
||||
* *Integrations:*
|
||||
<<project-features.adoc#features-jax-rs, JAX-RS>> |
|
||||
<<project-features.adoc#features-context-paths, Context Paths>> |
|
||||
<<project-features.adoc#features-rest-docs, RESTDocs>>
|
||||
<<howto.adoc#how-to-generate-pact-from-scc, Pact>>
|
||||
* *Modules:*
|
||||
<<project-features.adoc#features-stub-runner, Stub Runner>> |
|
||||
<<project-features.adoc#features-wiremock, WireMock>>
|
||||
// TODO: links don't work in "build Tools" section
|
||||
* *Build Tools:*
|
||||
link:maven-project.html[Contract Verifier - Maven] |
|
||||
link:gradle-project.html[Contract Verifier - Gradle] |
|
||||
link:docker-project.html[Docker]
|
||||
|
||||
|
||||
== Advanced Topics
|
||||
Finally, we have a few topics for more advanced users:
|
||||
|
||||
* *Customizing the DSL:*
|
||||
<<advanced.adoc#contract-dsl-customization, DSL Customization>> |
|
||||
<<advanced.adoc#contract-dsl-extending-common-jar, Common JAR>> |
|
||||
<<advanced.adoc#contract-dsl-test-dep, Test Dependency>> |
|
||||
<<advanced.adoc#contract-dsl-plugin-dep, Plugin Dependency>> |
|
||||
<<advanced.adoc#contract-dsl-referencing, Referencing the DSL>>
|
||||
* *Customizing WireMock:*
|
||||
<<advanced.adoc#customization-wiremock-extension, Extensions>> |
|
||||
<<advanced.adoc#customization-wiremock-configuration, Configuration>>
|
||||
* *Customizing {project-full-name}:*
|
||||
<<advanced.adoc#contract-dsl-pluggable-architecture, Pluggable Architecture>> |
|
||||
<<advanced.adoc#contract-dsl-custom-contract-converter, Contract Converter>> |
|
||||
<<advanced.adoc#contract-dsl-custom-test-generator, Test Generator>> |
|
||||
<<advanced.adoc#contract-dsl-custom-stub-generator, Stub Generator>> |
|
||||
<<advanced.adoc#contract-dsl-custom-stub-runner, Stub Runner>> |
|
||||
<<advanced.adoc#contract-dsl-custom-stub-downloader, Stub Downloader>>
|
||||
File diff suppressed because it is too large
Load Diff
435
docs/src/main/asciidoc/gradle-project.adoc
Normal file
435
docs/src/main/asciidoc/gradle-project.adoc
Normal file
@@ -0,0 +1,435 @@
|
||||
= Gradle Project
|
||||
include::_attributes.adoc[]
|
||||
|
||||
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-pushing-stubs-to-scm>>
|
||||
* <<gradle-consumer>>
|
||||
|
||||
[[gradle-prerequisites]]
|
||||
== Prerequisites
|
||||
|
||||
In order to use Spring Cloud Contract Verifier with WireMock, you must use either a
|
||||
Gradle or a Maven plugin.
|
||||
|
||||
WARNING: If you want to use Spock in your projects, you must separately add the
|
||||
`spock-core` and `spock-spring` modules. See https://spockframework.github.io/[Spock's
|
||||
documnetation for more information]
|
||||
|
||||
[[gradle-add-gradle-plugin]]
|
||||
== Add Gradle Plugin with Dependencies
|
||||
|
||||
To add a Gradle plugin with dependencies, you can use code similar to the following:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
|
||||
classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: 'groovy'
|
||||
apply plugin: 'spring-cloud-contract'
|
||||
|
||||
dependencyManagement {
|
||||
imports {
|
||||
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
|
||||
// example with adding Spock core and Spock Spring
|
||||
testCompile "org.spockframework:spock-core:${spockVersion}"
|
||||
testCompile "org.spockframework:spock-spring:${spockVersion}"
|
||||
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[gradle-and-rest-assured]]
|
||||
== Gradle and Rest Assured 2.0
|
||||
|
||||
By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x
|
||||
you can add it to the plugins classpath, as the following listing shows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
|
||||
classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
|
||||
classpath "com.jayway.restassured:rest-assured:2.5.0"
|
||||
classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
|
||||
}
|
||||
}
|
||||
|
||||
depenendencies {
|
||||
// all dependencies
|
||||
// you can exclude rest-assured from spring-cloud-contract-verifier
|
||||
testCompile "com.jayway.restassured:rest-assured:2.5.0"
|
||||
testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
|
||||
and modifies the imports accordingly.
|
||||
|
||||
[[gradle-snapshot-versions]]
|
||||
== Snapshot Versions for Gradle
|
||||
|
||||
You can add the additional snapshot repository to your `build.gradle` to use snapshot versions,
|
||||
which are automatically uploaded after every successful build, as the following listing shows:
|
||||
|
||||
====
|
||||
[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 looks for stubs in the
|
||||
`src/test/resources/contracts` directory.
|
||||
|
||||
The directory that contains stub definitions is treated as a class name, and each stub
|
||||
definition is treated as a single test. Spring Cloud Contract Verifier assumes that it
|
||||
contains at least one level of directories that are to be used as the test class name.
|
||||
If more than one level of nested directories is present, all except the last one is used
|
||||
as the package name. Consider the following structure:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
src/test/resources/contracts/myservice/shouldCreateUser.groovy
|
||||
src/test/resources/contracts/myservice/shouldReturnUser.groovy
|
||||
----
|
||||
====
|
||||
|
||||
Given the preceding structure, Spring Cloud Contract Verifier creates a test class named
|
||||
`defaultBasePackage.MyService` with two methods:
|
||||
|
||||
- `shouldCreateUser()`
|
||||
- `shouldReturnUser()`
|
||||
|
||||
[[gradle-run-plugin]]
|
||||
== Running the Plugin
|
||||
|
||||
The plugin registers itself to be invoked before a `check` task. If you want it to be
|
||||
part of your build process, you need do nothing more. If you just want to generate
|
||||
tests, invoke the `generateContractTests` task.
|
||||
|
||||
[[gradle-default-setup]]
|
||||
== Default Setup
|
||||
|
||||
The default Gradle Plugin setup creates the following Gradle part of the build (in
|
||||
pseudocode):
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
contracts {
|
||||
testFramework ='JUNIT'
|
||||
testMode = 'MockMvc'
|
||||
generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
|
||||
generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
|
||||
contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
|
||||
basePackageForTests = 'org.springframework.cloud.verifier.tests'
|
||||
stubsOutputDir = project.file("${project.buildDir}/stubs")
|
||||
|
||||
// the following properties are used when you want to provide where the JAR with contract lays
|
||||
contractDependency {
|
||||
stringNotation = ''
|
||||
}
|
||||
contractsPath = ''
|
||||
contractsWorkOffline = false
|
||||
contractRepository {
|
||||
cacheDownloadedContracts(true)
|
||||
}
|
||||
}
|
||||
|
||||
tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
|
||||
baseName = project.name
|
||||
classifier = contracts.stubsSuffix
|
||||
from contractVerifier.stubsOutputDir
|
||||
}
|
||||
|
||||
project.artifacts {
|
||||
archives task
|
||||
}
|
||||
|
||||
tasks.create(type: Copy, name: 'copyContracts') {
|
||||
from contracts.contractsDslDir
|
||||
into contracts.stubsOutputDir
|
||||
}
|
||||
|
||||
verifierStubsJar.dependsOn 'copyContracts'
|
||||
|
||||
publishing {
|
||||
publications {
|
||||
stubs(MavenPublication) {
|
||||
artifactId project.name
|
||||
artifact verifierStubsJar
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[gradle-configure-plugin]]
|
||||
== Configuring the Plugin
|
||||
|
||||
To change the default configuration, you can add a `contracts` snippet to your Gradle
|
||||
configuration, as the following listing shows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
contracts {
|
||||
testMode = 'MockMvc'
|
||||
baseClassForTests = 'org.mycompany.tests'
|
||||
generatedTestSourcesDir = project.file('src/generatedContract')
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[gradle-configuration-options]]
|
||||
== Configuration Options
|
||||
|
||||
* `testMode`: Defines the mode for acceptance tests. By default, the mode is MockMvc,
|
||||
which is based on Spring's MockMvc. It can also be changed to WebTestClient, JaxRsClient, or
|
||||
Explicit (for real HTTP calls).
|
||||
* `imports`: Creates an array with imports that should be included in the generated tests
|
||||
(for example, `['org.myorg.Matchers']`). By default, it creates an empty array.
|
||||
* `staticImports`: Creates an array with static imports that should be included in
|
||||
generated tests(for example, `['org.myorg.Matchers.*']`). By default, it creates an empty
|
||||
array.
|
||||
* `basePackageForTests`: Specifies the base package for all generated tests. If not set,
|
||||
the value is picked from the package of `baseClassForTests` and from `packageWithBaseClasses`.
|
||||
If neither of these values are set, the value is set to
|
||||
`org.springframework.cloud.contract.verifier.tests`.
|
||||
* `baseClassForTests`: Creates a base class for all generated tests. By default, if you
|
||||
use Spock classes, the class is `spock.lang.Specification`.
|
||||
* `packageWithBaseClasses`: Defines a package where all the base classes reside. This
|
||||
setting takes precedence over `baseClassForTests`.
|
||||
* `baseClassMappings`: Explicitly maps a contract package to a FQN of a base class. This
|
||||
setting takes precedence over `packageWithBaseClasses` and `baseClassForTests`.
|
||||
* `ruleClassForTests`: Specifies a rule that should be added to the generated test
|
||||
classes.
|
||||
* `ignoredFiles`: Uses an `Antmatcher` to allow defining stub files for which processing
|
||||
should be skipped. By default, it is an empty array.
|
||||
* `contractsDslDir`: Specifies the directory that contains contracts written by using the
|
||||
GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`.
|
||||
* `generatedTestSourcesDir`: Specifies the test source directory where tests generated
|
||||
from the Groovy DSL should be placed. By default, its value is
|
||||
`$buildDir/generated-test-sources/contracts`.
|
||||
* `generatedTestResourcesDir`: Specifies the test resource directory where resources used by the tests generated
|
||||
from the Groovy DSL should be placed. By default, its value is
|
||||
`$buildDir/generated-test-resources/contracts`.
|
||||
* `stubsOutputDir`: Specifies the directory where the generated WireMock stubs from
|
||||
the Groovy DSL should be placed.
|
||||
* `testFramework`: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`), and
|
||||
JUnit 5 are supported, with JUnit 4 being the default framework.
|
||||
* `contractsProperties`: A map that contains properties to be passed to Spring Cloud Contract
|
||||
components. Those properties might be used by (for example) built-in or custom Stub Downloaders.
|
||||
|
||||
You can use the following properties when you want to specify the location of the JAR
|
||||
that contains the contracts:
|
||||
|
||||
* `contractDependency`: Specifies the Dependency that provides
|
||||
`groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency`
|
||||
closure to set it up.
|
||||
* `contractsPath`: Specifies the path to the jar. If contract dependencies are
|
||||
downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash
|
||||
separated. Otherwise, it scans contracts under the provided directory.
|
||||
* `contractsMode`: Specifies the mode for downloading contracts (whether the
|
||||
JAR is available offline, remotely, and so on).
|
||||
* `deleteStubsAfterTest`: If set to `false`, do not remove any downloaded
|
||||
contracts from temporary directories.
|
||||
|
||||
You can also turn on the following experimental features in the plugin:
|
||||
|
||||
* `convertToYaml`: Converts all DSLs to the declarative YAML format. This can be extremely
|
||||
useful when you use external libraries in your Groovy DSLs. By turning this feature on
|
||||
(by setting it to `true`) you need not add the library dependency on the consumer side.
|
||||
* `assertJsonSize`: You can check the size of JSON arrays in the generated tests. This
|
||||
feature is disabled by default.
|
||||
|
||||
[[gradle-single-base-class]]
|
||||
== Single Base Class for All Tests
|
||||
|
||||
When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base
|
||||
specification for all generated acceptance tests. In this class, you need to point to an
|
||||
endpoint, which should be verified. The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
If you use `Explicit` mode, you can use a base class to initialize the whole tested application,
|
||||
as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this
|
||||
base class should also contain a `protected WebTarget webTarget` field. Right now, the
|
||||
only option to test the JAX-RS API is to start a web server.
|
||||
|
||||
[[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:
|
||||
|
||||
* Follow a convention by providing the `packageWithBaseClasses`
|
||||
* Provide explicit mapping by using `baseClassMappings`
|
||||
|
||||
=== By Convention
|
||||
|
||||
The convention is such that if you have a contract in (for example)
|
||||
`src/test/resources/contract/foo/bar/baz/` and set the value of the
|
||||
`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract
|
||||
Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package.
|
||||
In other words, the system takes the last two parts of the package, if they exist, and
|
||||
forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`.
|
||||
The following example shows how it works in the `contracts` closure:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
=== By Mapping
|
||||
|
||||
You can manually map a regular expression of the contract's package to the fully qualified
|
||||
name of the base class for the matched contract. You have to provide a list called
|
||||
`baseClassMappings` that consists of `baseClassMapping` objects that take a
|
||||
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
|
||||
|
||||
====
|
||||
[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 in the following directories:
|
||||
- `src/test/resources/contract/com/`
|
||||
- `src/test/resources/contract/foo/`
|
||||
|
||||
By providing `baseClassForTests`, we have a fallback in case mapping did not succeed.
|
||||
(You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests
|
||||
generated from `src/test/resources/contract/com/` contracts extend the
|
||||
`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`.
|
||||
|
||||
[[gradle-invoking-generated-tests]]
|
||||
== Invoking Generated Tests
|
||||
|
||||
To ensure that the provider side is compliant with your defined contracts, you need to run
|
||||
the following command:
|
||||
|
||||
====
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
./gradlew generateContractTests test
|
||||
----
|
||||
====
|
||||
|
||||
[[gradle-pushing-stubs-to-scm]]
|
||||
== Pushing Stubs to SCM
|
||||
|
||||
If you use the SCM repository to keep the contracts and
|
||||
stubs, you might want to automate the step of pushing stubs to
|
||||
the repository. To do that, you can call the `pushStubsToScm`
|
||||
task by running the following command:
|
||||
|
||||
====
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
$ ./gradlew pushStubsToScm
|
||||
----
|
||||
====
|
||||
|
||||
Under <<scm-stub-downloader>> you can find all possible
|
||||
configuration options that you can pass either through
|
||||
the `contractsProperties` field (for example, `contracts { contractsProperties = [foo:"bar"] }`),
|
||||
through the `contractsProperties` method (for example, `contracts { contractsProperties([foo:"bar"]) }`),
|
||||
or through a system property or an environment variable.
|
||||
|
||||
[[gradle-consumer]]
|
||||
== Spring Cloud Contract Verifier on the Consumer Side
|
||||
|
||||
In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin
|
||||
in exactly the same way as in the case of a provider. If you do not want to use Stub Runner,
|
||||
you need to copy the contracts stored in `src/test/resources/contracts` and generate
|
||||
WireMock JSON stubs by using the following command:
|
||||
|
||||
====
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
./gradlew generateClientStubs
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: The `stubsOutputDir` option has to be set for stub generation to work.
|
||||
|
||||
When present, JSON stubs can be used in automated tests to consume a service. The
|
||||
following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
|
||||
class LoanApplicationServiceSpec extends Specification {
|
||||
|
||||
@ClassRule
|
||||
@Shared
|
||||
WireMockClassRule wireMockRule == new WireMockClassRule()
|
||||
|
||||
@Autowired
|
||||
LoanApplicationService sut
|
||||
|
||||
def 'should successfully apply for loan'() {
|
||||
given:
|
||||
LoanApplication application =
|
||||
new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
|
||||
when:
|
||||
LoanApplicationResult loanApplication == sut.loanApplication(application)
|
||||
then:
|
||||
loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
|
||||
loanApplication.rejectionReason == null
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
In the preceding example, `LoanApplication` makes a call to the `FraudDetection` service.
|
||||
This request is handled by a WireMock server configured with stubs that were generated by
|
||||
Spring Cloud Contract Verifier.
|
||||
1434
docs/src/main/asciidoc/howto.adoc
Normal file
1434
docs/src/main/asciidoc/howto.adoc
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1 +0,0 @@
|
||||
spring-cloud-contract.adoc
|
||||
16
docs/src/main/asciidoc/index.htmladoc
Normal file
16
docs/src/main/asciidoc/index.htmladoc
Normal file
@@ -0,0 +1,16 @@
|
||||
[[spring-cloud-contract-reference-documentation]]
|
||||
= Spring Cloud Contract Reference Documentation
|
||||
Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
|
||||
:docinfo: shared
|
||||
include::_attributes.adoc[]
|
||||
|
||||
The reference documentation consists of the following sections:
|
||||
|
||||
[horizontal]
|
||||
<<legal.adoc#legal-information,Legal>> :: Legal information.
|
||||
<<documentation-overview.adoc#contract-documentation,Documentation Overview>> :: About the Documentation, Getting Help, First Steps, and more.
|
||||
<<getting-started.adoc#getting-started,Getting Started>> :: Introducing {project-full-name}, Developing Your First {project-full-name}-based Application
|
||||
<<using.adoc#using,Using {project-full-name}>> :: {project-full-name} usage examples and workflows
|
||||
<<project-features.adoc#features,{project-full-name} Features>> :: Contract DSL, Messaging, Spring Cloud Contract Stub Runner, and Spring Cloud Contract WireMock.
|
||||
<<project-features.adoc#features-build-tools,Build Tools>> :: Maven Plugin, Gradle Plugin, and Docker.
|
||||
<<howto.adoc#howto,"`How-to`" Guides>> :: Stubs versioning, Pact integration, Debugging, and more.
|
||||
11
docs/src/main/asciidoc/index.htmlpdfadoc
Normal file
11
docs/src/main/asciidoc/index.htmlpdfadoc
Normal file
@@ -0,0 +1,11 @@
|
||||
[[spring-cloud-contract-reference-documentation]]
|
||||
= Spring Cloud Contract Reference Documentation
|
||||
Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
|
||||
include::_attributes.adoc[]
|
||||
|
||||
include::legal.adoc[leveloffset=+1]
|
||||
include::documentation-overview.adoc[leveloffset=+1]
|
||||
include::getting-started.adoc[leveloffset=+1]
|
||||
include::using.adoc[leveloffset=+1]
|
||||
include::project-features.adoc[leveloffset=+1]
|
||||
include::howto.adoc[leveloffset=+1]
|
||||
12
docs/src/main/asciidoc/index.htmlsingleadoc
Normal file
12
docs/src/main/asciidoc/index.htmlsingleadoc
Normal file
@@ -0,0 +1,12 @@
|
||||
[[spring-cloud-contract-reference-documentation]]
|
||||
= Spring Cloud Contract Reference Documentation
|
||||
Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant
|
||||
:docinfo: shared
|
||||
include::_attributes.adoc[]
|
||||
|
||||
include::legal.adoc[leveloffset=+1]
|
||||
include::documentation-overview.adoc[leveloffset=+1]
|
||||
include::getting-started.adoc[leveloffset=+1]
|
||||
include::using.adoc[leveloffset=+1]
|
||||
include::project-features.adoc[leveloffset=+1]
|
||||
include::howto.adoc[leveloffset=+1]
|
||||
11
docs/src/main/asciidoc/legal.adoc
Normal file
11
docs/src/main/asciidoc/legal.adoc
Normal file
@@ -0,0 +1,11 @@
|
||||
[legal]
|
||||
= Legal
|
||||
|
||||
{project-version}
|
||||
|
||||
Copyright © 2012-2019
|
||||
|
||||
Copies of this document may be made for your own use and for distribution to
|
||||
others, provided that you do not charge any fee for such copies and further
|
||||
provided that each copy contains this Copyright Notice, whether distributed in
|
||||
print or electronically.
|
||||
@@ -1,11 +0,0 @@
|
||||
== Links
|
||||
|
||||
The following links may be helpful when working with Spring Cloud Contract:
|
||||
|
||||
* 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://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter]
|
||||
* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by
|
||||
Marcin Grzejszczak]
|
||||
564
docs/src/main/asciidoc/maven-project.adoc
Normal file
564
docs/src/main/asciidoc/maven-project.adoc
Normal file
@@ -0,0 +1,564 @@
|
||||
= Maven Project
|
||||
include::_attributes.adoc[]
|
||||
|
||||
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-pushing-stubs-to-scm>>
|
||||
* <<maven-sts>>
|
||||
|
||||
[[maven-add-plugin]]
|
||||
== Adding the Maven Plugin
|
||||
|
||||
Add the Spring Cloud Contract BOM in a fashion similar to the following:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_bom,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
Next, add the `Spring Cloud Contract Verifier` Maven plugin, as follows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
You can read more in the
|
||||
spring-cloud-contract-maven-plugin/index.html[Spring
|
||||
Cloud Contract Maven Plugin Documentation].
|
||||
|
||||
[[maven-rest-assured]]
|
||||
== Maven and Rest Assured 2.0
|
||||
|
||||
By default, Rest Assured 3.x is added to the classpath. However, you can use Rest
|
||||
Assured 2.x by adding it to the plugins classpath, as follows:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<packageWithBaseClasses>com.example</packageWithBaseClasses>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-verifier</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>spring-mock-mvc</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
|
||||
<dependencies>
|
||||
<!-- all dependencies -->
|
||||
<!-- you can exclude rest-assured from spring-cloud-contract-verifier -->
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>rest-assured</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.restassured</groupId>
|
||||
<artifactId>spring-mock-mvc</artifactId>
|
||||
<version>2.5.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
====
|
||||
|
||||
That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
|
||||
and modifies the imports accordingly.
|
||||
|
||||
[[maven-snapshot-versions]]
|
||||
== Using Snapshot and Milestone Versions for Maven
|
||||
|
||||
To use Snapshot and Milestone versions, you have to add the following section to your
|
||||
`pom.xml`:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
[[maven-add-stubs]]
|
||||
== Adding stubs
|
||||
|
||||
By default, Spring Cloud Contract Verifier looks for stubs in the
|
||||
`src/test/resources/contracts` directory. The directory containing stub definitions is
|
||||
treated as a class name, and each stub definition is treated as a single test. We assume
|
||||
that it contains at least one directory to be used as the test class name. If there is more
|
||||
than one level of nested directories, all except the last one is used as the package name.
|
||||
Consider the following structure:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
src/test/resources/contracts/myservice/shouldCreateUser.groovy
|
||||
src/test/resources/contracts/myservice/shouldReturnUser.groovy
|
||||
----
|
||||
====
|
||||
|
||||
Given that structure, Spring Cloud Contract Verifier creates a test class named
|
||||
`defaultBasePackage.MyService` with two methods:
|
||||
|
||||
* `shouldCreateUser()`
|
||||
* `shouldReturnUser()`
|
||||
|
||||
[[maven-run-plugin]]
|
||||
== Run plugin
|
||||
|
||||
The `generateTests` plugin goal is assigned to be invoked in the phase called
|
||||
`generate-test-sources`. If you want it to be part of your build process, you need not do
|
||||
anything. If you want only to generate tests, invoke the `generateTests` goal.
|
||||
|
||||
[[maven-configure-plugin]]
|
||||
== Configure plugin
|
||||
|
||||
To change the default configuration, you can add a `configuration` section to the plugin
|
||||
definition or the `execution` definition, as follows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>convert</goal>
|
||||
<goal>generateStubs</goal>
|
||||
<goal>generateTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
|
||||
<baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
====
|
||||
|
||||
[[maven-configuration-options]]
|
||||
== Configuration Options
|
||||
|
||||
* `testMode`: Defines the mode for acceptance tests. By default, the mode is `MockMvc`,
|
||||
which is based on Spring's MockMvc. You can also change it to `WebTestClient`, `JaxRsClient`, or
|
||||
`Explicit` (for real HTTP calls).
|
||||
* `basePackageForTests`: Specifies the base package for all generated tests. If not set,
|
||||
the value is picked from the package of `baseClassForTests` and from `packageWithBaseClasses`.
|
||||
If neither of these values are set, the value is set to
|
||||
`org.springframework.cloud.contract.verifier.tests`.
|
||||
* `ruleClassForTests`: Specifies a rule that should be added to the generated test
|
||||
classes.
|
||||
* `baseClassForTests`: Creates a base class for all generated tests. By default, if you
|
||||
use Spock classes, the class is `spock.lang.Specification`.
|
||||
* contractsDirectory: Specifies a directory that contains contracts written with the
|
||||
Groovyn DSL. The default directory is `/src/test/resources/contracts`.
|
||||
* `generatedTestSourcesDir`: Specifies the test source directory where tests generated
|
||||
from the Groovy DSL should be placed. By default, its value is
|
||||
`$buildDir/generated-test-sources/contracts`.
|
||||
* `generatedTestResourcesDir`: Specifies the test resource directory for resources used by the generated tests.
|
||||
* `testFramework`: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (`TestFramework.JUNIT`), and
|
||||
JUnit 5 are supported, with JUnit 4 being the default framework.
|
||||
* `packageWithBaseClasses`: Defines a package where all the base classes reside. This
|
||||
setting takes precedence over `baseClassForTests`. The convention is such that, if you
|
||||
have a contract under (for example) `src/test/resources/contract/foo/bar/baz/` and set
|
||||
the value of the `packageWithBaseClasses` property to `com.example.base`, Spring
|
||||
Cloud Contract Verifier assumes that there is a `BarBazBase` class under the
|
||||
`com.example.base` package. In other words, the system takes the last two parts of the
|
||||
package, if they exist, and forms a class with `Base` as a suffix.
|
||||
* `baseClassMappings`: Specifies a list of base class mappings that provide
|
||||
`contractPackageRegex` (which is checked against the package where the contract is
|
||||
located) and `baseClassFQN`( which maps to the fully qualified name of the base class for
|
||||
the matched contract). For example, if you have a contract under
|
||||
`src/test/resources/contract/foo/bar/baz/` and map the
|
||||
`.* -> com.example.base.BaseClass` property, the test class generated from these contracts
|
||||
extends `com.example.base.BaseClass`. This setting takes precedence over
|
||||
`packageWithBaseClasses` and `baseClassForTests`.
|
||||
* `contractsProperties`: A map that contains properties to be passed to Spring Cloud Contract
|
||||
components. Those properties might be used by (for example) built-in or custom Stub Downloaders.
|
||||
|
||||
If you want to download your contract definitions from a Maven repository, you can use
|
||||
the following options:
|
||||
|
||||
* `contractDependency`: The contract dependency that contains all the packaged contracts.
|
||||
* `contractsPath`: The path to the concrete contracts in the JAR with packaged contracts.
|
||||
Defaults to `groupid/artifactid` where `gropuid` is slash separated.
|
||||
* `contractsMode`: Picks the mode in which stubs are found and registered.
|
||||
* `deleteStubsAfterTest`: If set to `false` will not remove any downloaded
|
||||
contracts from temporary directories.
|
||||
* `contractsRepositoryUrl`: URL to a repository with the artifacts that have contracts. If it is not provided,
|
||||
use the current Maven ones.
|
||||
* `contractsRepositoryUsername`: The user name to be used to connect to the repo with contracts.
|
||||
* `contractsRepositoryPassword`: The password to be used to connect to the repo with contracts.
|
||||
* `contractsRepositoryProxyHost`: The proxy host to be used to connect to the repo with contracts.
|
||||
* `contractsRepositoryProxyPort`: The proxy port to be used to connect to the repo with contracts.
|
||||
|
||||
We cache only non-snapshot, explicitly provided versions (for example
|
||||
`+` or `1.0.0.BUILD-SNAPSHOT` do not get cached). By default, this feature is turned on.
|
||||
|
||||
The following list describes experimental features that you can turn on in the plugin:
|
||||
|
||||
* `convertToYaml`: Converts all DSLs to the declarative YAML format. This can be extremely useful when you use external libraries in your Groovy DSLs. By turning this feature on (by setting it to `true`) you need not add the library dependency on the consumer side.
|
||||
* `assertJsonSize`: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.
|
||||
|
||||
[[maven-single-base]]
|
||||
== Single Base Class for All Tests
|
||||
|
||||
When using Spring Cloud Contract Verifier in the default (`MockMvc`), you need to create a base
|
||||
specification for all generated acceptance tests. In this class, you need to point to an
|
||||
endpoint, which should be verified. The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
package org.mycompany.tests
|
||||
|
||||
import org.mycompany.ExampleSpringController
|
||||
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
|
||||
import spock.lang.Specification
|
||||
|
||||
class MvcSpec extends Specification {
|
||||
def setup() {
|
||||
RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
You can also setup the whole context if necessary, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import io.restassured.module.mockmvc.RestAssuredMockMvc;
|
||||
import org.junit.Before;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
|
||||
public abstract class BaseTestClass {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext context;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
RestAssuredMockMvc.webAppContextSetup(this.context);
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use `EXPLICIT` mode, you can use a base class to initialize the whole tested app,
|
||||
similar to what you might do in regular integration tests. The following example shows
|
||||
how to do so:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.Before;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.web.server.LocalServerPort
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
|
||||
public abstract class BaseTestClass {
|
||||
|
||||
@LocalServerPort
|
||||
int port;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
RestAssured.baseURI = "http://localhost:" + this.port;
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
If you use the `JAXRSCLIENT` mode, this base class should also contain a `protected WebTarget webTarget` field. Right
|
||||
now, the only way to test the JAX-RS API is to start a web server.
|
||||
|
||||
[[maven-different-base]]
|
||||
== Using Different Base Classes for Contracts
|
||||
|
||||
If your base classes differ between contracts, you can tell the Spring Cloud Contract
|
||||
plugin which class should get extended by the autogenerated tests. You have two options:
|
||||
|
||||
* Follow a convention by providing a value for `packageWithBaseClasses`
|
||||
* Provide explicit mapping with `baseClassMappings`
|
||||
|
||||
=== By Convention
|
||||
|
||||
The convention is such that if you have a contract under (for example)
|
||||
`src/test/resources/contract/foo/bar/baz/` and set the value of the
|
||||
`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract
|
||||
Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package.
|
||||
In other words, the system takes the last two parts of the package, if they exist, and
|
||||
forms a class with a `Base` suffix. This rule takes precedence over `baseClassForTests`.
|
||||
The following example shows how it works in the `contracts` closure:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[tags=convention,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
=== By Mapping
|
||||
|
||||
You can manually map a regular expression of the contract's package to the fully qualified
|
||||
name of the base class for the matched contract. You have to provide a list called
|
||||
`baseClassMappings` that consists of `baseClassMapping` objects that each take a
|
||||
`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-baseclass-from-mappings/pom.xml[tags=mapping,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
Assume that you have contracts under these two locations:
|
||||
* `src/test/resources/contract/com/`
|
||||
* `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
|
||||
|
||||
The Spring Cloud Contract Maven Plugin generates verification code in a directory called
|
||||
`/generated-test-sources/contractVerifier` and attaches this directory to `testCompile`
|
||||
goal.
|
||||
|
||||
For Groovy Spock code, you can use the following:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<testSources>
|
||||
<testSource>
|
||||
<directory>${project.basedir}/src/test/groovy</directory>
|
||||
<includes>
|
||||
<include>**/*.groovy</include>
|
||||
</includes>
|
||||
</testSource>
|
||||
<testSource>
|
||||
<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
|
||||
<includes>
|
||||
<include>**/*.groovy</include>
|
||||
</includes>
|
||||
</testSource>
|
||||
</testSources>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
====
|
||||
|
||||
To ensure that the provider side is compliant with defined contracts, you need to invoke
|
||||
`mvn generateTest test`.
|
||||
|
||||
[[maven-pushing-stubs-to-scm]]
|
||||
== Pushing Stubs to SCM
|
||||
|
||||
If you use the SCM (Source Control Management) repository to keep the contracts and
|
||||
stubs, you might want to automate the step of pushing stubs to
|
||||
the repository. To do that, you can add the `pushStubsToScm`
|
||||
goal. The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- Base class mappings etc. -->
|
||||
|
||||
<!-- We want to pick contracts from a Git repository -->
|
||||
<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
|
||||
|
||||
<!-- We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts -->
|
||||
<contractDependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>${project.artifactId}</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</contractDependency>
|
||||
|
||||
<!-- The contracts mode can't be classpath -->
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<!-- By default we will not push the stubs back to SCM,
|
||||
you have to explicitly add it as a goal -->
|
||||
<goal>pushStubsToScm</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
----
|
||||
====
|
||||
|
||||
Under <<scm-stub-downloader>>, you can find all possible
|
||||
configuration options that you can pass through
|
||||
the `<configuration><contractProperties>` map, a system property,
|
||||
or an environment variable.
|
||||
|
||||
[[maven-sts]]
|
||||
== Maven Plugin and STS
|
||||
|
||||
The following image shows an exception that you may see when you use STS:
|
||||
|
||||
image::{github-raw}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception]
|
||||
|
||||
When you click on the error marker you should see something like the following:
|
||||
|
||||
====
|
||||
[source,bash]
|
||||
----
|
||||
plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
|
||||
cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
|
||||
org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
|
||||
...
|
||||
org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
|
||||
org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
|
||||
org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
|
||||
----
|
||||
====
|
||||
|
||||
In order to fix this issue, provide the following section in your `pom.xml`:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<!--This plugin's configuration is used to store Eclipse m2e settings
|
||||
only. It has no influence on the Maven build itself. -->
|
||||
<plugin>
|
||||
<groupId>org.eclipse.m2e</groupId>
|
||||
<artifactId>lifecycle-mapping</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<configuration>
|
||||
<lifecycleMappingMetadata>
|
||||
<pluginExecutions>
|
||||
<pluginExecution>
|
||||
<pluginExecutionFilter>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<versionRange>[1.0,)</versionRange>
|
||||
<goals>
|
||||
<goal>convert</goal>
|
||||
</goals>
|
||||
</pluginExecutionFilter>
|
||||
<action>
|
||||
<execute />
|
||||
</action>
|
||||
</pluginExecution>
|
||||
</pluginExecutions>
|
||||
</lifecycleMappingMetadata>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
----
|
||||
====
|
||||
|
||||
== Maven Plugin with Spock Tests
|
||||
|
||||
You can select the http://spockframework.org/[Spock Framework] for creating and running the auto-generated contract
|
||||
verification tests with both Maven and Gradle. However, whereas using Gradle is straightforward,
|
||||
in Maven, you will require some additional setup in order to make the tests compile and execute properly.
|
||||
|
||||
First of all, you must use a plugin, such as the https://github.com/groovy/GMavenPlus[GMavenPlus] plugin,
|
||||
to add Groovy to your project. In GMavenPlus plugin, you need to explicitly set test sources, including both the
|
||||
path where your base test classes are defined and the path were the generated contract tests are added.
|
||||
The following example shows how to do so:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{samples_url}/producer_with_spock/pom.xml[tags=gmavenplus-setup,indent=0]
|
||||
----
|
||||
====
|
||||
|
||||
If you uphold the Spock convention of ending the test class names with `Spec`, you also need to adjust your Maven
|
||||
Surefire plugin setup, as the following example shows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{samples_url}/producer_with_spock/pom.xml[tags=spock-surefire-setup,indent=0]
|
||||
----
|
||||
====
|
||||
@@ -1,180 +0,0 @@
|
||||
:core_path: ../../../..
|
||||
:doc_samples: {core_path}/samples/wiremock-jetty
|
||||
:wiremock_tests: {core_path}/spring-cloud-contract-wiremock
|
||||
|
||||
== Migrations
|
||||
|
||||
TIP: For up to date migration guides please visit
|
||||
the project's https://github.com/spring-cloud/spring-cloud-contract/wiki/[wiki page].
|
||||
|
||||
This section covers migrating from one version of Spring Cloud Contract Verifier to the
|
||||
next version. It covers the following versions upgrade paths:
|
||||
|
||||
[[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 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)
|
||||
----
|
||||
|
||||
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)
|
||||
----
|
||||
|
||||
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
|
||||
----
|
||||
<!-- start of pom.xml -->
|
||||
|
||||
<properties>
|
||||
<!-- we don't want the verifier to do a jar for us -->
|
||||
<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
|
||||
</properties>
|
||||
|
||||
<!-- ... -->
|
||||
|
||||
<!-- You need to set up the assembly plugin -->
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>stub</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<inherited>false</inherited>
|
||||
<configuration>
|
||||
<attach>true</attach>
|
||||
<descriptor>${basedir}/src/assembly/stub.xml</descriptor>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<!-- end of pom.xml -->
|
||||
|
||||
<!-- start of stub.xml-->
|
||||
|
||||
<assembly
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
|
||||
<id>stubs</id>
|
||||
<formats>
|
||||
<format>jar</format>
|
||||
</formats>
|
||||
<includeBaseDirectory>false</includeBaseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${project.build.directory}/snippets/stubs</directory>
|
||||
<outputDirectory>customer-stubs/mappings</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>${basedir}/src/test/resources/contracts</directory>
|
||||
<outputDirectory>customer-stubs/contracts</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*.groovy</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
</assembly>
|
||||
|
||||
<!-- end of stub.xml-->
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') {
|
||||
// Preserve directory structure from 1.0.X of spring-cloud-contract
|
||||
from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}"
|
||||
into "${project.buildDir}/resources/main/customer-stubs"
|
||||
}
|
||||
----
|
||||
|
||||
[[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`
|
||||
|
||||
`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:
|
||||
|
||||
* Set `basePackageForTests`
|
||||
* If `basePackageForTests` was not set, pick the package from `baseClassForTests`
|
||||
* If `baseClassForTests` was not set, pick `packageWithBaseClasses`
|
||||
* If nothing got set, pick the default value:
|
||||
`org.springframework.cloud.contract.verifier.tests`
|
||||
|
||||
See https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260] for more
|
||||
detail.
|
||||
|
||||
==== New Methods in TemplateProcessor
|
||||
|
||||
In order to add support for `fromRequest.path`, the following methods had to be added to the
|
||||
`TemplateProcessor` interface:
|
||||
|
||||
* `path()`
|
||||
* `path(int index)`
|
||||
|
||||
See 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
|
||||
40
docs/src/main/asciidoc/project-features.adoc
Normal file
40
docs/src/main/asciidoc/project-features.adoc
Normal file
@@ -0,0 +1,40 @@
|
||||
[[features]]
|
||||
= Spring Cloud Contract Features
|
||||
include::_attributes.adoc[]
|
||||
|
||||
This section dives into the details of {project-full-name}. Here you can learn about the key
|
||||
features that you may want to use and customize. If you have not already done so, you
|
||||
might want to read the "<<getting-started.adoc#getting-started>>" and
|
||||
"<<using.adoc#using>>" sections, so that you have a good grounding of the
|
||||
basics.
|
||||
|
||||
include::_project-features-contract.adoc[]
|
||||
|
||||
include::_project-features-flows.adoc[]
|
||||
|
||||
include::_project-features-messaging.adoc[]
|
||||
|
||||
include::_project-features-stubrunner.adoc[]
|
||||
|
||||
include::_project-features-wiremock.adoc[]
|
||||
|
||||
[[features-build-tools]]
|
||||
== Build Tools Integration
|
||||
|
||||
You can run test generation and stub execution in various ways. The most common ones are
|
||||
as follows:
|
||||
|
||||
* link:maven-project.html[Maven]
|
||||
* link:gradle-project.html[Gradle]
|
||||
* link:docker-project.html[Docker]
|
||||
|
||||
[[features-whats-next]]
|
||||
== What to Read Next
|
||||
|
||||
If you want to learn more about any of the classes discussed in this section, you can browse the
|
||||
{github-code}[source code directly]. If you have specific questions, see the
|
||||
<<howto.adoc#howto, how-to>> section.
|
||||
|
||||
If you are comfortable with {project-full-name}'s core features, you can continue on and read
|
||||
about
|
||||
<<advanced.adoc, {project-full-name}'s advanced features>>.
|
||||
@@ -1,8 +1,15 @@
|
||||
Add Sleuth to your classpath:
|
||||
== Adding Sleuth to Your Classpath:
|
||||
|
||||
Maven
|
||||
This section details how to add Sleuth to your class path for both Maven and Gradle
|
||||
|
||||
```xml
|
||||
=== Maven
|
||||
|
||||
To add Sleuth to your classpath with Maven, add the following elements
|
||||
to your `pom.xml` file:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
@@ -20,11 +27,17 @@ Maven
|
||||
<artifactId>spring-cloud-starter-sleuth</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
```
|
||||
----
|
||||
====
|
||||
|
||||
Gradle
|
||||
=== Gradle
|
||||
|
||||
```groovy
|
||||
To add Sleuth to your classpath with Gradle, add the following
|
||||
to your `build.gradle` file:
|
||||
|
||||
====
|
||||
[src,groovy]
|
||||
----
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath "io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE"
|
||||
@@ -41,11 +54,15 @@ dependencyManagement {
|
||||
dependencies {
|
||||
compile 'org.springframework.cloud:spring-cloud-starter-sleuth'
|
||||
}
|
||||
```
|
||||
----
|
||||
====
|
||||
|
||||
As long as Spring Cloud Sleuth is on the classpath any Spring Boot application will generate trace data:
|
||||
As long as Spring Cloud Sleuth is on the classpath, any Spring Boot application can
|
||||
generate trace data. The following example shows how to do so:
|
||||
|
||||
```java
|
||||
====
|
||||
[src,java]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@RestController
|
||||
public class Application {
|
||||
@@ -63,12 +80,21 @@ public class Application {
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
----
|
||||
====
|
||||
|
||||
Run this app and then hit the home page. You will see traceId and spanId populated in the logs. If this app calls out to another one (e.g. with `RestTemplate`) it will send the trace data in headers and if the receiver is another Sleuth app you will see the trace continue there.
|
||||
Now you can run this application and visit the home page. In the logs, you can see
|
||||
`traceId` and `spanId` populated. If this application calls out to another one (for
|
||||
example, with `RestTemplate`), it sends the trace data in headers, and, if the receiver is
|
||||
another Sleuth application, you can see the trace continue there.
|
||||
|
||||
IMPORTANT: instead of logging the request in the handler explicitly, you could set `logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG`
|
||||
IMPORTANT: instead of logging the request in the handler explicitly, you could set
|
||||
`logging.level.org.springframework.web.servlet.DispatcherServlet=DEBUG`
|
||||
|
||||
IMPORTANT: If you use Zipkin, configure the probability of spans exported by setting (for `2.0.x`) `spring.sleuth.sampler.probability` or (up till `2.0.x`)`spring.sleuth.sampler.percentage` (default: 0.1, which is 10 percent). Otherwise, you might think that Sleuth is not working because it omits some spans.
|
||||
IMPORTANT: If you use Zipkin, you can configure the probability of spans being exported by
|
||||
setting (for `2.0.x`) `spring.sleuth.sampler.probability` or (up till `2.0.x`)
|
||||
`spring.sleuth.sampler.percentage` (default: 0.1, which is 10 percent). Otherwise, you
|
||||
might think that Sleuth is not working because it omits some spans.
|
||||
|
||||
IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as well as the trace and span ids.
|
||||
IMPORTANT: Set `spring.application.name=bar` (for instance) to see the service name as
|
||||
well as the trace and span IDs.
|
||||
|
||||
@@ -1,12 +1,30 @@
|
||||
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing heavily from https://research.google.com/pubs/pub36356.html[Dapper], https://github.com/openzipkin/zipkin[Zipkin] and HTrace. For most users Sleuth should be invisible, and all your interactions with external systems should be instrumented automatically. You can capture data simply in logs, or by sending it to a remote collector service.
|
||||
Spring Cloud Sleuth implements a distributed tracing solution for Spring Cloud, borrowing
|
||||
heavily from https://research.google.com/pubs/pub36356.html[Dapper],
|
||||
https://github.com/openzipkin/zipkin[Zipkin], and HTrace. For most users, Sleuth should be
|
||||
invisible, and all your interactions with external systems should be instrumented
|
||||
automatically. You can capture data in logs or by sending it to a remote collector service.
|
||||
|
||||
## Features
|
||||
|
||||
A Span is the basic unit of work. For example, sending an RPC is a new span, as is sending a response to an RPC. Span’s are identified by a unique 64-bit ID for the span and another 64-bit ID for the trace the span is a part of. Spans also have other data, such as descriptions, key-value annotations, the ID of the span that caused them, and process ID’s (normally IP address). Spans are started and stopped, and they keep track of their timing information. Once you create a span, you must stop it at some point in the future. A set of spans forming a tree-like structure called a Trace. For example, if you are running a distributed big-data store, a trace might be formed by a put request.
|
||||
A span is the basic unit of work. For example, sending an RPC is a new span, as is sending
|
||||
a response to an RPC. Spans are identified by a unique 64-bit ID for the span and another
|
||||
64-bit ID for the trace of which the span is a part. Spans also have other data, such as
|
||||
descriptions, key-value annotations, the ID of the span that caused them, and process IDs
|
||||
(normally IP addresses). Spans are started and stopped, and they keep track of their
|
||||
timing information. Once you create a span, you must stop it at some point in the future.
|
||||
A set of spans (which form a tree-like structure) is called a trace. For example, if you
|
||||
run a distributed big-data store, a trace might be formed by a `PUT` request.
|
||||
|
||||
Spring Cloud Sleuth features:
|
||||
Spring Cloud Sleuth:
|
||||
|
||||
* Adds trace and span ids to the Slf4J MDC, so you can extract all the logs from a given trace or span in a log aggregator.
|
||||
* Provides an abstraction over common distributed tracing data models: traces, spans (forming a DAG), annotations, key-value annotations. Loosely based on HTrace, but Zipkin (Dapper) compatible.
|
||||
* Instruments common ingress and egress points from Spring applications (servlet filter, rest template, scheduled actions, message channels, zuul filters, feign client).
|
||||
* If `spring-cloud-sleuth-zipkin` is available then the app will generate and collect Zipkin-compatible traces via HTTP. By default it sends them to a Zipkin collector service on localhost (port 9411). Configure the location of the service using `spring.zipkin.baseUrl`.
|
||||
* Adds trace and span IDs to the Slf4J MDC so that you can extract all the logs from a
|
||||
given trace or span in a log aggregator.
|
||||
* Provides an abstraction over common distributed tracing data models: traces, spans
|
||||
(forming a DAG), annotations, and key-value annotations. This is loosely based on HTrace
|
||||
but is Zipkin (Dapper) compatible.
|
||||
* Instruments common ingress and egress points from Spring applications (servlet filter,
|
||||
rest template, scheduled actions, message channels, zuul filters, and the feign client).
|
||||
* If `spring-cloud-sleuth-zipkin` is available, the app generates and collects
|
||||
Zipkin-compatible traces over HTTP. By default, it sends them to a Zipkin collector
|
||||
service on localhost (port 9411). You can configure the location of the service using
|
||||
`spring.zipkin.baseUrl`.
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
:toc: left
|
||||
:toclevels: 3
|
||||
:nofooter:
|
||||
:source-highlighter: prettify
|
||||
:numbered:
|
||||
:icons: font
|
||||
:sectlinks: true
|
||||
:branch: master
|
||||
|
||||
= 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, Jay Bryant_
|
||||
|
||||
{spring-cloud-version}
|
||||
|
||||
== Spring Cloud Contract
|
||||
|
||||
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[]
|
||||
|
||||
include::spring-cloud-wiremock.adoc[]
|
||||
|
||||
include::migrations.adoc[]
|
||||
|
||||
include::links.adoc[]
|
||||
@@ -1,399 +0,0 @@
|
||||
:core_path: ../../..
|
||||
:doc_samples: {core_path}/samples/wiremock-jetty
|
||||
:wiremock_tests: {core_path}/spring-cloud-contract-wiremock
|
||||
|
||||
== Spring Cloud Contract WireMock
|
||||
|
||||
The Spring Cloud Contract WireMock modules let you use https://github.com/tomakehurst/wiremock[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 (which is
|
||||
the default with `spring-boot-starter-web`), you can add
|
||||
`spring-cloud-starter-contract-stub-runner` to your classpath and add `@AutoConfigureWireMock` in
|
||||
order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you
|
||||
can register stub behavior using a Java API or via static JSON declarations as part of
|
||||
your test. The following code shows an example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test1]
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2]
|
||||
----
|
||||
|
||||
To start the stub server on a different port use (for example),
|
||||
`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub
|
||||
server port can be bound in the test application context with the "wiremock.server.port"
|
||||
property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to
|
||||
your test application context, where it will be cached in between methods and classes
|
||||
having the same context, the same as for Spring integration tests. Also you can inject a bean of type `WireMockServer` into your test.
|
||||
|
||||
=== Registering Stubs Automatically
|
||||
|
||||
If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file
|
||||
system or classpath (by default, from `file:src/test/resources/mappings`). You can
|
||||
customize the locations using the `stubs` attribute in the annotation, which can be an
|
||||
Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is
|
||||
appended. The following code shows an example:
|
||||
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureWireMock(stubs="classpath:/stubs")
|
||||
public class WiremockImportApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private Service service;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
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.
|
||||
|
||||
If you're using Spring Cloud Contract's default stub jars, then your
|
||||
stubs are stored under `/META-INF/group-id/artifact-id/versions/mappings/` folder. If you want to register all stubs from that location, from all embedded JARs, then it's enough to use the following syntax.
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockFilesApplicationWithUrlResourceTests.java[tags=load_all_stubs]
|
||||
----
|
||||
|
||||
=== Using Files to Specify the Stub Bodies
|
||||
|
||||
WireMock can read response bodies from files on the classpath or the file system. In that
|
||||
case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a
|
||||
(literal) `body`. The files are resolved relative to a root directory (by default,
|
||||
`src/test/resources/\__files`). To customize this location you can set the `files`
|
||||
attribute in the `@AutoConfigureWireMock` annotation to the location of the parent
|
||||
directory (in other words, `__files` is a subdirectory). You can use Spring resource
|
||||
notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not
|
||||
supported. A list of values can be given, in which case WireMock resolves the first file
|
||||
that exists when it needs to find a response body.
|
||||
|
||||
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, you can use JUnit `@Rules` to start and stop
|
||||
the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options`
|
||||
instance, as shown in the following example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test1]
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2]
|
||||
----
|
||||
|
||||
The `@ClassRule` means that the server shuts down after all the methods in this class
|
||||
have been run.
|
||||
|
||||
=== Relaxed SSL Validation for Rest Template
|
||||
|
||||
WireMock lets you stub a "secure" server with an "https" URL protocol. If your
|
||||
application wants to contact that stub server in an integration test, it will find that
|
||||
the SSL certificates are not valid (the usual problem with self-installed certificates).
|
||||
The best option is often to re-configure the client to use "http". If that's not an
|
||||
option, you can ask Spring to configure an HTTP client that ignores SSL validation errors
|
||||
(do so only for tests, of course).
|
||||
|
||||
To make this work with minimum fuss, you need to be using the Spring Boot
|
||||
`RestTemplateBuilder` in your app, as shown in the following example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Bean
|
||||
public RestTemplate restTemplate(RestTemplateBuilder builder) {
|
||||
return builder.build();
|
||||
}
|
||||
----
|
||||
|
||||
You need `RestTemplateBuilder` because the builder is passed through callbacks to
|
||||
initialize it, so the SSL validation can be set up in the client at that point. This
|
||||
happens automatically in your test if you are using the `@AutoConfigureWireMock`
|
||||
annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the
|
||||
`@AutoConfigureHttpClient` annotation as well, as shown in the following example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest("app.baseUrl=https://localhost:6443")
|
||||
@AutoConfigureHttpClient
|
||||
public class WiremockHttpsServerApplicationTests {
|
||||
|
||||
@ClassRule
|
||||
public static WireMockClassRule wiremock = new WireMockClassRule(
|
||||
WireMockSpring.options().httpsPort(6443));
|
||||
...
|
||||
}
|
||||
----
|
||||
|
||||
If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the
|
||||
classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL
|
||||
errors. If you use the default `java.net` client, you do not need the annotation (but it
|
||||
won't do any harm). There is no support currently for other clients, but it may be added
|
||||
in future releases.
|
||||
|
||||
To disable the custom `RestTemplateBuilder`, set the `wiremock.rest-template-ssl-enabled`
|
||||
property to `false`.
|
||||
|
||||
=== WireMock and Spring MVC Mocks
|
||||
|
||||
Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
|
||||
a Spring `MockRestServiceServer`. The following code shows an example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test]
|
||||
----
|
||||
|
||||
The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub
|
||||
path resource pattern as an argument. In the preceding example, the stub defined at
|
||||
`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to
|
||||
visit `https://example.org/`, it gets the responses as being declared at that URL. More
|
||||
than one stub pattern can be specified, and each one can be a directory (for a recursive
|
||||
list of all ".json"), a fixed filename (as in the example above), or an Ant-style
|
||||
pattern. The JSON format is the normal WireMock format, which you can read about in the
|
||||
https://wiremock.org/docs/stubbing/[WireMock website].
|
||||
|
||||
Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as
|
||||
Spring Boot embedded servers, and Wiremock itself has "native" support for a particular
|
||||
version of Jetty (currently 9.2). To use the native Jetty, you need to add the native
|
||||
Wiremock dependencies and exclude the Spring Boot container (if there is one).
|
||||
|
||||
=== Customization of WireMock configuration
|
||||
|
||||
You can register a bean of `org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer` type
|
||||
in order to customize the WireMock configuration (e.g. add custom transformers).
|
||||
Example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_1]
|
||||
// perform your customization here
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/AutoConfigureWireMockConfigurationCustomizerTests.java[tags=customizer_2]
|
||||
----
|
||||
|
||||
=== 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 `WebTestClient` or Rest Assured. At the same time that you generate documentation for your API, you can also
|
||||
generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your
|
||||
normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be
|
||||
automatically generated in the REST Docs output directory. The following code shows an
|
||||
example using `MockMvc`:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureMockMvc
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(get("/resource"))
|
||||
.andExpect(content().string("Hello World"))
|
||||
.andDo(document("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches
|
||||
all GET requests to the "/resource" path. The same example with `WebTestClient` (used
|
||||
for testing Spring WebFlux applications) would look like this:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureWebTestClient
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private WebTestClient client;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
client.get().uri("/resource").exchange()
|
||||
.expectBody(String.class).isEqualTo("Hello World")
|
||||
.consumeWith(document("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
Without any additional configuration, these tests create a stub with a request matcher
|
||||
for the HTTP method and all headers except "host" and "content-length". To match the
|
||||
request more precisely (for example, to match the body of a POST or PUT), we need to
|
||||
explicitly create a request matcher. Doing so has two effects:
|
||||
|
||||
* Creating a stub that matches only in the way you specify.
|
||||
* Asserting that the request in the test case also matches the same conditions.
|
||||
|
||||
The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used
|
||||
as a substitute for the `document()` convenience method, as shown in the following
|
||||
example:
|
||||
|
||||
[source,java,indent=0]
|
||||
|
||||
import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
|
||||
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||||
@AutoConfigureMockMvc
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(post("/resource")
|
||||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(verify().jsonPath("$.id")
|
||||
.stub("resource"));
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
This contract specifies that any valid POST with an "id" field receives the response
|
||||
defined in this test. You can chain together calls to `.jsonPath()` to add additional
|
||||
matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay
|
||||
documentation] can help you get up to speed. The `WebTestClient` version of this test
|
||||
has a similar `verify()` static helper that you insert in the same place.
|
||||
|
||||
Instead of the `jsonPath` and `contentType` convenience methods, you can also use the
|
||||
WireMock APIs to verify that the request matches the created stub, as shown in the
|
||||
following example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@Test
|
||||
public void contextLoads() throws Exception {
|
||||
mockMvc.perform(post("/resource")
|
||||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(verify()
|
||||
.wiremock(WireMock.post(
|
||||
urlPathEquals("/resource"))
|
||||
.withRequestBody(matchingJsonPath("$.id"))
|
||||
.stub("post-resource"));
|
||||
}
|
||||
----
|
||||
|
||||
The WireMock API is rich. You can match headers, query parameters, and request body by
|
||||
regex as well as by JSON path. These features can be used to create stubs with a wider
|
||||
range of parameters. The above example generates a stub resembling the following example:
|
||||
|
||||
.post-resource.json
|
||||
[source,json]
|
||||
----
|
||||
{
|
||||
"request" : {
|
||||
"url" : "/resource",
|
||||
"method" : "POST",
|
||||
"bodyPatterns" : [ {
|
||||
"matchesJsonPath" : "$.id"
|
||||
}]
|
||||
},
|
||||
"response" : {
|
||||
"status" : 200,
|
||||
"body" : "Hello World",
|
||||
"headers" : {
|
||||
"X-Application-Context" : "application:-1",
|
||||
"Content-Type" : "text/plain"
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
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 earlier in this section
|
||||
available on the classpath (by
|
||||
<<publishing-stubs-as-jars], for example). After that, you can create a stub using WireMock in a
|
||||
number of different ways, including by using
|
||||
`@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this
|
||||
document.
|
||||
|
||||
=== Generating Contracts by Using REST Docs
|
||||
|
||||
You can also generate Spring Cloud Contract DSL files and documentation with Spring REST
|
||||
Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts
|
||||
and the stubs.
|
||||
|
||||
Why would you want to use this feature? Some people in the community asked questions
|
||||
about a situation in which they would like to move to DSL-based contract definition,
|
||||
but they already have a lot of Spring MVC tests. Using this feature lets you generate
|
||||
the contract files that you can later modify and move to folders (defined in your
|
||||
configuration) so that the plugin finds them.
|
||||
|
||||
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.
|
||||
|
||||
Consider the following test:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet]
|
||||
----
|
||||
|
||||
The preceding test creates the stub presented in the previous section, generating both
|
||||
the contract and a documentation file.
|
||||
|
||||
The contract is called `index.groovy` and might look like the following example:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
import org.springframework.cloud.contract.spec.Contract
|
||||
|
||||
Contract.make {
|
||||
request {
|
||||
method 'POST'
|
||||
url '/foo'
|
||||
body('''
|
||||
{"foo": 23 }
|
||||
''')
|
||||
headers {
|
||||
header('''Accept''', '''application/json''')
|
||||
header('''Content-Type''', '''application/json''')
|
||||
}
|
||||
}
|
||||
response {
|
||||
status OK()
|
||||
body('''
|
||||
bar
|
||||
''')
|
||||
headers {
|
||||
header('''Content-Type''', '''application/json;charset=UTF-8''')
|
||||
header('''Content-Length''', '''3''')
|
||||
}
|
||||
testMatchers {
|
||||
jsonPath('$[?(@.foo >= 20)]', byType())
|
||||
}
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
The generated document (formatted in Asciidoc in this case) contains a formatted
|
||||
contract. The location of this file would be `index/dsl-contract.adoc`.
|
||||
875
docs/src/main/asciidoc/using.adoc
Normal file
875
docs/src/main/asciidoc/using.adoc
Normal file
@@ -0,0 +1,875 @@
|
||||
[[using]]
|
||||
= Using Spring Cloud Contract
|
||||
include::_attributes.adoc[]
|
||||
|
||||
This section goes into more detail about how you should use {project-full-name}. It covers topics
|
||||
such as flows of how to work with {project-full-name}. We also
|
||||
cover some {project-full-name} best practices.
|
||||
|
||||
If you are starting out with {project-full-name}, you should probably read the
|
||||
<<getting-started.adoc#getting-started, Getting Started>> guide before diving into this
|
||||
section.
|
||||
|
||||
[[flows-provider-nexus]]
|
||||
== Provider Contract Testing with Stubs in Nexus or Artifactory
|
||||
|
||||
You can check the <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> link to see the provider contract testing with stubs in the Nexus or Artifactory flow.
|
||||
|
||||
You can also check the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page] for a step-by-step instruction on how to do this flow.
|
||||
|
||||
[[flows-provider-git]]
|
||||
== Provider Contract Testing with Stubs in Git
|
||||
|
||||
In this flow, we perform the provider contract testing (the producer has no knowledge of how consumers use their API). The stubs are uploaded to a separate repository (they are not uploaded to Artifactory or Nexus).
|
||||
|
||||
=== Prerequisites
|
||||
|
||||
Before testing provider contracts with stubs in git, you must provide a git repository
|
||||
that contains all the stubs for each producer. For an example of such a project, see
|
||||
{samples_code}/contract_git[this samples ] or {samples_code}/contract_git[this sample].
|
||||
As a result of pushing stubs there, the repository has the following structure:
|
||||
|
||||
====
|
||||
[src, bash]
|
||||
----
|
||||
$ tree .
|
||||
└── META-INF
|
||||
└── folder.with.group.id.as.its.name
|
||||
└── folder-with-artifact-id
|
||||
└── folder-with-version
|
||||
├── contractA.groovy
|
||||
├── contractB.yml
|
||||
└── contractC.groovy
|
||||
|
||||
----
|
||||
====
|
||||
|
||||
You must also provide consumer code that has Spring Cloud Contract Stub Runner set up. For
|
||||
an example of such a project, see {samples_code}/consumer[this sample] and search for a
|
||||
`BeerControllerGitTest` test. You must also provide producer code that has Spring Cloud
|
||||
Contract set up, together with a plugin. For an example of such a project, see
|
||||
{samples_code}/producer_with_empty_git[this sample].
|
||||
|
||||
[[flows-provider-git-flow]]
|
||||
=== The Flow
|
||||
|
||||
The flow looks exactly as the one presented in
|
||||
<<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>>,
|
||||
but the `Stub Storage` implementation is a git repository.
|
||||
|
||||
You can read more about setting up a git repository and setting consumer and producer side
|
||||
in the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
|
||||
|
||||
[[flows-provider-git-consumer]]
|
||||
=== Consumer setup
|
||||
|
||||
In order to fetch the stubs from a git repository instead of Nexus or Artifactory, you
|
||||
need to use the `git` protocol in the URL of the `repositoryRoot` property in Stub Runner.
|
||||
The following example shows how to set it up:
|
||||
|
||||
====
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Annotation
|
||||
----
|
||||
@AutoConfigureStubRunner(
|
||||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||||
repositoryRoot = "git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
|
||||
ids = "com.example:artifact-id:0.0.1")
|
||||
----
|
||||
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.JUnit 4 Rule
|
||||
----
|
||||
@Rule
|
||||
public StubRunnerRule rule = new StubRunnerRule()
|
||||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
|
||||
----
|
||||
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.JUnit 5 Extension
|
||||
----
|
||||
@Rule
|
||||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
|
||||
----
|
||||
====
|
||||
|
||||
[[flows-provider-git-producer]]
|
||||
=== Setting up the Producer
|
||||
|
||||
In order to push the stubs to a git repository instead of Nexus or Artifactory, you need
|
||||
to use the `git` protocol in the URL of the plugin setup. Also you need to explicitly tell
|
||||
the plugin to push the stubs at the end of the build process. The following example shows
|
||||
how to do so:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,role="primary"]
|
||||
.maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- Base class mappings etc. -->
|
||||
|
||||
<!-- We want to pick contracts from a Git repository -->
|
||||
<contractsRepositoryUrl>git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
|
||||
|
||||
<!-- We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts -->
|
||||
<contractDependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>${project.artifactId}</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</contractDependency>
|
||||
|
||||
<!-- The contracts mode can't be classpath -->
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<!-- By default we will not push the stubs back to SCM,
|
||||
you have to explicitly add it as a goal -->
|
||||
<goal>pushStubsToScm</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,role="secondary"]
|
||||
.gradle
|
||||
----
|
||||
contracts {
|
||||
// We want to pick contracts from a Git repository
|
||||
contractDependency {
|
||||
stringNotation = "${project.group}:${project.name}:${project.version}"
|
||||
}
|
||||
/*
|
||||
We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts
|
||||
*/
|
||||
contractRepository {
|
||||
repositoryUrl = "git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
|
||||
}
|
||||
// The mode can't be classpath
|
||||
contractsMode = "REMOTE"
|
||||
// Base class mappings etc.
|
||||
}
|
||||
|
||||
/*
|
||||
In this scenario we want to publish stubs to SCM whenever
|
||||
the `publish` task is executed
|
||||
*/
|
||||
publish.dependsOn("publishStubsToScm")
|
||||
----
|
||||
====
|
||||
|
||||
You can read more about setting up a git repository in the
|
||||
<<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
|
||||
|
||||
[[flows-cdc-contracts-producer]]
|
||||
== Consumer Driven Contracts with Contracts on the Producer Side
|
||||
|
||||
See <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven
|
||||
Contracts (CDC) with Contracts on the Producer Side>> to see the Consumer Driven Contracts
|
||||
with contracts on the producer side flow.
|
||||
|
||||
[[flows-cdc-contracts-external]]
|
||||
== Consumer Driven Contracts with Contracts in an External Repository
|
||||
|
||||
In this flow, we perform Consumer Driven Contract testing. The contract definitions are
|
||||
stored in a separate repository.
|
||||
|
||||
See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html[workshop page]
|
||||
for step-by-step instructions on how to do this flow.
|
||||
|
||||
=== Prerequisites
|
||||
|
||||
To use consumer-driven contracts with the contracts held in an external repository, you need to set up a git repository that:
|
||||
|
||||
* Contains all the contract definitions for each producer.
|
||||
* Can package the contract definitions in a JAR.
|
||||
* For each contract producer, contains a way (for example, `pom.xml`) to install stubs
|
||||
locally through the Spring Cloud Contract Plugin (SCC Plugin)
|
||||
|
||||
For more information, see the <<howto.adoc#how-to-common-repo-with-contracts, How To section>>,
|
||||
where we describe how to set up such a repository
|
||||
For an example of such a project, see {samples_code}/beer_contracts[this sample].
|
||||
|
||||
You also need consumer code that has Spring Cloud Contract Stub Runner set up.
|
||||
For an example of such a project, see {samples_code}/consumer[this sample].
|
||||
You also need producer code that has Spring Cloud Contract set up, together with a plugin.
|
||||
For an example of such a project, see {samples_code}/producer_with_external_contracts[this sample].
|
||||
The stub storage is Nexus or Artifactory
|
||||
|
||||
At a high level, the flow looks as follows:
|
||||
|
||||
. The consumer works with the contract definitions from the separate repository
|
||||
. Once the consumer's work is done, a branch with working code is done on the consumer
|
||||
side and a pull request is made to the separate repository that holds the contract definitions.
|
||||
. The producer takes over the pull request to the separate repository with contract
|
||||
definitions and installs the JAR with all contracts locally.
|
||||
. The producer generates tests from the locally stored JAR and writes the missing
|
||||
implementation to make the tests pass.
|
||||
. Once the producer's work is done, the pull request to the repository that holds the
|
||||
contract definitions is merged.
|
||||
. After the CI tool builds the repository with the contract definitions and the JAR with
|
||||
contract definitions gets uploaded to Nexus or Artifactory, the producer can merge its branch.
|
||||
. Finally, the consumer can switch to working online to fetch stubs of the producer from a
|
||||
remote location, and the branch can be merged to master.
|
||||
|
||||
[[flows-cdc-contracts-external-consumer]]
|
||||
=== Consumer Flow
|
||||
|
||||
The consumer:
|
||||
|
||||
. Writes a test that would send a request to the producer.
|
||||
+
|
||||
The test fails due to no server being present.
|
||||
. Clones the repository that holds the contract definitions.
|
||||
. Set up the requirements as contracts under the folder with the consumer name as a subfolder of the producer.
|
||||
+
|
||||
For example, for a producer named `producer` and a consumer named `consumer`, the contracts would be stored under `src/main/resources/contracts/producer/consumer/`)
|
||||
. Once the contracts are defined, installs the producer stubs to local storage, as the following example shows:
|
||||
+
|
||||
====
|
||||
[src,bash]
|
||||
----
|
||||
$ cd src/main/resource/contracts/producer
|
||||
$ ./mvnw clean install
|
||||
----
|
||||
====
|
||||
. Sets up Spring Cloud Contract (SCC) Stub Runner in the consumer tests, to:
|
||||
* Fetch the producer stubs from local storage.
|
||||
* Work in the stubs-per-consumer mode (this enables consumer driven contracts mode).
|
||||
+
|
||||
The SCC Stub Runner:
|
||||
* Fetches the producer stubs.
|
||||
* Runs an in-memory HTTP server stub with the producer stubs.
|
||||
* Now your test communicates with the HTTP server stub and your tests pass
|
||||
* Create a pull request to the repository with contract definitions, with the new contracts for the producer
|
||||
* Branch your consumer code, until the producer team has merged their code
|
||||
|
||||
The following UML diagram shows the consumer flow:
|
||||
|
||||
[plantuml, flow-overview-consumer-cdc-external-consumer, png]
|
||||
----
|
||||
"Consumer"->"Repo\nwith\ncontracts": clone
|
||||
"Repo\nwith\ncontracts"->"Repo\nwith\ncontracts\nclone": cloned
|
||||
"Consumer"->"Repo\nwith\ncontracts\nclone": create contract\ndefinitions of\nthe [Producer]
|
||||
"Repo\nwith\ncontracts\nclone"->"Local storage": install [Producer]\nstubs locally
|
||||
"Consumer"->"Consumer\nBuild": run tests
|
||||
"Consumer\nBuild"->"SCC\nStub Runner": Run [Producer] stubs
|
||||
"SCC\nStub Runner"->"Local storage": fetch [Producer] stubs
|
||||
"SCC\nStub Runner"->"Producer stub": stub is running
|
||||
"Consumer\nBuild"->"Producer stub": send a request\nin the tests
|
||||
"Producer stub"->"Consumer\nBuild": send a response
|
||||
"Consumer\nBuild"->"Consumer": the tests are passing
|
||||
"Consumer"->"Repo\nwith\ncontracts\nclone": send a pull request
|
||||
"Repo\nwith\ncontracts\nclone"->"Repo\nwith\ncontracts": pull request sent
|
||||
"Consumer"->"Consumer": branch the code
|
||||
----
|
||||
|
||||
[[flows-cdc-contracts-external-producer]]
|
||||
=== Producer Flow
|
||||
|
||||
The producer:
|
||||
|
||||
. Takes over the pull request to the repository with contract definitions. You can do it
|
||||
from the command line, as follows
|
||||
+
|
||||
====
|
||||
[src,bash]
|
||||
----
|
||||
$ git checkout -b the_branch_with_pull_request master
|
||||
git pull https://github.com/user_id/project_name.git the_branch_with_pull_request
|
||||
----
|
||||
====
|
||||
. Installs the contract definitions, as follows
|
||||
+
|
||||
====
|
||||
[src,bash]
|
||||
----
|
||||
$ ./mvnw clean install
|
||||
----
|
||||
====
|
||||
. Sets up the plugin to fetch the contract definitions from a JAR instead of from
|
||||
`src/test/resources/contracts`, as follows:
|
||||
+
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- We want to use the JAR with contracts with the following coordinates -->
|
||||
<contractDependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>beer-contracts</artifactId>
|
||||
</contractDependency>
|
||||
<!-- The JAR with contracts should be taken from Maven local -->
|
||||
<contractsMode>LOCAL</contractsMode>
|
||||
<!-- ... additional configuration -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
contracts {
|
||||
// We want to use the JAR with contracts with the following coordinates
|
||||
// group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
|
||||
contractDependency {
|
||||
stringNotation = 'com.example:beer-contracts:+:'
|
||||
}
|
||||
// The JAR with contracts should be taken from Maven local
|
||||
contractsMode = "LOCAL"
|
||||
// Additional configuration
|
||||
}
|
||||
----
|
||||
====
|
||||
. Runs the build to generate tests and stubs, as follows:
|
||||
+
|
||||
====
|
||||
[source,bash,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
./mvnw clean install
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
./gradlew clean build
|
||||
----
|
||||
====
|
||||
. Writes the missing implementation, to make the tests pass.
|
||||
. Merges the pull request to the repository with contract definitions, as follows:
|
||||
+
|
||||
====
|
||||
[src,bash]
|
||||
----
|
||||
$ git commit -am "Finished the implementation to make the contract tests pass"
|
||||
$ git checkout master
|
||||
$ git merge --no-ff the_branch_with_pull_request
|
||||
$ git push origin master
|
||||
----
|
||||
====
|
||||
. The CI system builds the project with the contract definitions and uploads the JAR with
|
||||
the contract definitions to Nexus or Artifactory.
|
||||
. Switches to working remotely.
|
||||
. Sets up the plugin so that the contract definitions are no longer taken from the local
|
||||
storage but from a remote location, as follows:
|
||||
+
|
||||
====
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- We want to use the JAR with contracts with the following coordinates -->
|
||||
<contractDependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>beer-contracts</artifactId>
|
||||
</contractDependency>
|
||||
<!-- The JAR with contracts should be taken from a remote location -->
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
<!-- ... additional configuration -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
contracts {
|
||||
// We want to use the JAR with contracts with the following coordinates
|
||||
// group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
|
||||
contractDependency {
|
||||
stringNotation = 'com.example:beer-contracts:+:'
|
||||
}
|
||||
// The JAR with contracts should be taken from a remote location
|
||||
contractsMode = "REMOTE"
|
||||
// Additional configuration
|
||||
}
|
||||
----
|
||||
====
|
||||
. Merges the producer code with the new implementation.
|
||||
. The CI system:
|
||||
* Builds the project
|
||||
* Generates tests, stubs, and the stub JAR
|
||||
* Uploads the artifact with the application and the stubs to Nexus or Artifactory.
|
||||
|
||||
The following UML diagram shows the producer process:
|
||||
|
||||
[plantuml, flow-overview-consumer-cdc-external-producer, png]
|
||||
----
|
||||
"Producer"->"Repo\nwith\ncontracts": take over the pull request
|
||||
"Producer"->"Repo\nwith\ncontracts": install the contract\ndefinitions JAR
|
||||
"Repo\nwith\ncontracts"->"Local storage": install the\ncontract definitions\nJAR locally
|
||||
"Local storage"->"Repo\nwith\ncontracts": contract definitions\nJAR installed
|
||||
"Producer"->"Producer\nBuild": run build
|
||||
"Producer\nBuild"->"SCC\nPlugin": generate tests,\nstubs\nand stub jar
|
||||
"SCC\nPlugin"->"Local storage": fetch the contract definitions
|
||||
"Local storage"->"SCC\nPlugin": contract definitions found
|
||||
"SCC\nPlugin"->"SCC\nPlugin": generate tests
|
||||
"Producer\nBuild"->"Producer\nBuild": run the\ngenerated tests
|
||||
"Producer\nBuild"->"Producer": the tests failed to pass
|
||||
"Producer"->"Producer": write the missing implementation
|
||||
"Producer"->"Producer\nBuild": run the build again
|
||||
"Producer\nBuild"->"Producer\nBuild": fetch the contract definitions\nrun the generated tests
|
||||
"Producer\nBuild"->"Producer": the tests passed
|
||||
"Producer"->"Repo\nwith\ncontracts": merge the pull request
|
||||
"Repo\nwith\ncontracts"->"CI": build and upload the\ncontract definitions artifact
|
||||
"CI"->"Stub Storage": upload the\ncontract definitions
|
||||
"Producer"->"Producer": setup the SCC Plugin\nto work remotely
|
||||
"Producer"->"Producer": merge the code\nwith the implementation
|
||||
"Producer"->"CI": build and upload\nthe artifacts
|
||||
"CI"->"Producer\nBuild\non CI": generate tests,\nstubs\nand stub jar
|
||||
"Producer\nBuild\non CI"->"SCC\nPlugin": generate tests,\nstubs\nand stub jar
|
||||
"SCC\nPlugin"->"Stub Storage": fetch the contract definitions
|
||||
"Stub Storage"->"SCC\nPlugin": contract definitions found
|
||||
"SCC\nPlugin"->"SCC\nPlugin": generate tests
|
||||
"Producer\nBuild\non CI"->"CI": the build passed
|
||||
"Producer\nBuild\non CI"->"Stub Storage": upload the application JAR\nand the stubs jar
|
||||
----
|
||||
|
||||
[[flows-cdc-contracts-stubs-git]]
|
||||
== Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git
|
||||
|
||||
You can check <<getting-started.adoc#getting-started-cdc, Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side>> to see the consumer driven contracts with contracts on the producer side flow.
|
||||
|
||||
The stub storage implementation is a git repository. We describe its setup in the
|
||||
<<flows-provider-git>> section.
|
||||
|
||||
You can read more about setting up a git repository for the consumer and producer sides in
|
||||
the <<howto.adoc#how-to-use-git-as-storage,How To page>> of the documentation.
|
||||
|
||||
[[flows-provider-non-spring]]
|
||||
== Provider Contract Testing with Stubs in Artifactory for a non-Spring Application
|
||||
|
||||
[[flows-provider-non-spring-flow]]
|
||||
=== The Flow
|
||||
|
||||
You can check <<getting-started.adoc#getting-started-first-application, Developing Your First Spring Cloud Contract based application>> to see the flow for provider contract testing with stubs in Nexus or Artifactory.
|
||||
|
||||
[[flows-provider-non-spring-consumer]]
|
||||
=== Setting up the Consumer
|
||||
|
||||
For the consumer side, you can use a JUnit rule. That way, you need not start a Spring context. The follwoing listing shows such a rule (in JUnit4 and JUnit 5);
|
||||
|
||||
====
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.JUnit 4 Rule
|
||||
----
|
||||
@Rule
|
||||
public StubRunnerRule rule = new StubRunnerRule()
|
||||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
|
||||
----
|
||||
|
||||
[source,java,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.JUnit 5 Extension
|
||||
----
|
||||
@Rule
|
||||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
|
||||
----
|
||||
====
|
||||
|
||||
[[flows-provider-non-spring-producer]]
|
||||
=== Setting up the Producer
|
||||
|
||||
By default, the Spring Cloud Contract Plugin uses Rest Assured's `MockMvc` setup for the
|
||||
generated tests. Since non-Spring applications do not use `MockMvc`, you can change the
|
||||
`testMode` to `EXPLICIT` to send a real request to an application bound at a specific port.
|
||||
|
||||
In this example, we use a framework called https://javalin.io[Javalin] to start a
|
||||
non-Spring HTTP server.
|
||||
|
||||
Assume that we have the following application:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
package com.example.demo;
|
||||
|
||||
import io.javalin.Javalin;
|
||||
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new DemoApplication().run(7000);
|
||||
}
|
||||
|
||||
public Javalin start(int port) {
|
||||
return Javalin.create().start(port);
|
||||
}
|
||||
|
||||
public Javalin registerGet(Javalin app) {
|
||||
return app.get("/", ctx -> ctx.result("Hello World"));
|
||||
}
|
||||
|
||||
public Javalin run(int port) {
|
||||
return registerGet(start(port));
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Given that application, we can set up the plugin to use the `EXPLICIT` mode (that is, to
|
||||
send out requests to a real port), as follows:
|
||||
|
||||
====
|
||||
[source,xml,indent=0,role="primary"]
|
||||
.maven
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<baseClassForTests>com.example.demo.BaseClass</baseClassForTests>
|
||||
<!-- This will setup the EXPLICIT mode for the tests -->
|
||||
<testMode>EXPLICIT</testMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,role="secondary"]
|
||||
.gradle
|
||||
----
|
||||
contracts {
|
||||
// This will setup the EXPLICIT mode for the tests
|
||||
testMode = "EXPLICIT"
|
||||
baseClassForTests = "com.example.demo.BaseClass"
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The base class might resemble the following:
|
||||
|
||||
====
|
||||
[source,java,indent=0]
|
||||
----
|
||||
import io.javalin.Javalin;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.springframework.util.SocketUtils;
|
||||
|
||||
public class BaseClass {
|
||||
|
||||
Javalin app;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
// pick a random port
|
||||
int port = SocketUtils.findAvailableTcpPort();
|
||||
// start the application at a random port
|
||||
this.app = start(port);
|
||||
// tell Rest Assured where the started application is
|
||||
RestAssured.baseURI = "http://localhost:" + port;
|
||||
}
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
// stop the server after each test
|
||||
this.app.stop();
|
||||
}
|
||||
|
||||
private Javalin start(int port) {
|
||||
// reuse the production logic to start a server
|
||||
return new DemoApplication().run(port);
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
With such a setup:
|
||||
|
||||
* We have setup the Spring Cloud Contract plugin to use the `EXPLICIT` mode to send real
|
||||
requests instead of mocked ones.
|
||||
* We have defined a base class that:
|
||||
** Starts the HTTP server on a random port for each test.
|
||||
** Sets Rest Assured to send requests to that port.
|
||||
** Closes the HTTP server after each test.
|
||||
|
||||
[[flows-provider-non-jvm]]
|
||||
== Provider Contract Testing with Stubs in Artifactory in a non-JVM World
|
||||
|
||||
In this flow, we assume that:
|
||||
|
||||
* The API Producer and API Consumer are non-JVM applications.
|
||||
* The contract definitions are written in YAML.
|
||||
* The Stub Storage is Artifactory or Nexus.
|
||||
* Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker
|
||||
(SCC Stub Runner Docker) images are used.
|
||||
|
||||
You can read more about how to use Spring Cloud Contract with Docker
|
||||
<<docker-project.adoc,in this page>>.
|
||||
|
||||
https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world[Here], you can
|
||||
read a blog post about how to use Spring Cloud Contract in a polyglot world.
|
||||
|
||||
https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/[Here], you can find
|
||||
a sample of a NodeJS application that uses Spring Cloud Contract both as a producer and a
|
||||
consumer.
|
||||
|
||||
[[flows-provider-non-jvm-producer]]
|
||||
=== Producer Flow
|
||||
|
||||
At a high level, the producer:
|
||||
|
||||
. Writes contract definitions (for example, in YAML).
|
||||
. Sets up the build tool to:
|
||||
.. Start the application with mocked services on a given port.
|
||||
+
|
||||
If mocking is not possible, you can setup the infrastructure and define tests in a stateful way.
|
||||
.. Run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable.
|
||||
|
||||
The SCC Docker image:
|
||||
* Generates the tests from the attached volume.
|
||||
* Runs the tests against the running application.
|
||||
|
||||
Upon test completion, stubs get uploaded to a stub storage site (such as Artifactory or Git).
|
||||
|
||||
The following UML diagram shows the producer flow:
|
||||
|
||||
[plantuml, flows-provider-non-jvm-producer, png]
|
||||
----
|
||||
"API Producer"->"API Producer": write contract definitions
|
||||
"API Producer"->"API Producer": (preferable) prepare a way\nto run the app\nwith mocked services
|
||||
"API Producer"->"API Producer\nbuild": run the build
|
||||
"API Producer\nbuild"->"API Producer\nrunning app": run the app\non port X\nwith mocked services
|
||||
"API Producer\nbuild"->"SCC Docker": attach contract definitions\nas a volume
|
||||
"API Producer\nbuild"->"SCC Docker": set environment variables\ne.g. app running on port X
|
||||
"API Producer\nbuild"->"SCC Docker": run the contract tests
|
||||
"SCC Docker"->"SCC Docker\nimage": run the contract tests
|
||||
"SCC Docker\nimage"->"SCC Docker\nimage": pick the contract definitions\nfrom volume
|
||||
"SCC Docker\nimage"->"SCC Docker\nimage": generate contract tests
|
||||
"SCC Docker\nimage"->"SCC Docker\nimage": run the tests\nagainst app running\non port X
|
||||
"SCC Docker\nimage"->"SCC Docker\nimage": the tests are passing!
|
||||
"SCC Docker\nimage"->"Stub Storage": upload the stubs
|
||||
"SCC Docker\nimage"->"SCC Docker": build successful
|
||||
"SCC Docker"->"API Producer\nbuild": build successful
|
||||
"API Producer\nbuild"->"API Producer": build successful
|
||||
----
|
||||
|
||||
[[flows-provider-non-jvm-consumer]]
|
||||
=== Consumer Flow
|
||||
|
||||
At a high level, the consumer:
|
||||
|
||||
. Sets up the build tool to:
|
||||
* Start the Spring Cloud Contract Stub Runner Docker image and start the stubs.
|
||||
+
|
||||
The environment variables configure:
|
||||
* The stubs to fetch.
|
||||
* The location of the repositories.
|
||||
+
|
||||
Note that:
|
||||
* To use the local storage, you can also attach it as a volume.
|
||||
* The ports at which the stubs are running need to be exposed.
|
||||
. Run the application tests against the running stubs.
|
||||
|
||||
The following UML diagram shows the consumer flow:
|
||||
|
||||
[plantuml, flows-provider-non-jvm-consumer, png]
|
||||
----
|
||||
"API Consumer"->"API Consumer\nbuild": run the build
|
||||
"API Consumer\nbuild"->"SCC\nStub Runner\nDocker": set environment variables\ne.g. stub X running on port Y
|
||||
"SCC\nStub Runner\nDocker"->"SCC\nStub Runner\nDocker\nimage": fetch and run\nthe stubs
|
||||
"SCC\nStub Runner\nDocker\nimage"->"Stub Storage": fetch the stubs of X
|
||||
"Stub Storage"->"SCC\nStub Runner\nDocker\nimage": stubs found
|
||||
"SCC\nStub Runner\nDocker\nimage"->"X Stub": run the stub of X
|
||||
"X Stub"->"SCC\nStub Runner\nDocker\nimage": stub is running\non port Y
|
||||
"SCC\nStub Runner\nDocker\nimage"->"SCC\nStub Runner\nDocker": stubs running and\nready for tests
|
||||
"API Consumer\nbuild"->"API Consumer\nbuild": run tests against X stub
|
||||
"API Consumer\nbuild"->"X Stub": send a request
|
||||
"X Stub"->"API Consumer\nbuild": response received
|
||||
"API Consumer\nbuild"->"API Consumer": build successful
|
||||
----
|
||||
|
||||
[[flows-provider-rest-docs]]
|
||||
== Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory
|
||||
|
||||
In this flow, we do not use a Spring Cloud Contract plugin to generate tests and stubs. We write https://spring.io/projects/spring-restdocs[Spring RESTDocs] and, from them, we automatically generate stubs. Finally, we set up our builds to package the stubs and upload them to the stub storage site -- in our case, Nexus or Artifactory.
|
||||
|
||||
See the https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html[workshop page] for a step-by-step instruction on how to use this flow.
|
||||
|
||||
[[flows-provider-rest-docs-producer]]
|
||||
=== Producer Flow
|
||||
|
||||
As a producer, we:
|
||||
|
||||
. We write RESTDocs tests of our API.
|
||||
. We add Spring Cloud Contract Stub Runner starter to our build (`spring-cloud-starter-contract-stub-runner`), as follows
|
||||
+
|
||||
====
|
||||
[source,xml,indent=0,role="primary"]
|
||||
.maven
|
||||
----
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,role="secondary"]
|
||||
.gradle
|
||||
----
|
||||
dependencies {
|
||||
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
|
||||
}
|
||||
|
||||
dependencyManagement {
|
||||
imports {
|
||||
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
. We set up the build tool to package our stubs, as follows:
|
||||
+
|
||||
====
|
||||
[source,xml,indent=0,role="primary"]
|
||||
.maven
|
||||
----
|
||||
<!-- pom.xml -->
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>stub</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<inherited>false</inherited>
|
||||
<configuration>
|
||||
<attach>true</attach>
|
||||
<descriptors>
|
||||
${basedir}/src/assembly/stub.xml
|
||||
</descriptors>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
<!-- src/assembly/stub.xml -->
|
||||
<assembly
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
|
||||
<id>stubs</id>
|
||||
<formats>
|
||||
<format>jar</format>
|
||||
</formats>
|
||||
<includeBaseDirectory>false</includeBaseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${project.build.directory}/generated-snippets/stubs</directory>
|
||||
<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
|
||||
<includes>
|
||||
<include>**/*</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
</assembly>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,role="secondary"]
|
||||
.gradle
|
||||
----
|
||||
task stubsJar(type: Jar) {
|
||||
classifier = "stubs"
|
||||
into("META-INF/${project.group}/${project.name}/${project.version}/mappings") {
|
||||
include('**/*.*')
|
||||
from("${project.buildDir}/generated-snippets/stubs")
|
||||
}
|
||||
}
|
||||
// we need the tests to pass to build the stub jar
|
||||
stubsJar.dependsOn(test)
|
||||
bootJar.dependsOn(stubsJar)
|
||||
----
|
||||
====
|
||||
|
||||
Now, when we run the tests, stubs are automatically published and packaged.
|
||||
|
||||
The following UML diagram shows the producer flow:
|
||||
|
||||
[plantuml, flows-provider-rest-docs-producer, png]
|
||||
----
|
||||
"API Producer"->"API Producer": write RESTDocs tests
|
||||
"API Producer"->"API Producer": add the stub runner\nstarter dependency
|
||||
"API Producer"->"API Producer": setup the build tool to package\nthe generated stubs
|
||||
"API Producer"->"API Producer\nbuild": run the build
|
||||
"API Producer\nbuild"->"RESTDocs": generate HTTP snippets
|
||||
"RESTDocs"->"Spring Cloud\nContract": generate HTTP stubs
|
||||
"RESTDocs"->"Spring Cloud\nContract": (optional) generate\ncontract DSLs
|
||||
"Spring Cloud\nContract"->"RESTDocs": files generated
|
||||
"RESTDocs"->"API Producer\nbuild": snippets generated
|
||||
"API Producer\nbuild"->"API Producer\nbuild": tests passed
|
||||
"API Producer\nbuild"->"API Producer\nbuild": generate stubs jar
|
||||
"API Producer\nbuild"->"Stub Storage": upload JAR with the application
|
||||
"API Producer\nbuild"->"Stub Storage": upload JAR with the stubs
|
||||
"Stub Storage"->"API Producer\nbuild": JARs uploaded
|
||||
"API Producer\nbuild"->"API Producer": build successful
|
||||
----
|
||||
|
||||
[[flows-provider-rest-docs-consumer]]
|
||||
=== Consumer Flow
|
||||
|
||||
Since the consumer flow is not affected by the tool used to generate the stubs, you can check <<getting-started.adoc#getting-started-first-application-consumer, Developing Your First Spring Cloud Contract based application>> to see the flow for consumer side of the provider contract testing with stubs in Nexus or Artifactory.
|
||||
|
||||
[[using-whats-next]]
|
||||
== What to Read Next
|
||||
|
||||
You should now understand how you can use {project-full-name} and some best practices that you
|
||||
should follow. You can now go on to learn about specific
|
||||
<<project-features#project-features, {project-full-name} features>>, or you could
|
||||
skip ahead and read about the link:advanced.html[advanced features of {project-full-name}].
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,913 +0,0 @@
|
||||
:branch: master
|
||||
:introduction_url: https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}
|
||||
:samples_branch: 2.2.x
|
||||
|
||||
== Spring Cloud Contract FAQ
|
||||
|
||||
=== Why use Spring Cloud Contract Verifier and not X ?
|
||||
|
||||
For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you're already creating
|
||||
software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make
|
||||
Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:
|
||||
|
||||
- Possibility to do CDC with messaging
|
||||
- Clear and easy to use, statically typed DSL
|
||||
- Possibility to copy paste your current JSON file to the contract and only edit its elements
|
||||
- Automatic generation of tests from the defined Contract
|
||||
- Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory
|
||||
- Spring Cloud integration - no discovery service is needed for integration tests
|
||||
- Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality
|
||||
- Via Docker adds support for any language & framework used
|
||||
|
||||
=== I don't want to write a contract in Groovy!
|
||||
|
||||
No problem. You can write a contract in YAML!
|
||||
|
||||
=== What is this value(consumer(), producer()) ?
|
||||
|
||||
One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose.
|
||||
What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids.
|
||||
Imagine the following JSON request
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "2016-10-10 20:10:15",
|
||||
"id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
|
||||
"body" : "foo"
|
||||
}
|
||||
----
|
||||
|
||||
and JSON response
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "2016-10-10 21:10:15",
|
||||
"id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
|
||||
"body" : "bar"
|
||||
}
|
||||
----
|
||||
|
||||
Imagine the pain required to set proper value of the `time` field (let's assume that this content is generated by the
|
||||
database) by changing the clock in the system or providing stub implementations of data providers. The same is related
|
||||
to the field called `id`. Will you create a stubbed implementation of UUID generator? Makes little sense...
|
||||
|
||||
So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system
|
||||
will work as usual - will generate data and you won't have to stub anything out. Let's assume that in case of the aforementioned
|
||||
JSON the most important part is the `body` field. You can focus on that and provide matching for other fields. In other words
|
||||
you would like the stub to work like this:
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "SOMETHING THAT MATCHES TIME",
|
||||
"id" : "SOMETHING THAT MATCHES UUID",
|
||||
"body" : "foo"
|
||||
}
|
||||
----
|
||||
|
||||
As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "2016-10-10 21:10:15",
|
||||
"id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
|
||||
"body" : "bar"
|
||||
}
|
||||
----
|
||||
|
||||
As you could see in the previous sections we generate tests from contracts. So from the producer's side the situation looks
|
||||
much different. We're parsing the provided contract and in the test we want to send a real request to your endpoints.
|
||||
So for the case of a producer for the request we can't have any sort of matching. We need concrete values that the
|
||||
producer's backend can work on. Such a JSON would be a valid one:
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "2016-10-10 20:10:15",
|
||||
"id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
|
||||
"body" : "foo"
|
||||
}
|
||||
----
|
||||
|
||||
On the other hand from the point of view of the validity of the contract the response doesn't necessarily have to
|
||||
contain concrete values of `time` or `id`. Let's say that you generate those on the producer side - again, you'd
|
||||
have to do a lot of stubbing to ensure that you always return the same values. That's why from the producer's side
|
||||
what you might want is the following response:
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"time" : "SOMETHING THAT MATCHES TIME",
|
||||
"id" : "SOMETHING THAT MATCHES UUID",
|
||||
"body" : "bar"
|
||||
}
|
||||
----
|
||||
|
||||
How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa?
|
||||
In Spring Cloud Contract we're allowing you to provide a *dynamic value*. That means that it can differ for both
|
||||
sides of the communication. You can pass the values:
|
||||
|
||||
Either via the `value` method
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
value(consumer(...), producer(...))
|
||||
value(stub(...), test(...))
|
||||
value(client(...), server(...))
|
||||
----
|
||||
|
||||
or using the `$()` method
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
$(consumer(...), producer(...))
|
||||
$(stub(...), test(...))
|
||||
$(client(...), server(...))
|
||||
----
|
||||
|
||||
You can read more about this in the <<contract-dsl>> section.
|
||||
|
||||
Calling `value()` or `$()` tells Spring Cloud Contract that you will be passing a dynamic value.
|
||||
Inside the `consumer()` method you pass the value that should be used on the consumer side (in the generated stub).
|
||||
Inside the `producer()` method you pass the value that should be used on the producer side (in the generated test).
|
||||
|
||||
TIP: If on one side you have passed the regular expression and you haven't passed the other, then the
|
||||
other side will get auto-generated.
|
||||
|
||||
Most often you will use that method together with the `regex` helper method. E.g. `consumer(regex('[0-9]{10}'))`.
|
||||
|
||||
To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression
|
||||
for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
org.springframework.cloud.contract.spec.Contract.make {
|
||||
request {
|
||||
method 'GET'
|
||||
url '/someUrl'
|
||||
body([
|
||||
time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
|
||||
id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
|
||||
body: "foo"
|
||||
])
|
||||
}
|
||||
response {
|
||||
status OK()
|
||||
body([
|
||||
time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
|
||||
id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
|
||||
body: "bar"
|
||||
])
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
IMPORTANT: Please read the https://groovy-lang.org/json.html[Groovy docs related to JSON] to understand how to
|
||||
properly structure the request / response bodies.
|
||||
|
||||
=== How to do Stubs versioning?
|
||||
|
||||
==== API Versioning
|
||||
|
||||
Let's try to answer a question what versioning really means. If you're referring to the API version then there are
|
||||
different approaches.
|
||||
|
||||
- use Hypermedia, links and do not version your API by any means
|
||||
- pass versions through headers / urls
|
||||
|
||||
I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate
|
||||
business value should be picked.
|
||||
|
||||
Let's assume that you do version your API. In that case you should provide as many contracts as many versions you support.
|
||||
You can create a subfolder for every version or append it to the contract name - whatever suits you more.
|
||||
|
||||
==== JAR versioning
|
||||
|
||||
If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.
|
||||
|
||||
Let's assume that you're doing Continuous Delivery / Deployment which means that you're generating a new version of
|
||||
the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version
|
||||
looks like this (it got built on the 20.10.2016 at 20:15:21) :
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
1.0.0.20161020-201521-RELEASE
|
||||
----
|
||||
|
||||
In that case your generated stub jar will look like this.
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
1.0.0.20161020-201521-RELEASE-stubs.jar
|
||||
----
|
||||
|
||||
In this case you should inside your `application.yml` or `@AutoConfigureStubRunner` when referencing stubs provide the
|
||||
latest version of the stubs. You can do that by passing the `+` sign. Example
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
|
||||
----
|
||||
|
||||
If the versioning however is fixed (e.g. `1.0.4.RELEASE` or `2.1.1`) then you have to set the concrete value of the jar
|
||||
version. Example for 2.1.1.
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})
|
||||
----
|
||||
|
||||
==== Dev or prod stubs
|
||||
|
||||
You can manipulate the classifier to run the tests against current development version of the stubs of other services
|
||||
or the ones that were deployed to production. If you alter your build to deploy the stubs with the `prod-stubs` classifier
|
||||
once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.
|
||||
|
||||
Example of tests using development version of stubs
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})
|
||||
----
|
||||
|
||||
Example of tests using production version of stubs
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})
|
||||
----
|
||||
|
||||
You can pass those values also via properties from your deployment pipeline.
|
||||
|
||||
=== Common repo with contracts
|
||||
|
||||
Another way of storing contracts other than having them with the producer is keeping them in a common place.
|
||||
It can be related to security issues where the consumers can't clone the producer's code. Also if you keep
|
||||
contracts in a single place then you, as a producer, will know how many consumers you have and which
|
||||
consumer you will break with your local changes.
|
||||
|
||||
==== Repo structure
|
||||
|
||||
Let's assume that we have a producer with coordinates `com.example:server` and 3 consumers: `client1`,
|
||||
`client2`, `client3`. Then in the repository with common contracts you would have the following setup
|
||||
(which you can checkout https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/contracts[here]):
|
||||
|
||||
[source,bash,indent=0]
|
||||
----
|
||||
├── com
|
||||
│ └── example
|
||||
│ └── server
|
||||
│ ├── client1
|
||||
│ │ └── expectation.groovy
|
||||
│ ├── client2
|
||||
│ │ └── expectation.groovy
|
||||
│ ├── client3
|
||||
│ │ └── expectation.groovy
|
||||
│ └── pom.xml
|
||||
├── mvnw
|
||||
├── mvnw.cmd
|
||||
├── pom.xml
|
||||
└── src
|
||||
└── assembly
|
||||
└── contracts.xml
|
||||
----
|
||||
|
||||
As you can see under the slash-delimited groupid `/` artifact id folder (`com/example/server`) you have
|
||||
expectations of the 3 consumers (`client1`, `client2` and `client3`). Expectations are the standard Groovy DSL
|
||||
contract files as described throughout this documentation. This repository has to produce a JAR file that maps
|
||||
one to one to the contents of the repo.
|
||||
|
||||
Example of a `pom.xml` inside the `server` folder.
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{introduction_url}/samples/standalone/contracts/com/example/server/pom.xml[indent=0]
|
||||
----
|
||||
|
||||
As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin.
|
||||
Those poms are necessary for the consumer side to run `mvn clean install -DskipTests` to locally install
|
||||
stubs of the producer project.
|
||||
|
||||
The `pom.xml` in the root folder can look like this:
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{introduction_url}/samples/standalone/contracts/pom.xml[indent=0]
|
||||
----
|
||||
|
||||
It's using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{introduction_url}/samples/standalone/contracts/src/assembly/contracts.xml[indent=0]
|
||||
----
|
||||
|
||||
==== Workflow
|
||||
|
||||
The workflow would look similar to the one presented in the `Step by step guide to CDC`. The only difference
|
||||
is that the producer doesn't own the contracts anymore. So the consumer and the producer have to work on
|
||||
common contracts in a common repository.
|
||||
|
||||
==== Consumer
|
||||
|
||||
When the *consumer* wants to work on the contracts offline, instead of cloning the producer code, the
|
||||
consumer team clones the common repository, goes to the required producer's folder (e.g. `com/example/server`)
|
||||
and runs `mvn clean install -DskipTests` to install locally the stubs converted from the contracts.
|
||||
|
||||
TIP: You need to have https://maven.apache.org/download.cgi[Maven installed locally]
|
||||
|
||||
==== Producer
|
||||
|
||||
As a *producer* it's enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency
|
||||
of the JAR containing the contracts:
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{introduction_url}/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/projects/basic-remote-contracts/pom-with-repo.xml[tags=remote_config,indent=0]
|
||||
----
|
||||
|
||||
With this setup the JAR with groupid `com.example.standalone` and artifactid `contracts` will be downloaded
|
||||
from `https://link/to/your/nexus/or/artifactory/or/sth`. It will be then unpacked in a local temporary folder
|
||||
and contracts present under the `com/example/server` will be picked as the ones used to generate the
|
||||
tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken
|
||||
when some incompatible changes are done.
|
||||
|
||||
The rest of the flow looks the same.
|
||||
|
||||
==== How can I define messaging contracts per topic not per producer?
|
||||
|
||||
To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic,
|
||||
we could create the structure when the rest contracts would be placed in a folder per producer and messaging
|
||||
contracts in the folder per topic.
|
||||
|
||||
===== For Maven Project
|
||||
|
||||
To make it possible to work on the producer side we should specify an inclusion pattern for
|
||||
filtering common repository jar by messaging topics we are interested in. ```includedFiles``` property of ```Maven Spring Cloud Contract plugin```
|
||||
allows us to do that. Also ```contractsPath``` need to be specified since the default path would be the common repository ```groupid/artifactid```.
|
||||
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<configuration>
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
<contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
|
||||
<contractDependency>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>common-repo-with-contracts</artifactId>
|
||||
<version>+</version>
|
||||
</contractDependency>
|
||||
<contractsPath>/</contractsPath>
|
||||
<baseClassMappings>
|
||||
<baseClassMapping>
|
||||
<contractPackageRegex>.*messaging.*</contractPackageRegex>
|
||||
<baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
|
||||
</baseClassMapping>
|
||||
<baseClassMapping>
|
||||
<contractPackageRegex>.*rest.*</contractPackageRegex>
|
||||
<baseClassFQN>com.example.services.TestBase</baseClassFQN>
|
||||
</baseClassMapping>
|
||||
</baseClassMappings>
|
||||
<includedFiles>
|
||||
<includedFile>**/${project.artifactId}/**</includedFile>
|
||||
<includedFile>**/${first-topic}/**</includedFile>
|
||||
<includedFile>**/${second-topic}/**</includedFile>
|
||||
</includedFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
===== For Gradle Project
|
||||
|
||||
- Add a custom configuration for the common-repo dependency:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
ext {
|
||||
conractsGroupId = "com.example"
|
||||
contractsArtifactId = "common-repo"
|
||||
contractsVersion = "1.2.3"
|
||||
}
|
||||
|
||||
configurations {
|
||||
contracts {
|
||||
transitive = false
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
- Add the common-repo dependency to your classpath:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
dependencies {
|
||||
contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
|
||||
testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
|
||||
}
|
||||
----
|
||||
|
||||
- Download the dependency to an appropriate folder:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
task getContracts(type: Copy) {
|
||||
from configurations.contracts
|
||||
into new File(project.buildDir, "downloadedContracts")
|
||||
}
|
||||
----
|
||||
|
||||
- Unzip JAR:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
task unzipContracts(type: Copy) {
|
||||
def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
|
||||
def outputDir = file("${buildDir}/unpackedContracts")
|
||||
|
||||
from zipTree(zipFile)
|
||||
into outputDir
|
||||
}
|
||||
----
|
||||
|
||||
- Cleanup unused contracts:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
task deleteUnwantedContracts(type: Delete) {
|
||||
delete fileTree(dir: "${buildDir}/unpackedContracts",
|
||||
include: "**/*",
|
||||
excludes: [
|
||||
"**/${project.name}/**"",
|
||||
"**/${first-topic}/**",
|
||||
"**/${second-topic}/**"])
|
||||
}
|
||||
----
|
||||
|
||||
- Create task dependencies:
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
unzipContracts.dependsOn("getContracts")
|
||||
deleteUnwantedContracts.dependsOn("unzipContracts")
|
||||
build.dependsOn("deleteUnwantedContracts")
|
||||
----
|
||||
|
||||
- Configure plugin by specifying the directory containing contracts using `contractsDslDir` property
|
||||
|
||||
[source,groovy,indent=0]
|
||||
----
|
||||
contracts {
|
||||
contractsDslDir = new File("${buildDir}/unpackedContracts")
|
||||
}
|
||||
----
|
||||
|
||||
=== Do I need a Binary Storage? Can't I use Git?
|
||||
|
||||
In the polyglot world, there are languages that don't use binary storages like
|
||||
Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide
|
||||
mechanisms to store contracts and stubs in a SCM repository. Currently the
|
||||
only supported SCM is Git.
|
||||
|
||||
The repository would have to the following setup
|
||||
(which you can checkout https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/contracts_git/[here]):
|
||||
|
||||
[source,indent=0]
|
||||
----
|
||||
.
|
||||
└── META-INF
|
||||
└── com.example
|
||||
└── beer-api-producer-git
|
||||
└── 0.0.1-SNAPSHOT
|
||||
├── contracts
|
||||
│ └── beer-api-consumer
|
||||
│ ├── messaging
|
||||
│ │ ├── shouldSendAcceptedVerification.groovy
|
||||
│ │ └── shouldSendRejectedVerification.groovy
|
||||
│ └── rest
|
||||
│ ├── shouldGrantABeerIfOldEnough.groovy
|
||||
│ └── shouldRejectABeerIfTooYoung.groovy
|
||||
└── mappings
|
||||
└── beer-api-consumer
|
||||
└── rest
|
||||
├── shouldGrantABeerIfOldEnough.json
|
||||
└── shouldRejectABeerIfTooYoung.json
|
||||
----
|
||||
|
||||
Under `META-INF` folder:
|
||||
|
||||
* we group applications via `groupId` (e.g. `com.example`)
|
||||
* then each application is represented via the `artifactId` (e.g. `beer-api-producer-git`)
|
||||
* next, the version of the application (e.g. `0.0.1-SNAPSHOT`). Starting from Spring Cloud Contract version `2.1.0`, you can specify the versions as follows (assuming that your versions follow the semantic versioning)
|
||||
** `+` or `latest` - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:
|
||||
*** if you have a version `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.BUILD-SNAPSHOT`
|
||||
*** if you have a version `1.0.0.RELEASE` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.RELEASE`
|
||||
*** if you have a version called `latest` or `+` we will pick that folder
|
||||
** `release` - to find the latest release version of your stubs. That means:
|
||||
*** if you have a version `1.0.0.RELEASE`, `2.0.0.BUILD-SNAPSHOT` and `2.0.0.RELEASE` we will assume that the latest is `2.0.0.RELEASE`
|
||||
*** if you have a version called `release` we will pick that folder
|
||||
* finally, there are two folders:
|
||||
** `contracts` - the good practice is to store the contracts required by each
|
||||
consumer in the folder with the consumer name (e.g. `beer-api-consumer`). That way you
|
||||
can use the `stubs-per-consumer` feature. Further directory structure is arbitrary.
|
||||
** `mappings` - in this folder the Maven / Gradle Spring Cloud Contract plugins will push
|
||||
the stub server mappings. On the consumer side, Stub Runner will scan this folder
|
||||
to start stub servers with stub definitions. The folder structure will be a copy
|
||||
of the one created in the `contracts` subfolder.
|
||||
|
||||
==== Protocol convention
|
||||
|
||||
In order to control the type and location of the source of contracts (whether it's
|
||||
a binary storage or an SCM repository), you can use the protocol in the URL of
|
||||
the repository. Spring Cloud Contract iterates over registered protocol resolvers
|
||||
and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).
|
||||
|
||||
For the SCM functionality, currently, we support the Git repository. To use it,
|
||||
in the property, where the repository URL needs to be placed you just have to prefix
|
||||
the connection URL with `git://`. Here you can find a couple of examples:
|
||||
|
||||
[source,indent=0]
|
||||
----
|
||||
git://file:///foo/bar
|
||||
git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
|
||||
git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
|
||||
----
|
||||
|
||||
==== Producer
|
||||
|
||||
For the producer, to use the SCM approach, we can reuse the
|
||||
same mechanism we use for external contracts. We route Spring Cloud Contract
|
||||
to use the SCM implementation via the URL that contains
|
||||
the `git://` protocol.
|
||||
|
||||
IMPORTANT: You have to manually add the `pushStubsToScm`
|
||||
goal in Maven or execute (bind) the `pushStubsToScm` task in
|
||||
Gradle. We don't push stubs to `origin` of your git
|
||||
repository out of the box.
|
||||
|
||||
.Maven
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- Base class mappings etc. -->
|
||||
|
||||
<!-- We want to pick contracts from a Git repository -->
|
||||
<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
|
||||
|
||||
<!-- We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts -->
|
||||
<contractDependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>${project.artifactId}</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</contractDependency>
|
||||
|
||||
<!-- The contracts mode can't be classpath -->
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<!-- By default we will not push the stubs back to SCM,
|
||||
you have to explicitly add it as a goal -->
|
||||
<goal>pushStubsToScm</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,gradle,indent=0]
|
||||
----
|
||||
contracts {
|
||||
// We want to pick contracts from a Git repository
|
||||
contractDependency {
|
||||
stringNotation = "${project.group}:${project.name}:${project.version}"
|
||||
}
|
||||
/*
|
||||
We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts
|
||||
*/
|
||||
contractRepository {
|
||||
repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
|
||||
}
|
||||
// The mode can't be classpath
|
||||
contractsMode = "REMOTE"
|
||||
// Base class mappings etc.
|
||||
}
|
||||
|
||||
/*
|
||||
In this scenario we want to publish stubs to SCM whenever
|
||||
the `publish` task is executed
|
||||
*/
|
||||
publish.dependsOn("publishStubsToScm")
|
||||
----
|
||||
|
||||
With such a setup:
|
||||
|
||||
* Git project will be cloned to a temporary directory
|
||||
* The SCM stub downloader will go to `META-INF/groupId/artifactId/version/contracts` folder
|
||||
to find contracts. E.g. for `com.example:foo:1.0.0` the path would be
|
||||
`META-INF/com.example/foo/1.0.0/contracts`
|
||||
* Tests will be generated from the contracts
|
||||
* Stubs will be created from the contracts
|
||||
* Once the tests pass, the stubs will be committed in the cloned repository
|
||||
* Finally, a push will be done to that repo's `origin`
|
||||
|
||||
==== Producer with contracts stored locally
|
||||
|
||||
Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.
|
||||
|
||||
.Maven
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{samples_url}/producer_with_empty_git/pom.xml[tags=plugin,indent=0]
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
include::{samples_url}/producer_with_empty_git/build.gradle[tags=plugin,indent=0]
|
||||
----
|
||||
|
||||
With such a setup:
|
||||
|
||||
* Contracts from the default `src/test/resources/contracts` directory will be picked
|
||||
* Tests will be generated from the contracts
|
||||
* Stubs will be created from the contracts
|
||||
* Once the tests pass
|
||||
** Git project will be cloned to a temporary directory
|
||||
** The stubs and contracts will be committed in the cloned repository
|
||||
* Finally, a push will be done to that repo's `origin`
|
||||
|
||||
===== Keeping contracts with the producer and stubs in an external repository
|
||||
|
||||
It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo.
|
||||
This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to
|
||||
use an artifact repository for storing the stubs.
|
||||
|
||||
In order to do that, use the usual producer setup, and then add the `pushStubsToScm` goal and set
|
||||
`contractsRepositoryUrl` to the repository where you want to keep the stubs.
|
||||
|
||||
==== Consumer
|
||||
|
||||
On the consumer side when passing the `repositoryRoot` parameter,
|
||||
either from the `@AutoConfigureStubRunner` annotation, the
|
||||
JUnit rule, JUnit 5 extension or properties, it's enough to pass the URL of the
|
||||
SCM repository, prefixed with the protocol. For example
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@AutoConfigureStubRunner(
|
||||
stubsMode="REMOTE",
|
||||
repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
|
||||
ids="com.example:bookstore:0.0.1.RELEASE"
|
||||
)
|
||||
----
|
||||
|
||||
With such a setup:
|
||||
|
||||
* Git project will be cloned to a temporary directory
|
||||
* The SCM stub downloader will go to `META-INF/groupId/artifactId/version/` folder
|
||||
to find stub definitions and contracts. E.g. for `com.example:foo:1.0.0` the path would be
|
||||
`META-INF/com.example/foo/1.0.0/`
|
||||
* Stub servers will be started and fed with mappings
|
||||
* Messaging definitions will be read and used in the messaging tests
|
||||
|
||||
=== Can I use the Pact Broker?
|
||||
|
||||
When using https://pact.io/[Pact] you can use the https://github.com/pact-foundation/pact_broker[Pact Broker]
|
||||
to store and share Pact definitions. Starting from Spring Cloud Contract
|
||||
2.0.0 one can fetch Pact files from the Pact Broker to generate
|
||||
tests and stubs.
|
||||
|
||||
As a prerequisite the Pact Converter and Pact Stub Downloader
|
||||
are required. You have to add them via the `spring-cloud-contract-pact` dependency.
|
||||
You can read more about it in the <<pact-converter>> section.
|
||||
|
||||
IMPORTANT: Pact follows the Consumer Contract convention. That means
|
||||
that the Consumer creates the Pact definitions first, then
|
||||
shares the files with the Producer. Those expectations are generated
|
||||
from the Consumer's code and can break the Producer if the expectations
|
||||
are not met.
|
||||
|
||||
==== Pact Consumer
|
||||
|
||||
The consumer uses Pact framework to generate Pact files. The
|
||||
Pact files are sent to the Pact Broker. An example of such
|
||||
setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact[here].
|
||||
|
||||
==== Producer
|
||||
|
||||
For the producer, to use the Pact files from the Pact Broker, we can reuse the
|
||||
same mechanism we use for external contracts. We route Spring Cloud Contract
|
||||
to use the Pact implementation via the URL that contains
|
||||
the `pact://` protocol. It's enough to pass the URL to the
|
||||
Pact Broker. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/producer_pact[here].
|
||||
|
||||
.Maven
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<plugin>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<!-- Base class mappings etc. -->
|
||||
|
||||
<!-- We want to pick contracts from a Git repository -->
|
||||
<contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
|
||||
|
||||
<!-- We reuse the contract dependency section to set up the path
|
||||
to the folder that contains the contract definitions. In our case the
|
||||
path will be /groupId/artifactId/version/contracts -->
|
||||
<contractDependency>
|
||||
<groupId>${project.groupId}</groupId>
|
||||
<artifactId>${project.artifactId}</artifactId>
|
||||
<!-- When + is passed, a latest tag will be applied when fetching pacts -->
|
||||
<version>+</version>
|
||||
</contractDependency>
|
||||
|
||||
<!-- The contracts mode can't be classpath -->
|
||||
<contractsMode>REMOTE</contractsMode>
|
||||
</configuration>
|
||||
<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||||
<version>${spring-cloud-contract.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,gradle,indent=0]
|
||||
----
|
||||
buildscript {
|
||||
repositories {
|
||||
//...
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// ...
|
||||
// Don't forget to add spring-cloud-contract-pact to the classpath!
|
||||
classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
|
||||
}
|
||||
}
|
||||
|
||||
contracts {
|
||||
// When + is passed, a latest tag will be applied when fetching pacts
|
||||
contractDependency {
|
||||
stringNotation = "${project.group}:${project.name}:+"
|
||||
}
|
||||
contractRepository {
|
||||
repositoryUrl = "pact://http://localhost:8085"
|
||||
}
|
||||
// The mode can't be classpath
|
||||
contractsMode = "REMOTE"
|
||||
// Base class mappings etc.
|
||||
}
|
||||
----
|
||||
|
||||
With such a setup:
|
||||
|
||||
* Pact files will be downloaded from the Pact Broker
|
||||
* Spring Cloud Contract will convert the Pact files into tests and stubs
|
||||
* The JAR with the stubs gets automatically created as usual
|
||||
|
||||
==== Pact Consumer (Producer Contract approach)
|
||||
|
||||
In the scenario where you don't want to do Consumer Contract approach
|
||||
(for every single consumer define the expectations) but you'd prefer
|
||||
to do Producer Contracts (the producer provides the contracts and
|
||||
publishes stubs), it's enough to use Spring Cloud Contract with
|
||||
Stub Runner option. An example of such setup can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/{samples_branch}/consumer_pact_stubrunner[here].
|
||||
|
||||
First, remember to add Stub Runner and Spring Cloud Contract Pact module
|
||||
as test dependencies.
|
||||
|
||||
.Maven
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
|
||||
<dependencies>
|
||||
<!-- ... -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
.Gradle
|
||||
[source,gradle,indent=0]
|
||||
----
|
||||
dependencyManagement {
|
||||
imports {
|
||||
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
//...
|
||||
testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
|
||||
// Don't forget to add spring-cloud-contract-pact to the classpath!
|
||||
testCompile("org.springframework.cloud:spring-cloud-contract-pact")
|
||||
}
|
||||
----
|
||||
|
||||
Next, just pass the URL of the Pact Broker to `repositoryRoot`, prefixed
|
||||
with `pact://` protocol. E.g. `pact://http://localhost:8085`
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||||
ids = "com.example:beer-api-producer-pact",
|
||||
repositoryRoot = "pact://http://localhost:8085")
|
||||
public class BeerControllerTest {
|
||||
//Inject the port of the running stub
|
||||
@StubRunnerPort("beer-api-producer-pact") int producerPort;
|
||||
//...
|
||||
}
|
||||
----
|
||||
|
||||
With such a setup:
|
||||
|
||||
* Pact files will be downloaded from the Pact Broker
|
||||
* Spring Cloud Contract will convert the Pact files into stub definitions
|
||||
* The stub servers will be started and fed with stubs
|
||||
|
||||
For more information about Pact support you can go to
|
||||
the <<pact-stub-downloader>> section.
|
||||
|
||||
=== How can I debug the request/response being sent by the generated tests client?
|
||||
|
||||
The generated tests all boil down to RestAssured in some form or fashion which relies on https://hc.apache.org/httpcomponents-client-ga/[Apache HttpClient]. HttpClient has a facility called https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging[wire logging] which logs the entire request and response to HttpClient. Spring Boot has a logging https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html[common application property] for doing this sort of thing, just add this to your application properties
|
||||
[source,properties,indent=0]
|
||||
----
|
||||
logging.level.org.apache.http.wire=DEBUG
|
||||
----
|
||||
|
||||
==== How can I debug the mapping/request/response being sent by WireMock?
|
||||
|
||||
Starting from version `1.2.0` we turn on WireMock logging to
|
||||
info and the WireMock notifier to being verbose. Now you will
|
||||
exactly know what request was received by WireMock server and which
|
||||
matching response definition was picked.
|
||||
|
||||
To turn off this feature just bump WireMock logging to `ERROR`
|
||||
|
||||
[source,properties,indent=0]
|
||||
----
|
||||
logging.level.com.github.tomakehurst.wiremock=ERROR
|
||||
----
|
||||
|
||||
==== How can I see what got registered in the HTTP server stub?
|
||||
|
||||
You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner`, `StubRunnerRule` or
|
||||
`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server
|
||||
was started will be attached.
|
||||
|
||||
==== Can I reference text from file?
|
||||
|
||||
Yes! With version 1.2.0 we've added such a possibility. It's enough to call `file(...)` method in the
|
||||
DSL and provide a path relative to where the contract lays.
|
||||
If you're using YAML just use the `bodyFromFile` property.
|
||||
@@ -1,195 +0,0 @@
|
||||
== Spring Cloud Contract Verifier Messaging
|
||||
|
||||
Spring Cloud Contract Verifier lets you verify applications that use messaging as a
|
||||
means of communication. All of the integrations shown in this document work with Spring,
|
||||
but you can also create one of your own and use that.
|
||||
|
||||
=== Integrations
|
||||
|
||||
You can use one of the following four integration configurations:
|
||||
|
||||
* Apache Camel
|
||||
* Spring Integration
|
||||
* Spring Cloud Stream
|
||||
* Spring AMQP
|
||||
|
||||
Since we use Spring Boot, if you have added one of these libraries to the classpath, all
|
||||
the messaging configuration is automatically set up.
|
||||
|
||||
IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your
|
||||
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 dependency on
|
||||
`org.springframework.cloud:spring-cloud-stream-test-support`, as shown here:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-stream-test-support</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
|
||||
----
|
||||
|
||||
=== Manual Integration Testing
|
||||
|
||||
The main interface used by the tests is
|
||||
`org.springframework.cloud.contract.verifier.messaging.MessageVerifier`.
|
||||
It defines how to send and receive messages. You can create your own implementation to
|
||||
achieve the same goal.
|
||||
|
||||
In a test, you can inject a `ContractVerifierMessageExchange` to send and receive
|
||||
messages that follow the contract. Then add `@AutoConfigureMessageVerifier` to your test.
|
||||
Here's an example:
|
||||
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@RunWith(SpringTestRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMessageVerifier
|
||||
public static class MessagingContractTests {
|
||||
|
||||
@Autowired
|
||||
private MessageVerifier verifier;
|
||||
...
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the
|
||||
messaging configuration, so you only need the one annotation.
|
||||
|
||||
=== Publisher-Side Test Generation
|
||||
|
||||
Having the `input` or `outputMessage` sections in your DSL results in creation of tests
|
||||
on the publisher's side. By default, JUnit 4 tests are created. However, there is also a
|
||||
possibility to create JUnit 5, TestNG or Spock tests.
|
||||
|
||||
There are 3 main scenarios that we should take into consideration:
|
||||
|
||||
* Scenario 1: There is no input message that produces an output message. The output
|
||||
message is triggered by a component inside the application (for example, scheduler).
|
||||
* Scenario 2: The input message triggers an output message.
|
||||
* Scenario 3: The input message is consumed and there is no output message.
|
||||
|
||||
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`).
|
||||
|
||||
==== Scenario 1: No Input Message
|
||||
|
||||
For the given contract:
|
||||
|
||||
.Groovy DSL
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_dsl]
|
||||
----
|
||||
|
||||
.YAML
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario1.yml[indent=0]
|
||||
----
|
||||
|
||||
The following JUnit test is created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_junit_test]
|
||||
----
|
||||
|
||||
And the following Spock test would be created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
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
|
||||
|
||||
For the given contract:
|
||||
|
||||
.Groovy DSL
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_dsl]
|
||||
----
|
||||
|
||||
.YAML
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario2.yml[indent=0]
|
||||
----
|
||||
|
||||
The following JUnit test is created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_junit]
|
||||
----
|
||||
|
||||
And the following Spock test would be created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_spock]
|
||||
----
|
||||
|
||||
==== Scenario 3: No Output Message
|
||||
|
||||
For the given contract:
|
||||
|
||||
.Groovy DSL
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl]
|
||||
----
|
||||
|
||||
.YAML
|
||||
[source,yml,indent=0]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/resources/yml/contract_message_scenario3.yml[indent=0]
|
||||
----
|
||||
|
||||
The following JUnit test is created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_junit]
|
||||
----
|
||||
|
||||
And the following Spock test would be created:
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_spock]
|
||||
----
|
||||
|
||||
=== Consumer Stub Generation
|
||||
|
||||
Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with
|
||||
a stub. Then it is parsed on the consumer side and proper stubbed routes are created.
|
||||
|
||||
For more information, see <<stub-runner-for-messaging>> section.
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
include::{standalone_messaging_samples_path}/stream-sink/pom.xml[tags=jars,indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0]
|
||||
----
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,182 +0,0 @@
|
||||
== Spring Cloud Contract Stub Runner
|
||||
|
||||
One of the issues that you might encounter while using Spring Cloud Contract Verifier is
|
||||
passing the generated WireMock JSON stubs from the server side to the client side (or to
|
||||
various clients). The same takes place in terms of client-side generation for messaging.
|
||||
|
||||
Copying the JSON files and setting the client side for messaging manually is out of the
|
||||
question. That is why we introduced Spring Cloud Contract Stub Runner. It can
|
||||
automatically download and run the stubs for you.
|
||||
|
||||
=== Snapshot versions
|
||||
|
||||
Add the additional snapshot repository to your `build.gradle` file to use snapshot
|
||||
versions, which are automatically uploaded after every successful build:
|
||||
|
||||
[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
|
||||
.Maven
|
||||
----
|
||||
include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
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.
|
||||
|
||||
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 -->
|
||||
include::{samples_url}/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0]
|
||||
|
||||
<!-- Next add the assembly plugin to your build -->
|
||||
include::{samples_url}/producer_with_restdocs/pom.xml[tags=assembly,indent=0]
|
||||
|
||||
<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
|
||||
include::{samples_url}/producer_with_restdocs/src/assembly/stub.xml[indent=0]
|
||||
----
|
||||
|
||||
[source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
|
||||
.Gradle
|
||||
----
|
||||
include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/scenarioProject/build.gradle[tags=jar_setup,indent=0]
|
||||
----
|
||||
|
||||
include::{stubrunner_core_path}/README.adoc[]
|
||||
|
||||
=== Common
|
||||
|
||||
This section briefly describes common properties, including:
|
||||
|
||||
* <<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| Minimum value of a port for a started WireMock with stubs.
|
||||
|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs.
|
||||
|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo.
|
||||
|stubrunner.classifier|stubs| Default classifier for the stub artifacts.
|
||||
|stubrunner.stubsMode|CLASSPATH| The way you want to fetch and register the stubs
|
||||
|stubrunner.ids|| Array of Ivy notation stubs to download.
|
||||
|stubrunner.username|| Optional username to access the tool that stores the JARs with
|
||||
stubs.
|
||||
|stubrunner.password|| Optional password to access the tool that stores the JARs with
|
||||
stubs.
|
||||
|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for
|
||||
each consumer instead of registering all stubs for every consumer.
|
||||
|stubrunner.consumerName|| If you want to use a stub for each consumer and want to
|
||||
override the consumer name just change this value.
|
||||
|===============
|
||||
|
||||
[[stub-runner-stub-ids]]
|
||||
==== Stub Runner Stubs IDs
|
||||
|
||||
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
|
||||
----
|
||||
|
||||
Note that `version`, `classifier` and `port` are optional.
|
||||
|
||||
* If you do not provide the `port`, a random one will be picked.
|
||||
* If you do not provide the `classifier`, the default is used. (Note that you can
|
||||
pass an empty classifier this way: `groupId:artifactId:version:`).
|
||||
* If you do not provide the `version`, then the `+` will be passed and the latest one is
|
||||
downloaded.
|
||||
|
||||
`port` means the port of the WireMock server.
|
||||
|
||||
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].
|
||||
|
||||
[[stubrunner-docker]]
|
||||
=== Stub Runner Docker
|
||||
|
||||
We're publishing a `spring-cloud/spring-cloud-contract-stub-runner` Docker image
|
||||
that will start the standalone version of Stub Runner.
|
||||
|
||||
If you want to learn more about the basics of Maven, artifact ids,
|
||||
group ids, classifiers and Artifact Managers, just click here <<docker-project>>.
|
||||
|
||||
==== How to use it
|
||||
|
||||
Just execute the docker image. You can pass any of the <<common-properties-junit-spring>>
|
||||
as environment variables. The convention is that all the
|
||||
letters should be upper case. The camel case notation should
|
||||
and the dot (`.`) should be separated via underscore (`_`). E.g.
|
||||
the `stubrunner.repositoryRoot` property should be represented
|
||||
as a `STUBRUNNER_REPOSITORY_ROOT` environment variable.
|
||||
|
||||
==== Example of client side usage in a non JVM project
|
||||
|
||||
We'd like to use the stubs created in this <<docker-server-side>> step.
|
||||
Let's assume that we want to run the stubs on port `9876`. The NodeJS code
|
||||
is available here:
|
||||
|
||||
```bash
|
||||
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
|
||||
$ cd bookstore
|
||||
```
|
||||
|
||||
Let's run the Stub Runner Boot application with the stubs.
|
||||
|
||||
```bash
|
||||
# Provide the Spring Cloud Contract Docker version
|
||||
$ SC_CONTRACT_DOCKER_VERSION="..."
|
||||
# The IP at which the app is running and Docker container can reach it
|
||||
$ APP_IP="192.168.0.100"
|
||||
# Spring Cloud Contract Stub Runner properties
|
||||
$ STUBRUNNER_PORT="8083"
|
||||
# Stub coordinates 'groupId:artifactId:version:classifier:port'
|
||||
$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
|
||||
$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
|
||||
# Run the docker with Stub Runner Boot
|
||||
$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"
|
||||
```
|
||||
|
||||
What's happening is that
|
||||
|
||||
- a standalone Stub Runner application got started
|
||||
- it downloaded the stub with coordinates `com.example:bookstore:0.0.1.RELEASE:stubs` on port `9876`
|
||||
- it got downloaded from Artifactory running at `http://192.168.0.100:8081/artifactory/libs-release-local`
|
||||
- after a while Stub Runner will be running on port `8083`
|
||||
- and the stubs will be running at port `9876`
|
||||
|
||||
On the server side we built a stateful stub. Let's use curl to assert
|
||||
that the stubs are setup properly.
|
||||
|
||||
```bash
|
||||
# let's execute the first request (no response is returned)
|
||||
$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
|
||||
# Now time for the second request
|
||||
$ curl -X GET http://localhost:9876/api/books
|
||||
# You will receive contents of the JSON
|
||||
```
|
||||
|
||||
IMPORTANT: If you want use the stubs that you have built locally, on your host,
|
||||
then you should pass the environment variable `-e STUBRUNNER_STUBS_MODE=LOCAL` and mount
|
||||
the volume of your local m2 `-v "${HOME}/.m2/:/root/.m2:ro"`
|
||||
@@ -1,75 +0,0 @@
|
||||
[[stub-runner-for-messaging]]
|
||||
== Stub Runner for Messaging
|
||||
|
||||
Stub Runner can run the published stubs in memory. It can integrate with the following
|
||||
frameworks:
|
||||
|
||||
* Spring Integration
|
||||
* Spring Cloud Stream
|
||||
* Apache Camel
|
||||
* Spring AMQP
|
||||
|
||||
It also provides entry points to integrate with any other solution on the market.
|
||||
|
||||
IMPORTANT: If you have multiple frameworks on the classpath Stub Runner will need to
|
||||
define which one should be used. Let's assume that you have both AMQP, Spring Cloud Stream and Spring Integration
|
||||
on the classpath. Then you need to set `stubrunner.stream.enabled=false` and `stubrunner.integration.enabled=false`.
|
||||
That way the only remaining framework is Spring AMQP.
|
||||
|
||||
=== Stub triggering
|
||||
|
||||
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 you only need one
|
||||
or the other in your tests.
|
||||
|
||||
`StubTrigger` gives you the following options to trigger a message:
|
||||
|
||||
* <<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-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-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
|
||||
|
||||
[source,groovy]
|
||||
----
|
||||
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_all,indent=0]
|
||||
----
|
||||
|
||||
include::{tests_path}/spring-cloud-contract-stub-runner-camel/README.adoc[]
|
||||
|
||||
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[]
|
||||
Reference in New Issue
Block a user