From 72671c6631bbf3a9b13da8493a6a6f125f96a9e6 Mon Sep 17 00:00:00 2001 From: buildmaster Date: Thu, 26 Sep 2019 12:35:02 +0000 Subject: [PATCH] Sync docs from 2.1.x to gh-pages --- 2.1.x/multi/multi__customization.html | 16 +- 2.1.x/multi/multi__links.html | 4 +- 2.1.x/multi/multi__migrations.html | 14 +- .../multi__spring_cloud_contract_faq.html | 6 +- ...ti__spring_cloud_contract_stub_runner.html | 71 +- ..._cloud_contract_verifier_introduction.html | 2 +- ...ing_cloud_contract_verifier_messaging.html | 20 +- ..._spring_cloud_contract_verifier_setup.html | 693 +--------------- ...multi__spring_cloud_contract_wiremock.html | 20 +- ...lti__using_the_pluggable_architecture.html | 26 +- 2.1.x/multi/multi_contract-dsl.html | 70 +- .../multi/multi_gradle-add-gradle-plugin.html | 774 ++++++++++++++++++ 2.1.x/multi/multi_spring-cloud-contract.html | 2 +- .../multi_stub-runner-for-messaging.html | 28 +- 2.1.x/single/spring-cloud-contract.html | 429 ++++++---- .../licenses.html | 609 +------------- 2.1.x/spring-cloud-contract.xml | 140 +++- 17 files changed, 1325 insertions(+), 1599 deletions(-) create mode 100644 2.1.x/multi/multi_gradle-add-gradle-plugin.html diff --git a/2.1.x/multi/multi__customization.html b/2.1.x/multi/multi__customization.html index 3bcaae3da0..3a73c2dbf4 100644 --- a/2.1.x/multi/multi__customization.html +++ b/2.1.x/multi/multi__customization.html @@ -1,9 +1,9 @@ - 9. Customization

9. Customization

[Important]Important

This section is valid only for Groovy DSL

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

9.1 Extending the DSL

You can provide your own functions to the DSL. The key requirement for this feature is to + 10. Customization

10. Customization

[Important]Important

This section is valid only for Groovy DSL

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

10.1 Extending the DSL

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

  • Creating a JAR with reusable classes.
  • Referencing of these classes in the DSLs.

You can find the full example -here.

9.1.1 Common JAR

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

PatternUtils contains functions used by both the consumer and the producer.

package com.example;
+here.

10.1.1 Common JAR

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

PatternUtils contains functions used by both the consumer and the producer.

package com.example;
 
 import java.util.regex.Pattern;
 
@@ -134,8 +134,8 @@ maintain the static compatibility. Later in this document, you can see examples
 		return new ServerDslProperty( PatternUtils.ok(), "OK");
 	}
 }
-//end::impl[]

9.1.2 Adding the Dependency to the Project

In order for the plugins and IDE to be able to reference the common JAR classes, you need -to pass the dependency to your project.

9.1.3 Test the Dependency in the Project’s Dependencies

First, add the common jar dependency as a test dependency. Because your contracts files +//end::impl[]

10.1.2 Adding the Dependency to the Project

In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

10.1.3 Test the Dependency in the Project’s Dependencies

First, add the common jar dependency as a test dependency. Because your contracts files are available on the test resources path, the common jar classes automatically become visible in your Groovy files. The following examples show how to test the dependency:

Maven. 

<dependency>
@@ -146,7 +146,7 @@ visible in your Groovy files. The following examples show how to test the depend
 </dependency>

Gradle. 

testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")

-

9.1.4 Test a Dependency in the Plugin’s Dependencies

Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +

10.1.4 Test a Dependency in the Plugin’s Dependencies

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

Maven. 

<plugin>
 	<groupId>org.springframework.cloud</groupId>
@@ -173,7 +173,7 @@ following example:

Maven.  </plugin>

Gradle. 

classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"

-

9.1.5 Referencing classes in DSLs

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

package contracts.beer.rest
+

10.1.5 Referencing classes in DSLs

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

package contracts.beer.rest
 
 import com.example.ConsumerUtils
 import com.example.ProducerUtils
@@ -214,4 +214,4 @@ then:
 			contentType(applicationJson())
 		}
 	}
-}
[Important]Important

You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

\ No newline at end of file +}
[Important]Important

You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

\ No newline at end of file diff --git a/2.1.x/multi/multi__links.html b/2.1.x/multi/multi__links.html index fb9dc1b235..72f6d87b46 100644 --- a/2.1.x/multi/multi__links.html +++ b/2.1.x/multi/multi__links.html @@ -1,6 +1,6 @@ - 13. Links

13. Links

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

\ No newline at end of file diff --git a/2.1.x/multi/multi__migrations.html b/2.1.x/multi/multi__migrations.html index cb308e5a09..4691b82b09 100644 --- a/2.1.x/multi/multi__migrations.html +++ b/2.1.x/multi/multi__migrations.html @@ -1,8 +1,8 @@ - 12. Migrations

12. Migrations

[Tip]Tip

For up to date migration guides please visit + 13. Migrations

13. Migrations

[Tip]Tip

For up to date migration guides please visit the project’s wiki page.

This section covers migrating from one version of Spring Cloud Contract Verifier to the -next version. It covers the following versions upgrade paths:

12.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

12.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 +next version. It covers the following versions upgrade paths:

13.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

13.1.1 New structure of generated stubs

In 1.1.x we have introduced a change to the structure of generated stubs. If you have been using the @AutoConfigureWireMock notation to use the stubs from the classpath, it no longer works. The following example shows how the @AutoConfigureWireMock notation used to work:

@AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)

You must either change the location of the stubs to: @@ -80,17 +80,17 @@ structure presented in the previous snippet.

Maven.&nbs from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}" into "${project.buildDir}/resources/main/customer-stubs" }

-

12.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

12.2.1 Custom HttpServerStub

HttpServerStub includes a method that was not in version 1.1. The method is +

13.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

13.2.1 Custom HttpServerStub

HttpServerStub includes a method that was not in version 1.1. The method is String registeredMappings() If you have classes that implement HttpServerStub, you now have to implement the registeredMappings() method. It should return a String representing all mappings available in a single HttpServerStub.

See issue 355 for more -detail.

12.2.2 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: +detail.

13.2.2 New packages for generated tests

The flow for setting the generated tests package name will look like this:

  • Set basePackageForTests
  • If basePackageForTests was not set, pick the package from baseClassForTests
  • If baseClassForTests was not set, pick packageWithBaseClasses
  • If nothing got set, pick the default value: org.springframework.cloud.contract.verifier.tests

See issue 260 for more -detail.

12.2.3 New Methods in TemplateProcessor

In order to add support for fromRequest.path, the following methods had to be added to the +detail.

13.2.3 New Methods in TemplateProcessor

In order to add support for fromRequest.path, the following methods had to be added to the TemplateProcessor interface:

  • path()
  • path(int index)

See issue 388 for more -detail.

12.2.4 RestAssured 3.0

Rest Assured, used in the generated test classes, got bumped to 3.0. If +detail.

13.2.4 RestAssured 3.0

Rest Assured, used in the generated test classes, got bumped to 3.0. If you manually set versions of Spring Cloud Contract and the release train you might see the following exception:

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
 [ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist

This exception will occur due to the fact that the tests got generated with an old version of plugin and at test execution time you have an incompatible -version of the release train (and vice versa).

Done via issue 267

12.3 1.2.x → 2.0.x

\ No newline at end of file +version of the release train (and vice versa).

Done via issue 267

13.3 1.2.x → 2.0.x

\ No newline at end of file diff --git a/2.1.x/multi/multi__spring_cloud_contract_faq.html b/2.1.x/multi/multi__spring_cloud_contract_faq.html index 516614ae9b..0e20fbd636 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_faq.html +++ b/2.1.x/multi/multi__spring_cloud_contract_faq.html @@ -45,7 +45,7 @@ sides of the communication. You can pass the values:

Either via the

or using the $() method

$(consumer(...), producer(...))
 $(stub(...), test(...))
-$(client(...), server(...))

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

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +$(client(...), server(...))

You can read more about this in the Chapter 9, 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]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 @@ -567,7 +567,7 @@ 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 Section 10.1.1, “Pact Converter” section.

[Important]Important

Pact follows the Consumer Contract convention. That means +You can read more about it in the Section 11.1.1, “Pact Converter” section.

[Important]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 @@ -692,7 +692,7 @@ with pact:// protocol. E.g. p @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 Section 10.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

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

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

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

Starting from version 1.2.0 we turn on WireMock logging to +the Section 11.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

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

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

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

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

To turn off this feature just bump WireMock logging to ERROR

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

3.8.2 How can I see what got registered in the HTTP server stub?

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner, StubRunnerRule or diff --git a/2.1.x/multi/multi__spring_cloud_contract_stub_runner.html b/2.1.x/multi/multi__spring_cloud_contract_stub_runner.html index 181cb341b2..bca8656eee 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_stub_runner.html +++ b/2.1.x/multi/multi__spring_cloud_contract_stub_runner.html @@ -1,10 +1,10 @@ - 6. Spring Cloud Contract Stub Runner

6. Spring Cloud Contract Stub Runner

One of the issues that you might encounter while using Spring Cloud Contract Verifier is + 7. Spring Cloud Contract Stub Runner

7. 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.

6.1 Snapshot versions

Add the additional snapshot repository to your build.gradle file to use snapshot +automatically download and run the stubs for you.

7.1 Snapshot versions

Add the additional snapshot repository to your build.gradle file to use snapshot versions, which are automatically uploaded after every successful build:

Maven. 

<repositories>
 	<repository>
@@ -59,7 +59,28 @@ versions, which are automatically uploaded after every successful build:

</pluginRepository> </pluginRepositories>

Gradle.  -

buildscript {
+

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

"https://repo.spring.io/milestone" } maven { url "https://repo.spring.io/release" } }

-

6.2 Publishing Stubs as JARs

The easiest approach would be to centralize the way stubs are kept. For example, you can +

7.2 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]Tip

For both Maven and Gradle, the setup comes ready to work. However, you can customize it if you want to.

Maven. 

<!-- First disable the default jar setup in the properties section -->
@@ -157,9 +178,9 @@ publishing {
 		}
 	}
 }

-

6.3 Stub Runner Core

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +

7.3 Stub Runner Core

Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of Consumer Driven Contracts.

Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. -For messaging, special stub routes are defined.

6.3.1 Retrieving stubs

You can pick the following options of acquiring stubs

  • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
  • Classpath scanning solution that searches classpath via pattern to retrieve stubs
  • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

The latter example is described in the Custom Stub Runner section.

Stub downloading

You can control the stub downloading via the stubsMode switch. It picks value from the +For messaging, special stub routes are defined.

7.3.1 Retrieving stubs

You can pick the following options of acquiring stubs

  • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
  • Classpath scanning solution that searches classpath via pattern to retrieve stubs
  • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

The latter example is described in the Custom Stub Runner section.

Stub downloading

You can control the stub downloading via the stubsMode switch. It picks value from the StubRunnerProperties.StubsMode enum. You can use the following options

  • StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath
  • StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)
  • StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

Example:

@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)

Classpath scanning

If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH (or set nothing since CLASSPATH is the default value) then classpath will get scanned. Let’s look at the following example:

@AutoConfigureStubRunner(ids = {
@@ -246,7 +267,7 @@ case might be starting WireMock for the given artifact id, on an HTTPs port. Exa
 	}
 }

You can then reuse it via the annotation

@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
-		httpServerStubConfigurer = HttpsForFraudDetection)

Whenever an https port is found, it will take precedence over the http one.

6.3.2 Running stubs

Running using main app

You can set the following options to the main class:

-c, --classifier                Suffix for the jar containing stubs (e.
+		httpServerStubConfigurer = HttpsForFraudDetection)

Whenever an https port is found, it will take precedence over the http one.

7.3.2 Running stubs

Running using main app

You can set the following options to the main class:

-c, --classifier                Suffix for the jar containing stubs (e.
                                   g. 'stubs' if the stub jar would
                                   have a 'stubs' classifier for stubs:
                                   foobar-stubs ). Defaults to 'stubs'
@@ -309,7 +330,7 @@ mappings available for the given server:

["uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
 },
 ...
-]

Messaging Stubs

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

6.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

@ClassRule
+]

Messaging Stubs

Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

7.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

@ClassRule
 public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
 		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
@@ -459,9 +480,9 @@ def 'should outp
 	}
 }

Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

[Important]Important

To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). -If you don’t do this, then whenever you try to send a message an exception will be thrown.

6.4.1 Maven settings

The stub downloader honors Maven settings for a different local repository folder. -Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

6.4.2 Providing fixed ports

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of -JUnit rule.

6.4.3 Fluent API

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule
+If you don’t do this, then whenever you try to send a message an exception will be thrown.

7.4.1 Maven settings

The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

7.4.2 Providing fixed ports

You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

7.4.3 Fluent API

When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule
 public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
 		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
@@ -477,7 +498,7 @@ JUnit rule.

You can see that for this example the following test is valid:

then(rule.findStubUrl("loanIssuance"))
 		.isEqualTo(URI.create("http://localhost:12345").toURL());
 then(rule.findStubUrl("fraudDetectionServer"))
-		.isEqualTo(URI.create("http://localhost:12346").toURL());

6.4.4 Stub Runner with Spring

Sets up Spring configuration of the Stub Runner project.

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads + .isEqualTo(URI.create("http://localhost:12346").toURL());

7.4.4 Stub Runner with Spring

Sets up Spring configuration of the Stub Runner project.

By providing a list of stubs inside your configuration file the Stub Runner automatically downloads and registers in WireMock the selected stubs.

If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use its methods as presented below:

@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
 @SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
@@ -614,7 +635,7 @@ Value of the annotation can be the groupid:artifactidcom.example:foo, com.example:bar.

@StubRunnerPort("foo")
 int fooPort;
 @StubRunnerPort("com.example:bar")
-int barPort;

6.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

6.5.1 Stubbing Service Discovery

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

  • DiscoveryClient
  • Ribbon ServerList

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +int barPort;

7.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

7.5.1 Stubbing Service Discovery

The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

  • DiscoveryClient
  • Ribbon ServerList

that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

For example this test will pass

def 'should make service discovery work'() {
 	expect: 'WireMocks are running'
@@ -633,16 +654,16 @@ via a static block like presented below (example for Eureka)

static {
         System.setProperty("eureka.client.enabled", "false");
         System.setProperty("spring.cloud.config.failFast", "false");
-    }

6.5.2 Additional Configuration

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. + }

7.5.2 Additional Configuration

You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

[Tip]Tip

By default all service discovery will be stubbed. That means that regardless of the fact if you have an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be merged with the stubbed ones.

The default Maven configuration used by Stub Runner can be tweaked either -via the following system properties or environment variables

  • maven.repo.local - path to the custom maven local repository location
  • org.apache.maven.user-settings - path to custom maven user settings location
  • org.apache.maven.global-settings - path to maven global settings location

6.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +via the following system properties or environment variables

  • maven.repo.local - path to the custom maven local repository location
  • org.apache.maven.user-settings - path to custom maven user settings location
  • org.apache.maven.global-settings - path to maven global settings location

7.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to trigger the messaging labels and to access started WireMock servers.

One of the use-cases is to run some smoke (end to end) tests on a deployed application. You can check out the Spring Cloud Pipelines -project for more information.

6.6.1 How to use it?

Stub Runner Server

Just add the

compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

For the properties check the Stub Runner Spring section.

Stub Runner Server Fat Jar

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
+project for more information.

7.6.1 How to use it?

Stub Runner Server

Just add the

compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

For the properties check the Stub Runner Spring section.

Stub Runner Server Fat Jar

You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
 $ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...

Spring Cloud CLI

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI project you can start Stub Runner Boot by executing spring cloud stubrunner.

In order to pass the configuration just create a stubrunner.yml file in the current working directory or a subdirectory called config or in ~/.spring-cloud. The file could look like this @@ -652,7 +673,7 @@ or a subdirectory called config or in spring cloud stubrunner from your terminal window to start -the Stub Runner server. It will be available at port 8750.

6.6.2 Endpoints

HTTP

  • GET /stubs - returns a list of all running stubs in ivy:integer notation
  • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

Messaging

For Messaging

  • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
  • POST /triggers/{label} - executes a trigger with label
  • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

6.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
+the Stub Runner server. It will be available at port 8750.

7.6.2 Endpoints

HTTP

  • GET /stubs - returns a list of all running stubs in ivy:integer notation
  • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

Messaging

For Messaging

  • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
  • POST /triggers/{label} - executes a trigger with label
  • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

7.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
 @SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
 @ActiveProfiles("test")
 class StubRunnerBootSpec extends Specification {
@@ -739,7 +760,7 @@ the Stub Runner server. It will be available at port 8750<
 			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
 	}
 
-}

6.6.4 Stub Runner Boot with Service Discovery

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? +}

7.6.4 Stub Runner Boot with Service Discovery

One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? Let’s assume that you don’t want to deploy 50 microservice to a test environment in order to check if your application is working fine. You’ve already executed a suite of tests during the build process but you would also like to ensure that the packaging of your application is fine. What you can do @@ -774,7 +795,7 @@ and we want to have the stub runner feature turned on @Aut * be picked (3) - we provide a list of stubs to download (4) - we provide a list of

That way your deployed application can send requests to started WireMock servers via the service discovery. Most likely points 1-3 could be set by default in application.yml cause they are not likely to change. That way you can provide only the list of stubs to download whenever you start -the Stub Runner Boot.

6.7 Stubs Per Consumer

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

[Tip]Tip

This approach also allows you to immediately know which consumer is using which part of your API. +the Stub Runner Boot.

7.7 Stubs Per Consumer

There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

[Tip]Tip

This approach also allows you to immediately know which consumer is using which part of your API. You can remove part of a response that your API produces and you can see which of your autogenerated tests fails. If none fails then you can safely delete that part of the response cause nobody is using it.

Let’s look at the following example for contract defined for the producer called producer. There are 2 consumers: foo-consumer and bar-consumer.

Consumer foo-service

request {
@@ -827,25 +848,25 @@ Or set the test as follows:

Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

You can check out issue 224 for more -information about the reasons behind this change.

6.8 Common

This section briefly describes common properties, including:

6.8.1 Common Properties for JUnit and Spring

You can set repetitive properties by using system properties or Spring configuration +information about the reasons behind this change.

7.8 Common

This section briefly describes common properties, including:

7.8.1 Common Properties for JUnit and Spring

You can set repetitive properties by using system properties or Spring configuration properties. Here are their names with their default values:

Property nameDefault valueDescription

stubrunner.minPort

10000

Minimum value of a port for a started WireMock with stubs.

stubrunner.maxPort

15000

Maximum value of a port for a started WireMock with stubs.

stubrunner.repositoryRoot

 

Maven repo URL. If blank, then call the local maven repo.

stubrunner.classifier

stubs

Default classifier for the stub artifacts.

stubrunner.stubsMode

CLASSPATH

The way you want to fetch and register the stubs

stubrunner.ids

 

Array of Ivy notation stubs to download.

stubrunner.username

 

Optional username to access the tool that stores the JARs with stubs.

stubrunner.password

 

Optional password to access the tool that stores the JARs with stubs.

stubrunner.stubsPerConsumer

false

Set to true if you want to use different stubs for each consumer instead of registering all stubs for every consumer.

stubrunner.consumerName

 

If you want to use a stub for each consumer and want to -override the consumer name just change this value.

6.8.2 Stub Runner Stubs IDs

You can provide the stubs to download via the stubrunner.ids system property. They +override the consumer name just change this value.

7.8.2 Stub Runner Stubs IDs

You can provide the stubs to download via the stubrunner.ids system property. They follow this pattern:

groupId:artifactId:version:classifier:port

Note that version, classifier and port are optional.

  • If you do not provide the port, a random one will be picked.
  • If you do not provide the classifier, the default is used. (Note that you can pass an empty classifier this way: groupId:artifactId:version:).
  • If you do not provide the version, then the + will be passed and the latest one is downloaded.

port means the port of the WireMock server.

[Important]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 Aether versioning -ranges here.

6.9 Stub Runner Docker

We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +ranges here.

7.9 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 Section 4.5, “Docker Project”.

6.9.1 How to use it

Just execute the docker image. You can pass any of the Section 6.8.1, “Common Properties for JUnit and Spring” +group ids, classifiers and Artifact Managers, just click here Section 5.16, “Docker Project”.

7.9.1 How to use it

Just execute the docker image. You can pass any of the Section 7.8.1, “Common Properties for JUnit and Spring” as environment variables. The convention is that all the letters should be upper case. The camel case notation should and the dot (.) should be separated via underscore (_). E.g. the stubrunner.repositoryRoot property should be represented - as a STUBRUNNER_REPOSITORY_ROOT environment variable.

6.9.2 Example of client side usage in a non JVM project

We’d like to use the stubs created in this Section 4.5.4, “Server side (nodejs)” step. + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

7.9.2 Example of client side usage in a non JVM project

We’d like to use the stubs created in this Section 5.16.4, “Server side (nodejs)” step. Let’s assume that we want to run the stubs on port 9876. The NodeJS code is available here:

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

Let’s run the Stub Runner Boot application with the stubs.

# Provide the Spring Cloud Contract Docker version
@@ -865,4 +886,4 @@ $ curl -H "Conte
 $ curl -X GET http://localhost:9876/api/books
 # You will receive contents of the JSON
[Important]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"

\ No newline at end of file +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro"

\ No newline at end of file diff --git a/2.1.x/multi/multi__spring_cloud_contract_verifier_introduction.html b/2.1.x/multi/multi__spring_cloud_contract_verifier_introduction.html index fe8bdf7d14..52cacec2b8 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_verifier_introduction.html +++ b/2.1.x/multi/multi__spring_cloud_contract_verifier_introduction.html @@ -646,7 +646,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either a map notation or String with interpolations. -Consult the Chapter 8, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

You must understand the map notation in order to set up contracts. Please read the +Consult the Chapter 9, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

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

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

  • if an HTTP request is sent with all of

    • a PUT method on the /fraudcheck endpoint,
    • a JSON body with a client.id that matches the regular expression [0-9]{10} and loanAmount equal to 99999,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json,
  • then an HTTP response is sent to the consumer that

    • has status 200,
    • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and the rejectionReason field having value Amount too high,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json.

Once you are ready to check the API in practice in the integration tests, you need to diff --git a/2.1.x/multi/multi__spring_cloud_contract_verifier_messaging.html b/2.1.x/multi/multi__spring_cloud_contract_verifier_messaging.html index 46808027a0..863e4a7778 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_verifier_messaging.html +++ b/2.1.x/multi/multi__spring_cloud_contract_verifier_messaging.html @@ -1,8 +1,8 @@ - 5. Spring Cloud Contract Verifier Messaging

5. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that use messaging as a + 6. Spring Cloud Contract Verifier Messaging

6. 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.

5.1 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 +but you can also create one of your own and use that.

6.1 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]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]Important

If you want to use Spring Cloud Stream, remember to add a dependency on @@ -14,7 +14,7 @@ work.

</dependency>

Gradle. 

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

-

5.2 Manual Integration Testing

The main interface used by the tests is +

6.2 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 @@ -28,14 +28,14 @@ Here’s an example:

private MessageVerifier verifier;
   ...
 }
[Note]Note

If your tests require stubs as well, then @AutoConfigureStubRunner includes the -messaging configuration, so you only need the one annotation.

5.3 Publisher-Side Test Generation

Having the input or outputMessage sections in your DSL results in creation of tests +messaging configuration, so you only need the one annotation.

6.3 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 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]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).

5.3.1 Scenario 1: No Input Message

For the given contract:

Groovy DSL.  +jms).

6.3.1 Scenario 1: No Input Message

For the given contract:

Groovy DSL. 

			def contractDsl = Contract.make {
 				label 'some_label'
 				input {
@@ -88,7 +88,7 @@ outputMessage:
   DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
   assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
 
-'''

5.3.2 Scenario 2: Output Triggered by Input

For the given contract:

Groovy DSL.  +'''

6.3.2 Scenario 2: Output Triggered by Input

For the given contract:

Groovy DSL. 

			def contractDsl = Contract.make {
 				label 'some_label'
 				input {
@@ -159,7 +159,7 @@ then:
 and:
    DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
    assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
-"""

5.3.3 Scenario 3: No Output Message

For the given contract:

Groovy DSL.  +"""

6.3.3 Scenario 3: No Output Message

For the given contract:

Groovy DSL. 

			def contractDsl = Contract.make {
 				label 'some_label'
 				input {
@@ -207,8 +207,8 @@ when:
 then:
 	 noExceptionThrown()
 	 bookWasDeleted()
-'''

5.4 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 Chapter 7, Stub Runner for Messaging section.

Maven.  +'''

6.4 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 Chapter 8, Stub Runner for Messaging section.

Maven. 

<dependencies>
 	<dependency>
 		<groupId>org.springframework.cloud</groupId>
@@ -257,4 +257,4 @@ publishing {
 		}
 	}
 }

-

\ No newline at end of file +

\ No newline at end of file diff --git a/2.1.x/multi/multi__spring_cloud_contract_verifier_setup.html b/2.1.x/multi/multi__spring_cloud_contract_verifier_setup.html index 3f6843ee94..e32e347f8e 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_verifier_setup.html +++ b/2.1.x/multi/multi__spring_cloud_contract_verifier_setup.html @@ -1,694 +1,7 @@ - 4. Spring Cloud Contract Verifier Setup

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in the following ways:

4.1 Gradle Project

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

4.1.1 Prerequisites

In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a + 4. Spring Cloud Contract Verifier Setup

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in the following ways:

4.1 Gradle Project

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

4.1.1 Prerequisites

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

[Warning]Warning

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

4.1.2 Add Gradle Plugin with Dependencies

To add a Gradle plugin with dependencies, use code similar to this:

buildscript {
-	repositories {
-		mavenCentral()
-	}
-	dependencies {
-	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
-		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
-	}
-}
-
-apply plugin: 'groovy'
-apply plugin: 'spring-cloud-contract'
-
-dependencyManagement {
-	imports {
-		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
-	}
-}
-
-dependencies {
-	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
-	// example with adding Spock core and Spock Spring
-	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
-	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
-	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}

4.1.3 Gradle and Rest Assured 2.0

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

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

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

4.1.4 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as shown here:

buildscript {
-	repositories {
-		mavenCentral()
-		mavenLocal()
-		maven { url "https://repo.spring.io/snapshot" }
-		maven { url "https://repo.spring.io/milestone" }
-		maven { url "https://repo.spring.io/release" }
-	}
-}

4.1.5 Add stubs

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

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

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

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

  • shouldCreateUser()
  • shouldReturnUser()

4.1.6 Run the Plugin

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

4.1.7 Default Setup

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

contracts {
-    testFramework ='JUNIT'
-    testMode = 'MockMvc'
-    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
-    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
-    contractsDslDir = file("${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
-        }
-    }
-}

4.1.8 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as -shown here:

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

4.1.9 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.
  • imports: Creates an array with imports that should be included in generated tests -(for example ['org.myorg.Matchers']). By default, it creates an empty array.
  • staticImports: Creates an array with static imports that should be included in -generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty -array.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests.
  • baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This -setting takes precedence over packageWithBaseClasses and baseClassForTests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test -classes.
  • ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing -should be skipped. By default, it is an empty array.
  • contractsDslDir: Specifies the directory containing contracts written using the -GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-resources/contracts.
  • stubsOutputDir: Specifies the directory where the generated WireMock stubs from -the Groovy DSL should be placed.
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and -JUnit 5 are supported with JUnit 4 being the default framework.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

The following properties are used when you want to specify the location of the JAR -containing the contracts:

  • contractDependency: Specifies the Dependency that provides -groupid:artifactid:version:classifier coordinates. You can use the contractDependency -closure to set it up.
  • contractsPath: Specifies the path to the jar. If contract dependencies are -downloaded, the path defaults to groupid/artifactid where groupid is slash -separated. Otherwise, it scans contracts under the provided directory.
  • contractsMode: Specifies the mode of downloading contracts (whether the -JAR is available offline, remotely etc.)
  • deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.1.10 Single Base Class for All Tests

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

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

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

4.1.11 Different Base Classes for Contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • Provide explicit mapping via baseClassMappings

By Convention

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

packageWithBaseClasses = 'com.example.base'

By Mapping

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

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

Let’s assume that you have contracts under - - src/test/resources/contract/com/ - - src/test/resources/contract/foo/

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

4.1.12 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

4.1.13 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to call the pushStubsToScm -task. Example:

$ ./gradlew pushStubsToScm

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible -configuration options that you can pass either via -the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, -via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, -a system property or an environment variable.

4.1.14 Spring Cloud Contract Verifier on the Consumer Side

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

./gradlew generateClientStubs
[Note]Note

The stubsOutputDir option has to be set for stub generation to work.

When present, JSON stubs can be used in automated tests of consuming a service.

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

LoanApplication makes a call to FraudDetection service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

4.2 Maven Project

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

4.2.1 Add maven plugin

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

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

Next, add the Spring Cloud Contract Verifier Maven plugin:

<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<version>${spring-cloud-contract.version}</version>
-	<extensions>true</extensions>
-	<configuration>
-		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
-		<convertToYaml>true</convertToYaml>
-	</configuration>
-</plugin>

You can read more in the -Spring -Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

4.2.2 Maven and Rest Assured 2.0

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

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

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

4.2.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your -pom.xml, as shown here:

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

4.2.4 Add stubs

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

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

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods

  • shouldCreateUser()
  • shouldReturnUser()

4.2.5 Run plugin

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

4.2.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin -definition or the execution definition, as shown here:

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

4.2.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, -which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to -Explicit for real HTTP calls.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, -the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. -If neither of these values are set, then the value is set to -org.springframework.cloud.contract.verifier.tests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test -classes.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you -use Spock classes, the class is spock.lang.Specification.
  • contractsDirectory: Specifies a directory containing contracts written with the -GroovyDSL. The default directory is /src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated -from the Groovy DSL should be placed. By default its value is -$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and -JUnit 5 are supported with JUnit 4 being the default framework.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This -setting takes precedence over baseClassForTests. The convention is such that, if you -have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set -the value of the packageWithBaseClasses property to com.example.base, then Spring -Cloud Contract Verifier assumes that there is a BarBazBase class under the -com.example.base package. In other words, the system takes the last two parts of the -package, if they exist, and forms a class with a Base suffix.
  • baseClassMappings: Specifies a list of base class mappings that provide -contractPackageRegex, which is checked against the package where the contract is -located, and baseClassFQN, which maps to the fully qualified name of the base class for -the matched contract. For example, if you have a contract under -src/test/resources/contract/foo/bar/baz/ and map the property -.* → com.example.base.BaseClass, then the test class generated from these contracts -extends com.example.base.BaseClass. This setting takes precedence over -packageWithBaseClasses and baseClassForTests.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract -components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

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

  • contractDependency: The contract dependency that contains all the packaged contracts.
  • contractsPath: The path to the concrete contracts in the JAR with packaged contracts. -Defaults to groupid/artifactid where gropuid is slash separated.
  • contractsMode: Picks the mode in which stubs will be found and registered
  • deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories
  • contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, -use the current Maven ones.
  • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.
  • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.
  • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.
  • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

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

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.2.8 Single Base Class for All Tests

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

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

You can also setup the whole context if necessary.

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

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app -similarly, as you might find in regular integration tests.

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

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

4.2.9 Different base classes for contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • provide explicit mapping via baseClassMappings

By Convention

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

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

By Mapping

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

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

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

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

4.2.10 Invoking generated tests

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

For Groovy Spock code, use the following:

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

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

4.2.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and -stubs, you might want to automate the step of pushing stubs to -the repository. To do that, it’s enough to add the pushStubsToScm -goal. Example:

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

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible -configuration options that you can pass either via -the <configuration><contractProperties> map, a system property -or an environment variable.

4.2.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

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

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

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

<build>
-    <pluginManagement>
-        <plugins>
-            <!--This plugin's configuration is used to store Eclipse m2e settings
-                only. It has no influence on the Maven build itself. -->
-            <plugin>
-                <groupId>org.eclipse.m2e</groupId>
-                <artifactId>lifecycle-mapping</artifactId>
-                <version>1.0.0</version>
-                <configuration>
-                    <lifecycleMappingMetadata>
-                        <pluginExecutions>
-                             <pluginExecution>
-                                <pluginExecutionFilter>
-                                    <groupId>org.springframework.cloud</groupId>
-                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
-                                    <versionRange>[1.0,)</versionRange>
-                                    <goals>
-                                        <goal>convert</goal>
-                                    </goals>
-                                </pluginExecutionFilter>
-                                <action>
-                                    <execute />
-                                </action>
-                             </pluginExecution>
-                        </pluginExecutions>
-                    </lifecycleMappingMetadata>
-                </configuration>
-            </plugin>
-        </plugins>
-    </pluginManagement>
-</build>

4.2.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract -verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, -in Maven you will require some additional setup in order to make the tests compile and execute properly.

First of all, you will have to use a plugin, such as GMavenPlus plugin, -to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the -path where your base test classes are defined and the path were the generated contract tests are added. -Please refer to the example below:

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven -Surefire plugin setup, like in the following example:

4.3 Stubs and Transitive Dependencies

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

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

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

  • Mark all application dependencies as optional
  • Create a separate artifactid for the stubs
  • Exclude dependencies on the consumer side

Mark all application dependencies as optional

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

Create a separate artifactid for the stubs

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

Exclude dependencies on the consumer side

As a consumer, if you add the stub dependency to your classpath, you can explicitly -exclude the unwanted dependencies.

4.4 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to -stick to the proper naming convention while creating your contracts. The convention -requires including an order number followed by an underscore. This will work regardles - of whether you’re working with YAML or Groovy. Example:

my_contracts_dir\
-  scenario1\
-    1_login.groovy
-    2_showCart.groovy
-    3_logout.groovy

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a -name of scenario1 and the three following steps:

  1. login marked as Started pointing to…​
  2. showCart marked as Step1 pointing to…​
  3. logout marked as Step2 which will close the scenario.

More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

4.5 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image -that contains a project that will generate tests and execute them in EXPLICIT mode -against a running application.

[Tip]Tip

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

4.5.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to -explain the basic terms behind Spring Cloud Contract packaging defaults.

Part of the following definitions were taken from the Maven Glossary

  • Project: Maven thinks in terms of projects. Everything that you -will build are projects. Those projects follow a well defined -“Project Object Model”. Projects can depend on other projects, -in which case the latter are called “dependencies”. A project may -consistent of several subprojects, however these subprojects are still -treated equally as projects.
  • Artifact: An artifact is something that is either produced or used -by a project. Examples of artifacts produced by Maven for a project -include: JARs, source and binary distributions. Each artifact -is uniquely identified by a group id and an artifact ID which is -unique within a group.
  • JAR: JAR stands for Java ARchive. It’s a format based on -the ZIP file format. Spring Cloud Contract packages the contracts and generated -stubs in a JAR file.
  • GroupId: A group ID is a universally unique identifier for a project. -While this is often just the project name (eg. commons-collections), -it is helpful to use a fully-qualified package name to distinguish it -from other projects with a similar name (eg. org.apache.maven). -Typically, when published to the Artifact Manager, the GroupId will get -slash separated and form part of the URL. E.g. for group id com.example -and artifact id application would be /com/example/application/.
  • Classifier: The Maven dependency notation looks as follows: -groupId:artifactId:version:classifier. The classifier is additional suffix -passed to the dependency. E.g. stubs, sources. The same dependency -e.g. com.example:application can produce multiple artifacts that -differ from each other with the classifier.
  • Artifact manager: When you generate binaries / sources / packages, you would -like them to be available for others to download / reference or reuse. In case -of the JVM world those artifacts would be JARs, for Ruby these are gems -and for Docker those would be Docker images. You can store those artifacts -in a manager. Examples of such managers can be Artifactory -or Nexus.

4.5.2 How it works

The image searches for contracts under the /contracts folder. -The output from running the tests will be available under -/spring-cloud-contract/build folder (it’s useful for debugging -purposes).

It’s enough for you to mount your contracts, pass the environment variables - and the image will:

  • generate the contract tests
  • execute the tests against the provided URL
  • generate the WireMock stubs
  • (optional - turned on by default) publish the stubs to a Artifact Manager

Environment Variables

The Docker image requires some environment variables to point to -your running application, to the Artifact manager instance etc.

  • PROJECT_GROUP - your project’s group id. Defaults to com.example
  • PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT
  • PROJECT_NAME - artifact id. Defaults to example
  • REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally
  • REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured
  • REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured
  • PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

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

  • EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example
  • EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.
  • EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default
  • EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest
  • EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. -If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local -which is the default URL of Artifactory running locally
  • EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. -Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. -for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.
  • EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts -from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. -You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

These environment variables are used when tests are executed:

  • APPLICATION_BASE_URL - url against which tests should be executed. -Remember that it has to be accessible from the Docker container (e.g. localhost -will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application

4.5.3 Example of usage

Let’s take a look at a simple MVC application

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

The contracts are available under /contracts folder.

4.5.4 Server side (nodejs)

Since we want to run tests, we could just execute:

$ npm test

however, for learning purposes, let’s split it into pieces:

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

What will happen is that via bash scripts:

  • infrastructure will be set up (MongoDb, Artifactory). -In real life scenario you would just run the NodeJS application -with mocked database. In this example we want to show how we can -benefit from Spring Cloud Contract in no time.
  • due to those constraints the contracts also represent the -stateful situation

    • first request is a POST that causes data to get inserted to the database
    • second request is a GET that returns a list of data with 1 previously inserted element
  • the NodeJS application will be started (on port 3000)
  • contract tests will be generated via Docker and tests -will be executed against the running application

    • the contracts will be taken from /contracts folder.
    • the output of the test execution is available under -node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out -under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

\ No newline at end of file +docs for more information

\ No newline at end of file diff --git a/2.1.x/multi/multi__spring_cloud_contract_wiremock.html b/2.1.x/multi/multi__spring_cloud_contract_wiremock.html index 9f41cedc30..242c6baaf7 100644 --- a/2.1.x/multi/multi__spring_cloud_contract_wiremock.html +++ b/2.1.x/multi/multi__spring_cloud_contract_wiremock.html @@ -1,6 +1,6 @@ - 11. Spring Cloud Contract WireMock

11. Spring Cloud Contract WireMock

The Spring Cloud Contract WireMock modules let you use WireMock in a + 12. Spring Cloud Contract WireMock

12. Spring Cloud Contract WireMock

The Spring Cloud Contract WireMock modules let you use WireMock in a Spring Boot application. Check out the samples for more details.

If you have a Spring Boot application that uses Tomcat as an embedded server (which is @@ -38,7 +38,7 @@ your test. The following code shows an example:

<
 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.

11.1 Registering Stubs Automatically

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

12.1 Registering Stubs Automatically

If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file system or classpath (by default, from file:src/test/resources/mappings). You can customize the locations 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 @@ -58,7 +58,7 @@ public class WiremockImportApplicationTests { }

[Note]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.

@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

11.2 Using Files to Specify the Stub Bodies

WireMock can read response bodies from files on the classpath or the file system. In that +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

12.2 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 @@ -69,7 +69,7 @@ supported. A list of values can be given, in which case WireMock resolves the fi that exists when it needs to find a response body.

[Note]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.

11.3 Alternative: Using JUnit Rules

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +effect on the stubs loaded explicitly from the stubs attribute.

12.3 Alternative: Using JUnit Rules

For a more conventional WireMock experience, you can use JUnit @Rules to start and stop the server. To do so, use the WireMockSpring convenience class to obtain an Options instance, as shown in the following example:

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@@ -101,7 +101,7 @@ instance, as shown in the following example:

The @ClassRule means that the server shuts down after all the methods in this class -have been run.

11.4 Relaxed SSL Validation for Rest Template

WireMock lets you stub a "secure" server with an "https" URL protocol. If your +have been run.

12.4 Relaxed SSL Validation for Rest Template

WireMock lets you stub a "secure" server with an "https" URL protocol. If your application wants to contact that stub server in an integration test, it will find that the SSL certificates are not valid (the usual problem with self-installed certificates). The best option is often to re-configure the client to use "http". If that’s not an @@ -128,7 +128,7 @@ classpath and it is selected by the RestTemplateBuilderjava.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.

11.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +property to false.

12.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a Spring MockRestServiceServer. The following code shows an example:

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.NONE)
 public class WiremockForDocsMockServerApplicationTests {
@@ -160,7 +160,7 @@ pattern. The JSON format is the normal WireMock format, which you can read about
 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).

11.6 Customization of WireMock configuration

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +Wiremock dependencies and exclude the Spring Boot container (if there is one).

12.6 Customization of WireMock configuration

You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type in order to customize the WireMock configuration (e.g. add custom transformers). Example:

		@Bean
 		WireMockConfigurationCustomizer optionsCustomizer() {
@@ -170,7 +170,7 @@ Example:

		// perform your customization here
 				}
 			};
-		}

11.7 Generating Stubs using REST Docs

Spring REST Docs can be used to generate + }

12.7 Generating Stubs using REST Docs

Spring REST Docs can be used to generate documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your @@ -272,7 +272,7 @@ 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.

11.8 Generating Contracts by Using REST Docs

You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +document.

12.8 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, @@ -320,4 +320,4 @@ Contract.make { } } }

The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be index/dsl-contract.adoc.

\ No newline at end of file +contract. The location of this file would be index/dsl-contract.adoc.

\ No newline at end of file diff --git a/2.1.x/multi/multi__using_the_pluggable_architecture.html b/2.1.x/multi/multi__using_the_pluggable_architecture.html index f42ac89dbf..1fa8e36bbf 100644 --- a/2.1.x/multi/multi__using_the_pluggable_architecture.html +++ b/2.1.x/multi/multi__using_the_pluggable_architecture.html @@ -1,11 +1,11 @@ - 10. Using the Pluggable Architecture

10. Using the Pluggable Architecture

You may encounter cases where you have your contracts have been defined in other formats, + 11. Using the Pluggable Architecture

11. Using the Pluggable Architecture

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

10.1 Custom Contract Converter

The ContractConverter interface lets you register your own implementation of a contract +can generate stubs for other HTTP server implementations).

11.1 Custom Contract Converter

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

package org.springframework.cloud.contract.spec
 
 /**
@@ -47,7 +47,7 @@ structure converter. The following code listing shows the 
 conversion. Also, you must define how to perform that conversion in both directions.

[Important]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:

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

10.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of +org.springframework.cloud.contract.verifier.converter.YamlContractConverter

11.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we present how to add Pact support for your project. Note however that not all functionality is supported. Starting with v3 you can combine multiple matcher for the same element; @@ -57,7 +57,7 @@ Next to that the request and path matchers are skipped during the conversion. When using a date, time or datetime value generator with a given format, the given format will be skipped and the ISO format will be used.

In order to properly support the Spring Cloud Contract way of doing messaging with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

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

10.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

11.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the src/test/resources/contracts folder.

{
   "provider": {
     "name": "Provider"
@@ -155,7 +155,7 @@ set a metaData entry in the Pact file, with key "version": "3.5.13"
     }
   }
-}

The remainder of this section about using Pact refers to the preceding file.

10.1.3 Pact for Producers

On the producer side, you must add two additional dependencies to your plugin +}

The remainder of this section about using Pact refers to the preceding file.

11.1.3 Pact for Producers

On the producer side, you must add two additional dependencies to your plugin configuration. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use.

Maven. 

<plugin>
@@ -221,7 +221,7 @@ test might be as follows:

"transformers" : [ "response-template" ]
   },
-}

10.1.4 Pact for Consumers

On the consumer side, you must add two additional dependencies to your project +}

11.1.4 Pact for Consumers

On the consumer side, you must add two additional dependencies to your project dependencies. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use.

Maven. 

<dependency>
@@ -231,7 +231,7 @@ current Pact version that you use.

Maven.  </dependency>

Gradle. 

testCompile "org.springframework.cloud:spring-cloud-contract-pact"

-

10.2 Using the Custom Test Generator

If you want to generate tests for languages other than Java or you are not happy with the +

11.2 Using the Custom Test Generator

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

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

package org.springframework.cloud.contract.verifier.builder
 
@@ -301,7 +301,7 @@ trait SingleTestGenerator {
 	}
 }

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

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

10.3 Using the Custom Stub Generator

If you want to generate stubs for stub servers other than WireMock, you can plug in your +com.example.MyGenerator

11.3 Using the Custom Stub Generator

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

package org.springframework.cloud.contract.verifier.converter
 
@@ -344,7 +344,7 @@ own implementation of the StubGenerator interface.
 example:

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

The default implementation is the WireMock stub generation.

[Tip]Tip

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

10.4 Using the Custom Stub Runner

If you decide to use a custom stub generation, you also need a custom way of running +DSL, you can produce both WireMock stubs and Pact files.

11.4 Using the Custom Stub Runner

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

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

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

package org.springframework.cloud.contract.stubrunner.provider.moco
@@ -430,7 +430,7 @@ HTTP Stub server implementation, which might resemble the following example:

}

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

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

Now you can run stubs with Moco.

[Important]Important

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

10.5 Using the Custom Stub Downloader

You can customize the way your stubs are downloaded by creating an implementation of the +implementation is used. If you provide more than one, the first one on the list is used.

11.5 Using the Custom Stub Downloader

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

package com.example;
 
 class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
@@ -456,16 +456,16 @@ org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
 com.example.CustomStubDownloaderBuilder

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

[Important]Important

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

10.6 Using the SCM Stub Downloader

Whenever the repositoryRoot starts with a SCM protocol +If you provide more than one, then the first one on the list is used.

11.6 Using the SCM Stub Downloader

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

Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader’s behaviour. Below you can find the list of -properties

Table 10.1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

 

Git clone username

* git.password (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

 

Git clone password

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

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

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

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

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

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

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


10.7 Using the Pact Stub Downloader

Whenever the repositoryRoot starts with a Pact protocol +properties

Table 11.1. SCM Stub Downloader properties

Type of a property

Name of the property

Description

* git.branch (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

master

Which branch to checkout

* git.username (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

 

Git clone username

* git.password (plugin prop)

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

* STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

 

Git clone password

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

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

* STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

10

Number of attempts to push the commits to origin

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

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

* STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

1000

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


11.7 Using the Pact Stub Downloader

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

Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader’s behaviour. Below you can find the list of -properties

Table 10.2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

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

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

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

Password used to connect to the Pact Broker

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

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

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


\ No newline at end of file +properties

Table 11.2. SCM Stub Downloader properties

Name of a property

Default

Description

* pactbroker.host (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

Host from URL passed to repositoryRoot

What is the URL of Pact Broker

* pactbroker.port (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

Port from URL passed to repositoryRoot

What is the port of Pact Broker

* pactbroker.protocol (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

Protocol from URL passed to repositoryRoot

What is the protocol of Pact Broker

* pactbroker.tags (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

Version of the stub, or latest if version is +

What tags should be used to fetch the stub

* pactbroker.auth.scheme (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

Basic

What kind of authentication should be used to connect to the Pact Broker

* pactbroker.auth.username (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

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

Username used to connect to the Pact Broker

* pactbroker.auth.password (plugin prop)

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

* STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

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

Password used to connect to the Pact Broker

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

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

* STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

false

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


\ No newline at end of file diff --git a/2.1.x/multi/multi_contract-dsl.html b/2.1.x/multi/multi_contract-dsl.html index 57c00e4eb8..9146cf9583 100644 --- a/2.1.x/multi/multi_contract-dsl.html +++ b/2.1.x/multi/multi_contract-dsl.html @@ -1,6 +1,6 @@ - 8. Contract DSL

8. Contract DSL

Spring Cloud Contract supports out of the box 2 types of DSL. One written in + 9. Contract DSL

9. Contract DSL

Spring Cloud Contract supports out of the box 2 types of DSL. One written in Groovy and one written in YAML.

If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a tiny subset of it (only literals, method calls and closures). Also, the DSL is statically @@ -57,13 +57,13 @@ response: regex: bar - key: foo3 command: andMeToo($it)

[Tip]Tip

You can compile contracts to stubs mapping using standalone maven command: -mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

8.1 Limitations

[Warning]Warning

Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

9.1 Limitations

[Warning]Warning

Spring Cloud Contract Verifier does not properly support XML. Please use JSON or help us implement this feature.

[Warning]Warning

The support for verifying the size of JSON arrays is experimental. If you want to turn it on, please set the value of the following system property to true: spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. You can also provide the assertJsonSize property in the plugin configuration.

[Warning]Warning

Because JSON structure can have any form, it can be impossible to parse it properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That -is why you should use the Groovy Map notation.

8.2 Common Top-Level elements

The following sections describe the most common top-level elements:

8.2.1 Description

You can add a description to your contract. The description is arbitrary text. The +is why you should use the Groovy Map notation.

9.2 Common Top-Level elements

The following sections describe the most common top-level elements:

9.2.1 Description

You can add a description to your contract. The description is arbitrary text. The following code shows an example:

Groovy DSL. 

			org.springframework.cloud.contract.spec.Contract.make {
 				description('''
@@ -125,7 +125,7 @@ response:
         regex: bar
       - key: foo3
         command: andMeToo($it)

-

8.2.2 Name

You can provide a name for your contract. Assume that you provided the following name: +

9.2.2 Name

You can provide a name for your contract. Assume that you provided the following name: should register a user. If you do so, the name of the autogenerated test is validate_should_register_a_user. Also, the name of the stub in a WireMock stub is should_register_a_user.json.

[Important]Important

You must ensure that the name does not contain any characters that make the @@ -137,14 +137,14 @@ override each other.

Groovy DSL.  }

YAML. 

name: some name

-

8.2.3 Ignoring Contracts

If you want to ignore a contract, you can either set a value of ignored contracts in the +

9.2.3 Ignoring Contracts

If you want to ignore a contract, you can either set a value of ignored contracts in the plugin configuration or set the ignored property on the contract itself:

Groovy DSL. 

org.springframework.cloud.contract.spec.Contract.make {
 	ignored()
 }

YAML. 

ignored: true

-

8.2.4 Passing Values from Files

Starting with version 1.2.0, you can pass values from files. Assume that you have the +

9.2.4 Passing Values from Files

Starting with version 1.2.0, you can pass values from files. Assume that you have the following resources in our project.

└── src
     └── test
         └── resources
@@ -234,7 +234,7 @@ response:
   bodyFromFileAsBytes: response.pdf
   headers:
     Content-Type: application/octet-stream

-

[Important]Important

You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

8.2.5 HTTP Top-Level Elements

The following methods can be called in the top-level closure of a contract definition. +

[Important]Important

You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

9.2.5 HTTP Top-Level Elements

The following methods can be called in the top-level closure of a contract definition. request and response are mandatory. priority is optional.

Groovy DSL. 

org.springframework.cloud.contract.spec.Contract.make {
 	// Definition of HTTP request part of the contract
@@ -267,7 +267,7 @@ response:
 ...

[Important]Important

If you want to make your contract have a higher value of priority you need to pass a lower number to the priority tag / method. E.g. priority with -value 5 has higher priority than priority with value 10.

8.3 Request

The HTTP protocol requires only method and url to be specified in a request. The +value 5 has higher priority than priority with value 10.

9.3 Request

The HTTP protocol requires only method and url to be specified in a request. The same information is mandatory in request definition of the Contract.

Groovy DSL. 

org.springframework.cloud.contract.spec.Contract.make {
 	request {
@@ -560,7 +560,7 @@ parametrization of either fileName or "transformers" : [ "response-template", "foo-transformer" ]
   }
 }
-	'''

8.4 Response

The response must contain an HTTP status code and may contain other information. The + '''

9.4 Response

The response must contain an HTTP status code and may contain other information. The following code shows an example:

Groovy DSL. 

org.springframework.cloud.contract.spec.Contract.make {
 	request {
@@ -581,13 +581,13 @@ status: 200

Besides status, the response may contain headers, cookies and a body, both of which are specified the same way as in the request (see the previous paragraph).

[Tip]Tip

Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus methods to provide a meaningful status instead of a digit. E.g. you can call -OK() for a status 200 or BAD_REQUEST() for 400.

8.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +OK() for a status 200 or BAD_REQUEST() for 400.

9.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not want to force the consumers to stub their clocks to always return the same value of time so that it gets matched by the stub.

For Groovy DSL you can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in a separate section called bodyMatchers.

[Note]Note

Before 2.0.0 these were set using testMatchers and stubMatchers, -check out the migration guide for more information.

For YAML you can only use the matchers section.

8.5.1 Dynamic properties inside the body

[Important]Important

This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can set the properties inside the body either with the value method or, if you use +check out the migration guide for more information.

For YAML you can only use the matchers section.

9.5.1 Dynamic properties inside the body

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can set the properties inside the body either with the value method or, if you use the Groovy map notation, with $(). The following example shows how to set dynamic properties with the value method:

value(consumer(...), producer(...))
 value(c(...), p(...))
@@ -596,8 +596,8 @@ value(client(...), server(...))

The following example shows how to set d $(c(...), p(...)) $(stub(...), test(...)) $(client(...), server(...))

Both approaches work equally well. stub and client methods are aliases over the consumer -method. Subsequent sections take a closer look at what you can do with those values.

8.5.2 Regular expressions

[Important]Important

This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can use regular expressions to write your requests in Contract DSL. Doing so is +method. Subsequent sections take a closer look at what you can do with those values.

9.5.2 Regular expressions

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can use regular expressions to write your requests in Contract DSL. Doing so is particularly useful when you want to indicate that a given response should be provided for requests that follow a given pattern. Also, you can use regular expressions when you need to use patterns and not exact values both for your test and your server side tests.

The following example shows how to use regular expressions to write a request:

org.springframework.cloud.contract.spec.Contract.make {
@@ -847,8 +847,8 @@ T anyOf(String... values)

and this is an example of how you can referenc anyOf : $(anyOf('foo', 'bar')) ]) } -}

8.5.3 Passing Optional Parameters

[Important]Important

This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

It is possible to provide optional parameters in your contract. However, you can provide +}

9.5.3 Passing Optional Parameters

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

It is possible to provide optional parameters in your contract. However, you can provide optional parameters only for the following:

  • STUB side of the Request
  • TEST side of the Response

The following example shows how to provide optional parameters:

org.springframework.cloud.contract.spec.Contract.make {
 	priority 1
 	request {
@@ -913,8 +913,8 @@ expression that must be present 0 or more times.

If you use Spock for, the }, "priority" : 1 } -'''

8.5.4 Executing Custom Methods on the Server Side

[Important]Important

This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can define a method call that executes on the server side during the test. Such a +'''

9.5.4 Executing Custom Methods on the Server Side

[Important]Important

This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

You can define a method call that executes on the server side during the test. Such a method can be added to the class defined as "baseClassForTests" in the configuration. The following code shows an example of the contract portion of the test case:

org.springframework.cloud.contract.spec.Contract.make {
 	request {
@@ -977,7 +977,7 @@ It should resemble the following code:

"/something");
 
 // then:
- assertThat(response.statusCode()).isEqualTo(200);

8.5.5 Referencing the Request from the Response

The best situation is to provide fixed values, but sometimes you need to reference a + assertThat(response.statusCode()).isEqualTo(200);

9.5.5 Referencing the Request from the Response

The best situation is to provide fixed values, but sometimes you need to reference a request in your response.

If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets you reference a bunch of elements from the HTTP request. You can use the following options:

  • fromRequest().url(): Returns the request URL and query parameters.
  • fromRequest().query(String key): Returns the first query parameter with a given name.
  • fromRequest().query(String key, int index): Returns the nth query parameter with a @@ -1091,7 +1091,7 @@ in sending the following response body:

    }
    [Important]Important

    This feature works only with WireMock having a version greater than or equal to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into -proper values. Additionally, it registers two helper functions:

    • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
    • jsonpath: For a given parameter, find an object in the request body.

8.5.6 Registering Your Own WireMock Extension

WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +proper values. Additionally, it registers two helper functions:

  • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
  • jsonpath: For a given parameter, find an object in the request body.

9.5.6 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. @@ -1141,7 +1141,7 @@ org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter

[Important]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.

8.5.7 Dynamic Properties in the Matchers Sections

If you work with Pact, the following discussion may seem familiar. +want the transformation to be applied only for a mapping that explicitly requires it.

9.5.7 Dynamic Properties in the Matchers Sections

If you work with Pact, the following discussion may seem familiar. Quite a few users are used to having a separation between the body and setting the dynamic parts of a contract.

You can use the bodyMatchers section for two reasons:

  • Define the dynamic values that should end up in a stub. You can set it in the request or inputMessage part of your contract.
  • Verify the result of your test. @@ -1651,7 +1651,7 @@ and: assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$") assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")

    As you can see, the assertion is malformed. Only the first element of the array got asserted. In order to fix this, you should apply the assertion to the whole $.events -collection and assert it with the byCommand(…​) method.

8.6 JAX-RS Support

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +collection and assert it with the byCommand(…​) method.

9.6 JAX-RS Support

The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs to define protected WebTarget webTarget and server initialization. The only option for testing JAX-RS API is to start a web server. Also, a request with a body needs to have a content type set. Otherwise, the default of application/octet-stream gets used.

In order to use JAX-RS mode, use the following settings:

testMode == 'JAXRSCLIENT'

The following example shows a generated test API:

					'''
@@ -1676,7 +1676,7 @@ content type set. Otherwise, the default of application/oc
  // and:
   DocumentContext parsedJson = JsonPath.parse(responseAsString);
   assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
-'''

8.7 Async Support

If you’re using asynchronous communication on the server side (your controllers are +'''

9.7 Async Support

If you’re using asynchronous communication on the server side (your controllers are returning Callable, DeferredResult, and so on), then, inside your contract, you must provide an async() method in the response section. The following code shows an example:

Groovy DSL. 

org.springframework.cloud.contract.spec.Contract.make {
@@ -1708,7 +1708,7 @@ provide an async() method in the response:
     fixedDelayMilliseconds: 1000

-

8.8 Working with Context Paths

Spring Cloud Contract supports context paths.

[Important]Important

The only change needed to fully support context paths is the switch on the +

9.8 Working with Context Paths

Spring Cloud Contract supports context paths.

[Important]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.

Maven.  @@ -1752,7 +1752,7 @@ socket.

Consider the following contract:

or
 	}
 }

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).

8.9 Working with WebFlux

Spring Cloud Contract offers two ways of working with WebFlux.

8.9.1 WebFlux with WebTestClient

One of them is via the WebTestClient mode.

Maven.  +that information (for example, in the stubs, you have to call /my-context-path/url).

9.9 Working with WebFlux

Spring Cloud Contract offers two ways of working with WebFlux.

9.9.1 WebFlux with WebTestClient

One of them is via the WebTestClient mode.

Maven. 

<plugin>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-contract-maven-plugin</artifactId>
@@ -1778,7 +1778,7 @@ for WebFlux:

new ProducerController(personToCheck -> personToCheck.age >= 20));
 	}
 }
-}

8.9.2 WebFlux with Explicit mode

Another way is with the EXPLICIT mode in your generated tests +}

9.9.2 WebFlux with Explicit mode

Another way is with the EXPLICIT mode in your generated tests to work with WebFlux.

Maven. 

<plugin>
     <groupId>org.springframework.cloud</groupId>
@@ -1817,7 +1817,7 @@ to work with WebFlux.

Maven.  } } -}

8.10 XML Support for REST

For REST contracts, we also support XML request and response body. +}

9.10 XML Support for REST

For REST contracts, we also support XML request and response body. The XML body has to be passed within the body element as a String or GString. Also body matchers can be provided for both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath @@ -1891,8 +1891,8 @@ and the appropriate MatchingType as second. All the assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*"); assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo"); assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype"); - }

8.11 Messaging Top-Level Elements

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences:

8.11.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was + }

9.11 Messaging Top-Level Elements

The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

9.11.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was started and a message was sent), as shown in the following example:

Groovy DSL. 

def dsl = Contract.make {
 	// Human readable description
@@ -1937,7 +1937,7 @@ outputMessage:
 

In the previous example case, the output message is sent to output if a method called bookReturnedTriggered is executed. On the message publisher’s side, we generate a test that calls that method to trigger the message. On the consumer side, you can use -the some_label to trigger the message.

8.11.2 Output Triggered by a Message

The output message can be triggered by receiving a message, as shown in the following +the some_label to trigger the message.

9.11.2 Output Triggered by a Message

The output message can be triggered by receiving a message, as shown in the following example:

Groovy DSL. 

def dsl = Contract.make {
 	description 'Some Description'
@@ -1993,7 +1993,7 @@ outputMessage:
 received on the input destination. On the message publisher’s side, the engine
 generates a test that sends the input message to the defined destination. On the
 consumer side, you can either send a message to the input destination or use a label
-(some_label in the example) to trigger the message.

8.11.3 Consumer/Producer

[Important]Important

This section is valid only for Groovy DSL.

In HTTP, you have a notion of client/stub and `server/test notation. You can also +(some_label in the example) to trigger the message.

9.11.3 Consumer/Producer

[Important]Important

This section is valid only for Groovy DSL.

In HTTP, you have a notion of client/stub and `server/test notation. You can also use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also provides the consumer and producer methods, as presented in the following example (note that you can use either $ or value methods to provide consumer and producer @@ -2014,10 +2014,10 @@ parts):

					Contract.make {
 									bookName: 'foo'
 							])
 						}
-					}

8.11.4 Common

In the input or outputMessage section you can call assertThat with the name + }

9.11.4 Common

In the input or outputMessage section you can call assertThat with the name of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the base class or in a static import. Spring Cloud Contract will execute that method -in the generated test.

8.12 Multiple Contracts in One File

You can define multiple contracts in one file. Such a contract might resemble the +in the generated test.

9.12 Multiple Contracts in One File

You can define multiple contracts in one file. Such a contract might resemble the following example:

Groovy DSL. 

import org.springframework.cloud.contract.spec.Contract
 
@@ -2111,7 +2111,7 @@ index of the contract in the list.

The generated stubs is shown in the fol 1_WithList.json

As you can see, the first file got the name parameter from the contract. The second got the name of the contract file (WithList.groovy) prefixed with the index (in this case, the contract had an index of 1 in the list of contracts in the file).

[Tip]Tip

As you can see, it is much better if you name your contracts because doing so makes -your tests far more meaningful.

8.13 Generating Spring REST Docs snippets from the contracts

When you want to include the requests and responses of your API using Spring REST Docs, +your tests far more meaningful.

9.13 Generating Spring REST Docs snippets from the contracts

When you want to include the requests and responses of your API using Spring REST Docs, you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. Simply include the following dependencies if you haven’t already.

Maven. 

<dependency>
@@ -2205,4 +2205,4 @@ testCompile 'org
 						getClass().getSimpleName() + "_" + testName.getMethodName())));
 	}
 
-}
[Tip]Tip

You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

\ No newline at end of file +}
[Tip]Tip

You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

\ No newline at end of file diff --git a/2.1.x/multi/multi_gradle-add-gradle-plugin.html b/2.1.x/multi/multi_gradle-add-gradle-plugin.html new file mode 100644 index 0000000000..88c7cbdbd0 --- /dev/null +++ b/2.1.x/multi/multi_gradle-add-gradle-plugin.html @@ -0,0 +1,774 @@ + + + 5. Add Gradle Plugin with Dependencies

5. Add Gradle Plugin with Dependencies

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

Plugin DSL GA versions.  +

// build.gradle
+plugins {
+  id "groovy"
+  // this will work only for GA versions of Spring Cloud Contract
+  id "org.springframework.cloud.contract" version "${GAVerifierVersion}"
+}
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${GAVerifierVersion}"
+	}
+}
+
+dependencies {
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
+	// example with adding Spock core and Spock Spring
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

+

Plugin DSL non GA versions.  +

// settings.gradle
+pluginManagement {
+	plugins {
+		id "org.springframework.cloud.contract" version "${verifierVersion}"
+	}
+    repositories {
+        // to pick from local .m2
+        mavenLocal()
+        // for snapshots
+        maven { url "https://repo.spring.io/snapshot" }
+        // for milestones
+        maven { url "https://repo.spring.io/milestone" }
+        // for GA versions
+        gradlePluginPortal()
+    }
+}
+
+// build.gradle
+plugins {
+  id "groovy"
+  id "org.springframework.cloud.contract"
+}
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifierVersion}"
+	}
+}
+
+dependencies {
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
+	// example with adding Spock core and Spock Spring
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

+

Legacy Plugin Application.  +

// build.gradle
+buildscript {
+	repositories {
+		mavenCentral()
+	}
+	dependencies {
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+        // here you can also pass additional dependencies such as Pact or Kotlin spec e.g.:
+        // classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${verifier_version}"
+	}
+}
+
+apply plugin: 'groovy'
+apply plugin: 'spring-cloud-contract'
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
+	}
+}
+
+dependencies {
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
+	// example with adding Spock core and Spock Spring
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

+

5.1 Gradle and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here:

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

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

5.2 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

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

5.3 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +src/test/resources/contracts directory.

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

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

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

5.4 Run the Plugin

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

5.5 Default Setup

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

contracts {
+    testFramework ='JUNIT'
+    testMode = 'MockMvc'
+    generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
+    generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
+    contractsDslDir = file("${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
+        }
+    }
+}

5.6 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as +shown here:

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

5.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • imports: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array.
  • staticImports: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests.
  • baseClassMappings: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over packageWithBaseClasses and baseClassForTests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • ignoredFiles: Uses an Antmatcher to allow defining stub files for which processing +should be skipped. By default, it is an empty array.
  • contractsDslDir: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is $rootDir/src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-resources/contracts.
  • stubsOutputDir: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed.
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

The following properties are used when you want to specify the location of the JAR +containing the contracts:

  • contractDependency: Specifies the Dependency that provides +groupid:artifactid:version:classifier coordinates. You can use the contractDependency +closure to set it up.
  • contractsPath: Specifies the path to the jar. If contract dependencies are +downloaded, the path defaults to groupid/artifactid where groupid is slash +separated. Otherwise, it scans contracts under the provided directory.
  • contractsMode: Specifies the mode of downloading contracts (whether the +JAR is available offline, remotely etc.)
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

5.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

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

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

5.9 Different Base Classes for Contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • Provide explicit mapping via baseClassMappings

By Convention

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

packageWithBaseClasses = 'com.example.base'

By Mapping

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

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

Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

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

5.10 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

5.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to call the pushStubsToScm +task. Example:

$ ./gradlew pushStubsToScm

Under Section 11.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, +via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, +a system property or an environment variable.

5.12 Spring Cloud Contract Verifier on the Consumer Side

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

./gradlew generateClientStubs
[Note]Note

The stubsOutputDir option has to be set for stub generation to work.

When present, JSON stubs can be used in automated tests of consuming a service.

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

LoanApplication makes a call to FraudDetection service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

5.13 Maven Project

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

5.13.1 Add maven plugin

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

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

Next, add the Spring Cloud Contract Verifier Maven plugin:

<plugin>
+	<groupId>org.springframework.cloud</groupId>
+	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
+	<version>${spring-cloud-contract.version}</version>
+	<extensions>true</extensions>
+	<configuration>
+		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
+		<convertToYaml>true</convertToYaml>
+	</configuration>
+</plugin>

You can read more in the +Spring +Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

5.13.2 Maven and Rest Assured 2.0

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

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

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

5.13.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your +pom.xml, as shown here:

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

5.13.4 Add stubs

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

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

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

5.13.5 Run plugin

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

5.13.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin +definition or the execution definition, as shown here:

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

5.13.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to +Explicit for real HTTP calls.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, +the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. +If neither of these values are set, then the value is set to +org.springframework.cloud.contract.verifier.tests.
  • ruleClassForTests: Specifies a rule that should be added to the generated test +classes.
  • baseClassForTests: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is spock.lang.Specification.
  • contractsDirectory: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is /src/test/resources/contracts.
  • generatedTestSourcesDir: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +$buildDir/generated-test-sources/contracts.
  • generatedTestResourcesDir: Specifies the test resource directory where resources used by the tests generated
  • testFramework: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (TestFramework.JUNIT) and +JUnit 5 are supported with JUnit 4 being the default framework.
  • packageWithBaseClasses: Defines a package where all the base classes reside. This +setting takes precedence over baseClassForTests. The convention is such that, if you +have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set +the value of the packageWithBaseClasses property to com.example.base, then Spring +Cloud Contract Verifier assumes that there is a BarBazBase class under the +com.example.base package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a Base suffix.
  • baseClassMappings: Specifies a list of base class mappings that provide +contractPackageRegex, which is checked against the package where the contract is +located, and baseClassFQN, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +src/test/resources/contract/foo/bar/baz/ and map the property +.* → com.example.base.BaseClass, then the test class generated from these contracts +extends com.example.base.BaseClass. This setting takes precedence over +packageWithBaseClasses and baseClassForTests.
  • contractsProperties: a map containing properties to be passed to Spring Cloud Contract +components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.

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

  • contractDependency: The contract dependency that contains all the packaged contracts.
  • contractsPath: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to groupid/artifactid where gropuid is slash separated.
  • contractsMode: Picks the mode in which stubs will be found and registered
  • deleteStubsAfterTest: If set to false will not remove any downloaded +contracts from temporary directories
  • contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones.
  • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.
  • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.
  • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.
  • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

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

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

5.13.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified.

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

You can also setup the whole context if necessary.

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

If you use EXPLICIT mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests.

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

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

5.13.9 Different base classes for contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • provide explicit mapping via baseClassMappings

By Convention

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

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

By Mapping

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

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

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

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

5.13.10 Invoking generated tests

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

For Groovy Spock code, use the following:

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

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

5.13.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +stubs, you might want to automate the step of pushing stubs to +the repository. To do that, it’s enough to add the pushStubsToScm +goal. Example:

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

Under Section 11.6, “Using the SCM Stub Downloader” you can find all possible +configuration options that you can pass either via +the <configuration><contractProperties> map, a system property +or an environment variable.

5.13.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

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

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

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

<build>
+    <pluginManagement>
+        <plugins>
+            <!--This plugin's configuration is used to store Eclipse m2e settings
+                only. It has no influence on the Maven build itself. -->
+            <plugin>
+                <groupId>org.eclipse.m2e</groupId>
+                <artifactId>lifecycle-mapping</artifactId>
+                <version>1.0.0</version>
+                <configuration>
+                    <lifecycleMappingMetadata>
+                        <pluginExecutions>
+                             <pluginExecution>
+                                <pluginExecutionFilter>
+                                    <groupId>org.springframework.cloud</groupId>
+                                    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
+                                    <versionRange>[1.0,)</versionRange>
+                                    <goals>
+                                        <goal>convert</goal>
+                                    </goals>
+                                </pluginExecutionFilter>
+                                <action>
+                                    <execute />
+                                </action>
+                             </pluginExecution>
+                        </pluginExecutions>
+                    </lifecycleMappingMetadata>
+                </configuration>
+            </plugin>
+        </plugins>
+    </pluginManagement>
+</build>

5.13.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract +verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, +in Maven you will require some additional setup in order to make the tests compile and execute properly.

First of all, you will have to use a plugin, such as GMavenPlus plugin, +to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the +path where your base test classes are defined and the path were the generated contract tests are added. +Please refer to the example below:

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven +Surefire plugin setup, like in the following example:

5.14 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub’s dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom:

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

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

  • Mark all application dependencies as optional
  • Create a separate artifactid for the stubs
  • Exclude dependencies on the consumer side

Mark all application dependencies as optional

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

Create a separate artifactid for the stubs

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

Exclude dependencies on the consumer side

As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies.

5.15 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore. This will work regardles + of whether you’re working with YAML or Groovy. Example:

my_contracts_dir\
+  scenario1\
+    1_login.groovy
+    2_showCart.groovy
+    3_logout.groovy

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a +name of scenario1 and the three following steps:

  1. login marked as Started pointing to…​
  2. showCart marked as Step1 pointing to…​
  3. logout marked as Step2 which will close the scenario.

More details about WireMock scenarios can be found at +https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

5.16 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image +that contains a project that will generate tests and execute them in EXPLICIT mode +against a running application.

[Tip]Tip

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

5.16.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to +explain the basic terms behind Spring Cloud Contract packaging defaults.

Part of the following definitions were taken from the Maven Glossary

  • Project: Maven thinks in terms of projects. Everything that you +will build are projects. Those projects follow a well defined +“Project Object Model”. Projects can depend on other projects, +in which case the latter are called “dependencies”. A project may +consistent of several subprojects, however these subprojects are still +treated equally as projects.
  • Artifact: An artifact is something that is either produced or used +by a project. Examples of artifacts produced by Maven for a project +include: JARs, source and binary distributions. Each artifact +is uniquely identified by a group id and an artifact ID which is +unique within a group.
  • JAR: JAR stands for Java ARchive. It’s a format based on +the ZIP file format. Spring Cloud Contract packages the contracts and generated +stubs in a JAR file.
  • GroupId: A group ID is a universally unique identifier for a project. +While this is often just the project name (eg. commons-collections), +it is helpful to use a fully-qualified package name to distinguish it +from other projects with a similar name (eg. org.apache.maven). +Typically, when published to the Artifact Manager, the GroupId will get +slash separated and form part of the URL. E.g. for group id com.example +and artifact id application would be /com/example/application/.
  • Classifier: The Maven dependency notation looks as follows: +groupId:artifactId:version:classifier. The classifier is additional suffix +passed to the dependency. E.g. stubs, sources. The same dependency +e.g. com.example:application can produce multiple artifacts that +differ from each other with the classifier.
  • Artifact manager: When you generate binaries / sources / packages, you would +like them to be available for others to download / reference or reuse. In case +of the JVM world those artifacts would be JARs, for Ruby these are gems +and for Docker those would be Docker images. You can store those artifacts +in a manager. Examples of such managers can be Artifactory +or Nexus.

5.16.2 How it works

The image searches for contracts under the /contracts folder. +The output from running the tests will be available under +/spring-cloud-contract/build folder (it’s useful for debugging +purposes).

It’s enough for you to mount your contracts, pass the environment variables + and the image will:

  • generate the contract tests
  • execute the tests against the provided URL
  • generate the WireMock stubs
  • (optional - turned on by default) publish the stubs to a Artifact Manager

Environment Variables

The Docker image requires some environment variables to point to +your running application, to the Artifact manager instance etc.

  • PROJECT_GROUP - your project’s group id. Defaults to com.example
  • PROJECT_VERSION - your project’s version. Defaults to 0.0.1-SNAPSHOT
  • PROJECT_NAME - artifact id. Defaults to example
  • REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • REPO_WITH_BINARIES_USERNAME - (optional) username when the Artifact Manager is secured
  • REPO_WITH_BINARIES_PASSWORD - (optional) password when the Artifact Manager is secured
  • PUBLISH_ARTIFACTS - if set to true then will publish artifact to binary storage. Defaults to true.

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

  • EXTERNAL_CONTRACTS_GROUP_ID - group id of the project with contracts. Defaults to com.example
  • EXTERNAL_CONTRACTS_ARTIFACT_ID- artifact id of the project with contracts.
  • EXTERNAL_CONTRACTS_CLASSIFIER- classifier of the project with contracts. Empty by default
  • EXTERNAL_CONTRACTS_VERSION - version of the project with contracts. Defaults to +, equivalent to picking the latest
  • EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL - URL of your Artifact Manager. Defaults to value of REPO_WITH_BINARIES_URL env var. +If that’s not set, defaults to http://localhost:8081/artifactory/libs-release-local +which is the default URL of Artifactory running locally
  • EXTERNAL_CONTRACTS_PATH - path to contracts for the given project, inside the project with contracts. +Defaults to slash separated EXTERNAL_CONTRACTS_GROUP_ID concatenated with / and EXTERNAL_CONTRACTS_ARTIFACT_ID. E.g. +for group id foo.bar and artifact id baz, would result in foo/bar/baz contracts path.
  • EXTERNAL_CONTRACTS_WORK_OFFLINE - if set to true then will retrieve artifact with contracts +from the container’s .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. +You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

These environment variables are used when tests are executed:

  • APPLICATION_BASE_URL - url against which tests should be executed. +Remember that it has to be accessible from the Docker container (e.g. localhost +will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application

5.16.3 Example of usage

Let’s take a look at a simple MVC application

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

The contracts are available under /contracts folder.

5.16.4 Server side (nodejs)

Since we want to run tests, we could just execute:

$ npm test

however, for learning purposes, let’s split it into pieces:

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

What will happen is that via bash scripts:

  • infrastructure will be set up (MongoDb, Artifactory). +In real life scenario you would just run the NodeJS application +with mocked database. In this example we want to show how we can +benefit from Spring Cloud Contract in no time.
  • due to those constraints the contracts also represent the +stateful situation

    • first request is a POST that causes data to get inserted to the database
    • second request is a GET that returns a list of data with 1 previously inserted element
  • the NodeJS application will be started (on port 3000)
  • contract tests will be generated via Docker and tests +will be executed against the running application

    • the contracts will be taken from /contracts folder.
    • the output of the test execution is available under +node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out +under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

To see how the client side looks like check out the Section 7.9, “Stub Runner Docker” section.

\ No newline at end of file diff --git a/2.1.x/multi/multi_spring-cloud-contract.html b/2.1.x/multi/multi_spring-cloud-contract.html index e046ea4743..0ee0cdedce 100644 --- a/2.1.x/multi/multi_spring-cloud-contract.html +++ b/2.1.x/multi/multi_spring-cloud-contract.html @@ -1,3 +1,3 @@ - Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
4.1.2. Add Gradle Plugin with Dependencies
4.1.3. Gradle and Rest Assured 2.0
4.1.4. Snapshot Versions for Gradle
4.1.5. Add stubs
4.1.6. Run the Plugin
4.1.7. Default Setup
4.1.8. Configure Plugin
4.1.9. Configuration Options
4.1.10. Single Base Class for All Tests
4.1.11. Different Base Classes for Contracts
4.1.12. Invoking Generated Tests
4.1.13. Pushing stubs to SCM
4.1.14. Spring Cloud Contract Verifier on the Consumer Side
4.2. Maven Project
4.2.1. Add maven plugin
4.2.2. Maven and Rest Assured 2.0
4.2.3. Snapshot versions for Maven
4.2.4. Add stubs
4.2.5. Run plugin
4.2.6. Configure plugin
4.2.7. Configuration Options
4.2.8. Single Base Class for All Tests
4.2.9. Different base classes for contracts
4.2.10. Invoking generated tests
4.2.11. Pushing stubs to SCM
4.2.12. Maven Plugin and STS
4.2.13. Maven Plugin with Spock Tests
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
4.5. Docker Project
4.5.1. Short intro to Maven, JARs and Binary storage
4.5.2. How it works
Environment Variables
4.5.3. Example of usage
4.5.4. Server side (nodejs)
5. Spring Cloud Contract Verifier Messaging
5.1. Integrations
5.2. Manual Integration Testing
5.3. Publisher-Side Test Generation
5.3.1. Scenario 1: No Input Message
5.3.2. Scenario 2: Output Triggered by Input
5.3.3. Scenario 3: No Output Message
5.4. Consumer Stub Generation
6. Spring Cloud Contract Stub Runner
6.1. Snapshot versions
6.2. Publishing Stubs as JARs
6.3. Stub Runner Core
6.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
6.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
6.4.1. Maven settings
6.4.2. Providing fixed ports
6.4.3. Fluent API
6.4.4. Stub Runner with Spring
6.5. Stub Runner Spring Cloud
6.5.1. Stubbing Service Discovery
Test profiles and service discovery
6.5.2. Additional Configuration
6.6. Stub Runner Boot Application
6.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
6.6.2. Endpoints
HTTP
Messaging
6.6.3. Example
6.6.4. Stub Runner Boot with Service Discovery
6.7. Stubs Per Consumer
6.8. Common
6.8.1. Common Properties for JUnit and Spring
6.8.2. Stub Runner Stubs IDs
6.9. Stub Runner Docker
6.9.1. How to use it
6.9.2. Example of client side usage in a non JVM project
7. Stub Runner for Messaging
7.1. Stub triggering
7.1.1. Trigger by Label
7.1.2. Trigger by Group and Artifact Ids
7.1.3. Trigger by Artifact Ids
7.1.4. Trigger All Messages
7.2. Stub Runner Camel
7.2.1. Adding it to the project
7.2.2. Disabling the functionality
7.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.3. Stub Runner Integration
7.3.1. Adding the Runner to the Project
7.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.4. Stub Runner Stream
7.4.1. Adding the Runner to the Project
7.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.5. Stub Runner Spring AMQP
7.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
8. Contract DSL
8.1. Limitations
8.2. Common Top-Level elements
8.2.1. Description
8.2.2. Name
8.2.3. Ignoring Contracts
8.2.4. Passing Values from Files
8.2.5. HTTP Top-Level Elements
8.3. Request
8.4. Response
8.5. Dynamic properties
8.5.1. Dynamic properties inside the body
8.5.2. Regular expressions
8.5.3. Passing Optional Parameters
8.5.4. Executing Custom Methods on the Server Side
8.5.5. Referencing the Request from the Response
8.5.6. Registering Your Own WireMock Extension
8.5.7. Dynamic Properties in the Matchers Sections
8.6. JAX-RS Support
8.7. Async Support
8.8. Working with Context Paths
8.9. Working with WebFlux
8.9.1. WebFlux with WebTestClient
8.9.2. WebFlux with Explicit mode
8.10. XML Support for REST
8.11. Messaging Top-Level Elements
8.11.1. Output Triggered by a Method
8.11.2. Output Triggered by a Message
8.11.3. Consumer/Producer
8.11.4. Common
8.12. Multiple Contracts in One File
8.13. Generating Spring REST Docs snippets from the contracts
9. Customization
9.1. Extending the DSL
9.1.1. Common JAR
9.1.2. Adding the Dependency to the Project
9.1.3. Test the Dependency in the Project’s Dependencies
9.1.4. Test a Dependency in the Plugin’s Dependencies
9.1.5. Referencing classes in DSLs
10. Using the Pluggable Architecture
10.1. Custom Contract Converter
10.1.1. Pact Converter
10.1.2. Pact Contract
10.1.3. Pact for Producers
10.1.4. Pact for Consumers
10.2. Using the Custom Test Generator
10.3. Using the Custom Stub Generator
10.4. Using the Custom Stub Runner
10.5. Using the Custom Stub Downloader
10.6. Using the SCM Stub Downloader
10.7. Using the Pact Stub Downloader
11. Spring Cloud Contract WireMock
11.1. Registering Stubs Automatically
11.2. Using Files to Specify the Stub Bodies
11.3. Alternative: Using JUnit Rules
11.4. Relaxed SSL Validation for Rest Template
11.5. WireMock and Spring MVC Mocks
11.6. Customization of WireMock configuration
11.7. Generating Stubs using REST Docs
11.8. Generating Contracts by Using REST Docs
12. Migrations
12.1. 1.0.x → 1.1.x
12.1.1. New structure of generated stubs
12.2. 1.1.x → 1.2.x
12.2.1. Custom HttpServerStub
12.2.2. New packages for generated tests
12.2.3. New Methods in TemplateProcessor
12.2.4. RestAssured 3.0
12.3. 1.2.x → 2.0.x
13. Links
\ No newline at end of file + Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
5. Add Gradle Plugin with Dependencies
5.1. Gradle and Rest Assured 2.0
5.2. Snapshot Versions for Gradle
5.3. Add stubs
5.4. Run the Plugin
5.5. Default Setup
5.6. Configure Plugin
5.7. Configuration Options
5.8. Single Base Class for All Tests
5.9. Different Base Classes for Contracts
5.10. Invoking Generated Tests
5.11. Pushing stubs to SCM
5.12. Spring Cloud Contract Verifier on the Consumer Side
5.13. Maven Project
5.13.1. Add maven plugin
5.13.2. Maven and Rest Assured 2.0
5.13.3. Snapshot versions for Maven
5.13.4. Add stubs
5.13.5. Run plugin
5.13.6. Configure plugin
5.13.7. Configuration Options
5.13.8. Single Base Class for All Tests
5.13.9. Different base classes for contracts
5.13.10. Invoking generated tests
5.13.11. Pushing stubs to SCM
5.13.12. Maven Plugin and STS
5.13.13. Maven Plugin with Spock Tests
5.14. Stubs and Transitive Dependencies
5.15. Scenarios
5.16. Docker Project
5.16.1. Short intro to Maven, JARs and Binary storage
5.16.2. How it works
Environment Variables
5.16.3. Example of usage
5.16.4. Server side (nodejs)
6. Spring Cloud Contract Verifier Messaging
6.1. Integrations
6.2. Manual Integration Testing
6.3. Publisher-Side Test Generation
6.3.1. Scenario 1: No Input Message
6.3.2. Scenario 2: Output Triggered by Input
6.3.3. Scenario 3: No Output Message
6.4. Consumer Stub Generation
7. Spring Cloud Contract Stub Runner
7.1. Snapshot versions
7.2. Publishing Stubs as JARs
7.3. Stub Runner Core
7.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
7.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
7.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
7.4.1. Maven settings
7.4.2. Providing fixed ports
7.4.3. Fluent API
7.4.4. Stub Runner with Spring
7.5. Stub Runner Spring Cloud
7.5.1. Stubbing Service Discovery
Test profiles and service discovery
7.5.2. Additional Configuration
7.6. Stub Runner Boot Application
7.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
7.6.2. Endpoints
HTTP
Messaging
7.6.3. Example
7.6.4. Stub Runner Boot with Service Discovery
7.7. Stubs Per Consumer
7.8. Common
7.8.1. Common Properties for JUnit and Spring
7.8.2. Stub Runner Stubs IDs
7.9. Stub Runner Docker
7.9.1. How to use it
7.9.2. Example of client side usage in a non JVM project
8. Stub Runner for Messaging
8.1. Stub triggering
8.1.1. Trigger by Label
8.1.2. Trigger by Group and Artifact Ids
8.1.3. Trigger by Artifact Ids
8.1.4. Trigger All Messages
8.2. Stub Runner Camel
8.2.1. Adding it to the project
8.2.2. Disabling the functionality
8.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.3. Stub Runner Integration
8.3.1. Adding the Runner to the Project
8.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.4. Stub Runner Stream
8.4.1. Adding the Runner to the Project
8.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.5. Stub Runner Spring AMQP
8.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
9. Contract DSL
9.1. Limitations
9.2. Common Top-Level elements
9.2.1. Description
9.2.2. Name
9.2.3. Ignoring Contracts
9.2.4. Passing Values from Files
9.2.5. HTTP Top-Level Elements
9.3. Request
9.4. Response
9.5. Dynamic properties
9.5.1. Dynamic properties inside the body
9.5.2. Regular expressions
9.5.3. Passing Optional Parameters
9.5.4. Executing Custom Methods on the Server Side
9.5.5. Referencing the Request from the Response
9.5.6. Registering Your Own WireMock Extension
9.5.7. Dynamic Properties in the Matchers Sections
9.6. JAX-RS Support
9.7. Async Support
9.8. Working with Context Paths
9.9. Working with WebFlux
9.9.1. WebFlux with WebTestClient
9.9.2. WebFlux with Explicit mode
9.10. XML Support for REST
9.11. Messaging Top-Level Elements
9.11.1. Output Triggered by a Method
9.11.2. Output Triggered by a Message
9.11.3. Consumer/Producer
9.11.4. Common
9.12. Multiple Contracts in One File
9.13. Generating Spring REST Docs snippets from the contracts
10. Customization
10.1. Extending the DSL
10.1.1. Common JAR
10.1.2. Adding the Dependency to the Project
10.1.3. Test the Dependency in the Project’s Dependencies
10.1.4. Test a Dependency in the Plugin’s Dependencies
10.1.5. Referencing classes in DSLs
11. Using the Pluggable Architecture
11.1. Custom Contract Converter
11.1.1. Pact Converter
11.1.2. Pact Contract
11.1.3. Pact for Producers
11.1.4. Pact for Consumers
11.2. Using the Custom Test Generator
11.3. Using the Custom Stub Generator
11.4. Using the Custom Stub Runner
11.5. Using the Custom Stub Downloader
11.6. Using the SCM Stub Downloader
11.7. Using the Pact Stub Downloader
12. Spring Cloud Contract WireMock
12.1. Registering Stubs Automatically
12.2. Using Files to Specify the Stub Bodies
12.3. Alternative: Using JUnit Rules
12.4. Relaxed SSL Validation for Rest Template
12.5. WireMock and Spring MVC Mocks
12.6. Customization of WireMock configuration
12.7. Generating Stubs using REST Docs
12.8. Generating Contracts by Using REST Docs
13. Migrations
13.1. 1.0.x → 1.1.x
13.1.1. New structure of generated stubs
13.2. 1.1.x → 1.2.x
13.2.1. Custom HttpServerStub
13.2.2. New packages for generated tests
13.2.3. New Methods in TemplateProcessor
13.2.4. RestAssured 3.0
13.3. 1.2.x → 2.0.x
14. Links
\ No newline at end of file diff --git a/2.1.x/multi/multi_stub-runner-for-messaging.html b/2.1.x/multi/multi_stub-runner-for-messaging.html index 4ef2ba5f61..6a23025120 100644 --- a/2.1.x/multi/multi_stub-runner-for-messaging.html +++ b/2.1.x/multi/multi_stub-runner-for-messaging.html @@ -1,10 +1,10 @@ - 7. Stub Runner for Messaging

7. Stub Runner for Messaging

Stub Runner can run the published stubs in memory. It can integrate with the following + 8. Stub Runner for Messaging

8. 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]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.

7.1 Stub triggering

To trigger a message, use the StubTrigger interface:

package org.springframework.cloud.contract.stubrunner;
+That way the only remaining framework is Spring AMQP.

8.1 Stub triggering

To trigger a message, use the StubTrigger interface:

package org.springframework.cloud.contract.stubrunner;
 
 import java.util.Collection;
 import java.util.Map;
@@ -51,10 +51,10 @@ That way the only remaining framework is Spring AMQP.

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:

7.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

7.1.2 Trigger by Group and Artifact Ids

stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

7.1.3 Trigger by Artifact Ids

stubFinder.trigger('streamService', 'return_book_1')

7.1.4 Trigger All Messages

stubFinder.trigger()

7.2 Stub Runner Camel

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +or the other in your tests.

StubTrigger gives you the following options to trigger a message:

8.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

8.1.2 Trigger by Group and Artifact Ids

stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

8.1.3 Trigger by Artifact Ids

stubFinder.trigger('streamService', 'return_book_1')

8.1.4 Trigger All Messages

stubFinder.trigger()

8.2 Stub Runner Camel

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. For the provided artifacts it will automatically download the stubs and register the required -routes.

7.2.1 Adding it to the project

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with @AutoConfigureStubRunner.

7.2.2 Disabling the functionality

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

7.2.3 Examples

Stubs structure

Let us assume that we have the following Maven repository with a deployed stubs for the +routes.

8.2.1 Adding it to the project

It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

8.2.2 Disabling the functionality

If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

8.2.3 Examples

Stubs structure

Let us assume that we have the following Maven repository with a deployed stubs for the camelService application.

└── .m2
     └── repository
         └── io
@@ -111,10 +111,10 @@ receivedMessage.in.headers.get('jms:input', new BookReturned('foo'), [sample: 'header'])

Next we’ll want to listen to the output of the message sent to jms:output

Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

And the received message would pass the following assertions

receivedMessage != null
 assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
 receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you it’s enough to just send a message to the jms:output destination.

producerTemplate.
-		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

7.3 Stub Runner Integration

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to + sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

8.3 Stub Runner Integration

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Integration. For the provided artifacts, it automatically downloads -the stubs and registers the required routes.

7.3.1 Adding the Runner to the Project

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.3.2 Disabling the functionality

If you need to disable this functionality, set the +the stubs and registers the required routes.

8.3.1 Adding the Runner to the Project

You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

8.3.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.integration.enabled=false property.

Assume that you have the following Maven repository with deployed stubs for the integrationService application:

└── .m2
     └── repository
@@ -190,7 +190,7 @@ assertJsons(receivedMessage.payload)
 receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 2 (output triggered by input)

Since the route is set for you, you can send a message to the output destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')

To listen to the output of the message sent to output:

Message<?> receivedMessage = messaging.receive('outputTest')

The received message passes the following assertions:

receivedMessage != null
 assertJsons(receivedMessage.payload)
-receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the input destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.4 Stub Runner Stream

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the input destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

8.4 Stub Runner Stream

Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Stream. For the provided artifacts, it automatically downloads the stubs and registers the required routes.

[Warning]Warning

If Stub Runner’s integration with Stream the messageFrom or sentTo Strings are resolved first as a destination of a channel and no such destination exists, the @@ -203,8 +203,8 @@ destination is resolved as a channel name.

</dependency>

Gradle. 

testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

-

7.4.1 Adding the Runner to the Project

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

7.4.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.stream.enabled=false +

8.4.1 Adding the Runner to the Project

You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

8.4.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.stream.enabled=false property.

Assume that you have the following Maven repository with a deployed stubs for the streamService application:

└── .m2
     └── repository
@@ -271,7 +271,7 @@ receivedMessage.headers.get(destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')

To listen to the output of the message sent to returnBook:

Message<?> receivedMessage = messaging.receive('returnBook')

The received message passes the following assertions:

receivedMessage != null
 assertJsons(receivedMessage.payload)
 receivedMessage.headers.get('BOOK-NAME') == 'foo'

Scenario 3 (input with no output)

Since the route is set for you, you can send a message to the output -destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

7.5 Stub Runner Spring AMQP

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +destination:

messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

8.5 Stub Runner Spring AMQP

Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it automatically downloads the stubs and registers the required routes.

The integration tries to work standalone (that is, without interaction with a running RabbitMQ message broker). It expects a RabbitTemplate on the application context and @@ -284,7 +284,7 @@ Spring AMQP stub runner integration looks for bindings on the application contex match this exchange. Then it collects the queues from the Spring exchanges and tries to find message listeners bound to these queues. The message is triggered for all matching message listeners.

If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey -messaging header.

7.5.1 Adding the Runner to the Project

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +messaging header.

8.5.1 Adding the Runner to the Project

You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and set the property stubrunner.amqp.enabled=true. Remember to annotate your test class with @AutoConfigureStubRunner.

[Important]Important

If you already have Stream and Integration on the classpath, you need to disable them explicitly by setting the stubrunner.stream.enabled=false and @@ -357,4 +357,4 @@ definition is matched and invoked with the contract message.

ConnectionFactory.

To disable the mocked ConnectionFactory, set the following property: stubrunner.amqp.mockConnection=false

stubrunner:
   amqp:
-    mockConnection: false
\ No newline at end of file + mockConnection: false
\ No newline at end of file diff --git a/2.1.x/single/spring-cloud-contract.html b/2.1.x/single/spring-cloud-contract.html index 794d38250f..6a0dd62a75 100644 --- a/2.1.x/single/spring-cloud-contract.html +++ b/2.1.x/single/spring-cloud-contract.html @@ -1,6 +1,6 @@ - Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
4.1.2. Add Gradle Plugin with Dependencies
4.1.3. Gradle and Rest Assured 2.0
4.1.4. Snapshot Versions for Gradle
4.1.5. Add stubs
4.1.6. Run the Plugin
4.1.7. Default Setup
4.1.8. Configure Plugin
4.1.9. Configuration Options
4.1.10. Single Base Class for All Tests
4.1.11. Different Base Classes for Contracts
4.1.12. Invoking Generated Tests
4.1.13. Pushing stubs to SCM
4.1.14. Spring Cloud Contract Verifier on the Consumer Side
4.2. Maven Project
4.2.1. Add maven plugin
4.2.2. Maven and Rest Assured 2.0
4.2.3. Snapshot versions for Maven
4.2.4. Add stubs
4.2.5. Run plugin
4.2.6. Configure plugin
4.2.7. Configuration Options
4.2.8. Single Base Class for All Tests
4.2.9. Different base classes for contracts
4.2.10. Invoking generated tests
4.2.11. Pushing stubs to SCM
4.2.12. Maven Plugin and STS
4.2.13. Maven Plugin with Spock Tests
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
4.5. Docker Project
4.5.1. Short intro to Maven, JARs and Binary storage
4.5.2. How it works
Environment Variables
4.5.3. Example of usage
4.5.4. Server side (nodejs)
5. Spring Cloud Contract Verifier Messaging
5.1. Integrations
5.2. Manual Integration Testing
5.3. Publisher-Side Test Generation
5.3.1. Scenario 1: No Input Message
5.3.2. Scenario 2: Output Triggered by Input
5.3.3. Scenario 3: No Output Message
5.4. Consumer Stub Generation
6. Spring Cloud Contract Stub Runner
6.1. Snapshot versions
6.2. Publishing Stubs as JARs
6.3. Stub Runner Core
6.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
6.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
6.4.1. Maven settings
6.4.2. Providing fixed ports
6.4.3. Fluent API
6.4.4. Stub Runner with Spring
6.5. Stub Runner Spring Cloud
6.5.1. Stubbing Service Discovery
Test profiles and service discovery
6.5.2. Additional Configuration
6.6. Stub Runner Boot Application
6.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
6.6.2. Endpoints
HTTP
Messaging
6.6.3. Example
6.6.4. Stub Runner Boot with Service Discovery
6.7. Stubs Per Consumer
6.8. Common
6.8.1. Common Properties for JUnit and Spring
6.8.2. Stub Runner Stubs IDs
6.9. Stub Runner Docker
6.9.1. How to use it
6.9.2. Example of client side usage in a non JVM project
7. Stub Runner for Messaging
7.1. Stub triggering
7.1.1. Trigger by Label
7.1.2. Trigger by Group and Artifact Ids
7.1.3. Trigger by Artifact Ids
7.1.4. Trigger All Messages
7.2. Stub Runner Camel
7.2.1. Adding it to the project
7.2.2. Disabling the functionality
7.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.3. Stub Runner Integration
7.3.1. Adding the Runner to the Project
7.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.4. Stub Runner Stream
7.4.1. Adding the Runner to the Project
7.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
7.5. Stub Runner Spring AMQP
7.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
8. Contract DSL
8.1. Limitations
8.2. Common Top-Level elements
8.2.1. Description
8.2.2. Name
8.2.3. Ignoring Contracts
8.2.4. Passing Values from Files
8.2.5. HTTP Top-Level Elements
8.3. Request
8.4. Response
8.5. Dynamic properties
8.5.1. Dynamic properties inside the body
8.5.2. Regular expressions
8.5.3. Passing Optional Parameters
8.5.4. Executing Custom Methods on the Server Side
8.5.5. Referencing the Request from the Response
8.5.6. Registering Your Own WireMock Extension
8.5.7. Dynamic Properties in the Matchers Sections
8.6. JAX-RS Support
8.7. Async Support
8.8. Working with Context Paths
8.9. Working with WebFlux
8.9.1. WebFlux with WebTestClient
8.9.2. WebFlux with Explicit mode
8.10. XML Support for REST
8.11. Messaging Top-Level Elements
8.11.1. Output Triggered by a Method
8.11.2. Output Triggered by a Message
8.11.3. Consumer/Producer
8.11.4. Common
8.12. Multiple Contracts in One File
8.13. Generating Spring REST Docs snippets from the contracts
9. Customization
9.1. Extending the DSL
9.1.1. Common JAR
9.1.2. Adding the Dependency to the Project
9.1.3. Test the Dependency in the Project’s Dependencies
9.1.4. Test a Dependency in the Plugin’s Dependencies
9.1.5. Referencing classes in DSLs
10. Using the Pluggable Architecture
10.1. Custom Contract Converter
10.1.1. Pact Converter
10.1.2. Pact Contract
10.1.3. Pact for Producers
10.1.4. Pact for Consumers
10.2. Using the Custom Test Generator
10.3. Using the Custom Stub Generator
10.4. Using the Custom Stub Runner
10.5. Using the Custom Stub Downloader
10.6. Using the SCM Stub Downloader
10.7. Using the Pact Stub Downloader
11. Spring Cloud Contract WireMock
11.1. Registering Stubs Automatically
11.2. Using Files to Specify the Stub Bodies
11.3. Alternative: Using JUnit Rules
11.4. Relaxed SSL Validation for Rest Template
11.5. WireMock and Spring MVC Mocks
11.6. Customization of WireMock configuration
11.7. Generating Stubs using REST Docs
11.8. Generating Contracts by Using REST Docs
12. Migrations
12.1. 1.0.x → 1.1.x
12.1.1. New structure of generated stubs
12.2. 1.1.x → 1.2.x
12.2.1. Custom HttpServerStub
12.2.2. New packages for generated tests
12.2.3. New Methods in TemplateProcessor
12.2.4. RestAssured 3.0
12.3. 1.2.x → 2.0.x
13. Links

Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, + Spring Cloud Contract

Spring Cloud Contract


Table of Contents

1. Spring Cloud Contract
2. Spring Cloud Contract Verifier Introduction
2.1. History
2.2. Why a Contract Verifier?
2.2.1. Testing issues
2.3. Purposes
2.4. How It Works
2.4.1. A Three-second Tour
On the Producer Side
On the Consumer Side
2.4.2. A Three-minute Tour
On the Producer Side
On the Consumer Side
2.4.3. Defining the Contract
2.4.4. Client Side
2.4.5. Server Side
2.5. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.5.1. Technical note
2.5.2. Consumer side (Loan Issuance)
2.5.3. Producer side (Fraud Detection server)
2.5.4. Consumer Side (Loan Issuance) Final Step
2.6. Dependencies
2.7. Additional Links
2.7.1. Spring Cloud Contract video
2.7.2. Readings
2.8. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. I don’t want to write a contract in Groovy!
3.3. What is this value(consumer(), producer()) ?
3.4. How to do Stubs versioning?
3.4.1. API Versioning
3.4.2. JAR versioning
3.4.3. Dev or prod stubs
3.5. Common repo with contracts
3.5.1. Repo structure
3.5.2. Workflow
3.5.3. Consumer
3.5.4. Producer
3.5.5. How can I define messaging contracts per topic not per producer?
For Maven Project
For Gradle Project
3.6. Do I need a Binary Storage? Can’t I use Git?
3.6.1. Protocol convention
3.6.2. Producer
3.6.3. Producer with contracts stored locally
Keeping contracts with the producer and stubs in an external repository
3.6.4. Consumer
3.7. Can I use the Pact Broker?
3.7.1. Pact Consumer
3.7.2. Producer
3.7.3. Pact Consumer (Producer Contract approach)
3.8. How can I debug the request/response being sent by the generated tests client?
3.8.1. How can I debug the mapping/request/response being sent by WireMock?
3.8.2. How can I see what got registered in the HTTP server stub?
3.8.3. Can I reference text from file?
4. Spring Cloud Contract Verifier Setup
4.1. Gradle Project
4.1.1. Prerequisites
5. Add Gradle Plugin with Dependencies
5.1. Gradle and Rest Assured 2.0
5.2. Snapshot Versions for Gradle
5.3. Add stubs
5.4. Run the Plugin
5.5. Default Setup
5.6. Configure Plugin
5.7. Configuration Options
5.8. Single Base Class for All Tests
5.9. Different Base Classes for Contracts
5.10. Invoking Generated Tests
5.11. Pushing stubs to SCM
5.12. Spring Cloud Contract Verifier on the Consumer Side
5.13. Maven Project
5.13.1. Add maven plugin
5.13.2. Maven and Rest Assured 2.0
5.13.3. Snapshot versions for Maven
5.13.4. Add stubs
5.13.5. Run plugin
5.13.6. Configure plugin
5.13.7. Configuration Options
5.13.8. Single Base Class for All Tests
5.13.9. Different base classes for contracts
5.13.10. Invoking generated tests
5.13.11. Pushing stubs to SCM
5.13.12. Maven Plugin and STS
5.13.13. Maven Plugin with Spock Tests
5.14. Stubs and Transitive Dependencies
5.15. Scenarios
5.16. Docker Project
5.16.1. Short intro to Maven, JARs and Binary storage
5.16.2. How it works
Environment Variables
5.16.3. Example of usage
5.16.4. Server side (nodejs)
6. Spring Cloud Contract Verifier Messaging
6.1. Integrations
6.2. Manual Integration Testing
6.3. Publisher-Side Test Generation
6.3.1. Scenario 1: No Input Message
6.3.2. Scenario 2: Output Triggered by Input
6.3.3. Scenario 3: No Output Message
6.4. Consumer Stub Generation
7. Spring Cloud Contract Stub Runner
7.1. Snapshot versions
7.2. Publishing Stubs as JARs
7.3. Stub Runner Core
7.3.1. Retrieving stubs
Stub downloading
Classpath scanning
Configuring HTTP Server Stubs
7.3.2. Running stubs
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
7.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension
7.4.1. Maven settings
7.4.2. Providing fixed ports
7.4.3. Fluent API
7.4.4. Stub Runner with Spring
7.5. Stub Runner Spring Cloud
7.5.1. Stubbing Service Discovery
Test profiles and service discovery
7.5.2. Additional Configuration
7.6. Stub Runner Boot Application
7.6.1. How to use it?
Stub Runner Server
Stub Runner Server Fat Jar
Spring Cloud CLI
7.6.2. Endpoints
HTTP
Messaging
7.6.3. Example
7.6.4. Stub Runner Boot with Service Discovery
7.7. Stubs Per Consumer
7.8. Common
7.8.1. Common Properties for JUnit and Spring
7.8.2. Stub Runner Stubs IDs
7.9. Stub Runner Docker
7.9.1. How to use it
7.9.2. Example of client side usage in a non JVM project
8. Stub Runner for Messaging
8.1. Stub triggering
8.1.1. Trigger by Label
8.1.2. Trigger by Group and Artifact Ids
8.1.3. Trigger by Artifact Ids
8.1.4. Trigger All Messages
8.2. Stub Runner Camel
8.2.1. Adding it to the project
8.2.2. Disabling the functionality
8.2.3. Examples
Stubs structure
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.3. Stub Runner Integration
8.3.1. Adding the Runner to the Project
8.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.4. Stub Runner Stream
8.4.1. Adding the Runner to the Project
8.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
8.5. Stub Runner Spring AMQP
8.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
9. Contract DSL
9.1. Limitations
9.2. Common Top-Level elements
9.2.1. Description
9.2.2. Name
9.2.3. Ignoring Contracts
9.2.4. Passing Values from Files
9.2.5. HTTP Top-Level Elements
9.3. Request
9.4. Response
9.5. Dynamic properties
9.5.1. Dynamic properties inside the body
9.5.2. Regular expressions
9.5.3. Passing Optional Parameters
9.5.4. Executing Custom Methods on the Server Side
9.5.5. Referencing the Request from the Response
9.5.6. Registering Your Own WireMock Extension
9.5.7. Dynamic Properties in the Matchers Sections
9.6. JAX-RS Support
9.7. Async Support
9.8. Working with Context Paths
9.9. Working with WebFlux
9.9.1. WebFlux with WebTestClient
9.9.2. WebFlux with Explicit mode
9.10. XML Support for REST
9.11. Messaging Top-Level Elements
9.11.1. Output Triggered by a Method
9.11.2. Output Triggered by a Message
9.11.3. Consumer/Producer
9.11.4. Common
9.12. Multiple Contracts in One File
9.13. Generating Spring REST Docs snippets from the contracts
10. Customization
10.1. Extending the DSL
10.1.1. Common JAR
10.1.2. Adding the Dependency to the Project
10.1.3. Test the Dependency in the Project’s Dependencies
10.1.4. Test a Dependency in the Plugin’s Dependencies
10.1.5. Referencing classes in DSLs
11. Using the Pluggable Architecture
11.1. Custom Contract Converter
11.1.1. Pact Converter
11.1.2. Pact Contract
11.1.3. Pact for Producers
11.1.4. Pact for Consumers
11.2. Using the Custom Test Generator
11.3. Using the Custom Stub Generator
11.4. Using the Custom Stub Runner
11.5. Using the Custom Stub Downloader
11.6. Using the SCM Stub Downloader
11.7. Using the Pact Stub Downloader
12. Spring Cloud Contract WireMock
12.1. Registering Stubs Automatically
12.2. Using Files to Specify the Stub Bodies
12.3. Alternative: Using JUnit Rules
12.4. Relaxed SSL Validation for Rest Template
12.5. WireMock and Spring MVC Mocks
12.6. Customization of WireMock configuration
12.7. Generating Stubs using REST Docs
12.8. Generating Contracts by Using REST Docs
13. Migrations
13.1. 1.0.x → 1.1.x
13.1.1. New structure of generated stubs
13.2. 1.1.x → 1.2.x
13.2.1. Custom HttpServerStub
13.2.2. New packages for generated tests
13.2.3. New Methods in TemplateProcessor
13.2.4. RestAssured 3.0
13.3. 1.2.x → 2.0.x
14. Links

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

2.1.4.BUILD-SNAPSHOT

1. 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), @@ -651,7 +651,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either a map notation or String with interpolations. -Consult the Chapter 8, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

You must understand the map notation in order to set up contracts. Please read the +Consult the Chapter 9, Contract DSL section for more information. We highly recommend using the map notation!

[Tip]Tip

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

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

  • if an HTTP request is sent with all of

    • a PUT method on the /fraudcheck endpoint,
    • a JSON body with a client.id that matches the regular expression [0-9]{10} and loanAmount equal to 99999,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json,
  • then an HTTP response is sent to the consumer that

    • has status 200,
    • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and the rejectionReason field having value Amount too high,
    • and a Content-Type header with a value of application/vnd.fraud.v1+json.

Once you are ready to check the API in practice in the integration tests, you need to @@ -890,7 +890,7 @@ sides of the communication. You can pass the values:

Either via the

or using the $() method

$(consumer(...), producer(...))
 $(stub(...), test(...))
-$(client(...), server(...))

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

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +$(client(...), server(...))

You can read more about this in the Chapter 9, 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]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 @@ -1412,7 +1412,7 @@ 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 Section 10.1.1, “Pact Converter” section.

[Important]Important

Pact follows the Consumer Contract convention. That means +You can read more about it in the Section 11.1.1, “Pact Converter” section.

[Important]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 @@ -1537,24 +1537,86 @@ with pact:// protocol. E.g. p @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 Section 10.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

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

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

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

Starting from version 1.2.0 we turn on WireMock logging to +the Section 11.7, “Using the Pact Stub Downloader” section.

3.8 How can I debug the request/response being sent by the generated tests client?

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

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

3.8.1 How can I debug the mapping/request/response being sent by WireMock?

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

To turn off this feature just bump WireMock logging to ERROR

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

3.8.2 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.

3.8.3 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.

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in the following ways:

4.1 Gradle Project

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

4.1.1 Prerequisites

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

[Warning]Warning

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

4.1.2 Add Gradle Plugin with Dependencies

To add a Gradle plugin with dependencies, use code similar to this:

buildscript {
+docs for more information

5. Add Gradle Plugin with Dependencies

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

Plugin DSL GA versions.  +

// build.gradle
+plugins {
+  id "groovy"
+  // this will work only for GA versions of Spring Cloud Contract
+  id "org.springframework.cloud.contract" version "${GAVerifierVersion}"
+}
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${GAVerifierVersion}"
+	}
+}
+
+dependencies {
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
+	// example with adding Spock core and Spock Spring
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

+

Plugin DSL non GA versions.  +

// settings.gradle
+pluginManagement {
+	plugins {
+		id "org.springframework.cloud.contract" version "${verifierVersion}"
+	}
+    repositories {
+        // to pick from local .m2
+        mavenLocal()
+        // for snapshots
+        maven { url "https://repo.spring.io/snapshot" }
+        // for milestones
+        maven { url "https://repo.spring.io/milestone" }
+        // for GA versions
+        gradlePluginPortal()
+    }
+}
+
+// build.gradle
+plugins {
+  id "groovy"
+  id "org.springframework.cloud.contract"
+}
+
+dependencyManagement {
+	imports {
+		mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifierVersion}"
+	}
+}
+
+dependencies {
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
+	// example with adding Spock core and Spock Spring
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
+	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
+}

+

Legacy Plugin Application.  +

// build.gradle
+buildscript {
 	repositories {
 		mavenCentral()
 	}
 	dependencies {
-	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
+		classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
 		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
+        // here you can also pass additional dependencies such as Pact or Kotlin spec e.g.:
+        // classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${verifier_version}"
 	}
 }
 
@@ -1568,12 +1630,13 @@ dependencyManagement {
 }
 
 dependencies {
-	testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
+	testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}"
 	// example with adding Spock core and Spock Spring
-	testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
-	testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
+	testCompile "org.spockframework:spock-core:${spockVersion}"
+	testCompile "org.spockframework:spock-spring:${spockVersion}"
 	testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
-}

4.1.3 Gradle and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +}

+

5.1 Gradle and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x you can add it to the plugins classpath, as shown here:

buildscript {
 	repositories {
 		mavenCentral()
@@ -1592,8 +1655,29 @@ depenendencies {
     testCompile "com.jayway.restassured:rest-assured:2.5.0"
     testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
 }

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

4.1.4 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, -which are automatically uploaded after every successful build, as shown here:

buildscript {
+and modifies the imports accordingly.

5.2 Snapshot Versions for Gradle

Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here:

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

"https://repo.spring.io/milestone" } maven { url "https://repo.spring.io/release" } } -}

4.1.5 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +}

5.3 Add stubs

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

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

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

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

  • shouldCreateUser()
  • shouldReturnUser()

4.1.6 Run the Plugin

The plugin registers itself to be invoked before a check task. If you want it to be +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

5.4 Run the Plugin

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

4.1.7 Default Setup

The default Gradle Plugin setup creates the following Gradle part of the build (in +tests, invoke the generateContractTests task.

5.5 Default Setup

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

contracts {
     testFramework ='JUNIT'
     testMode = 'MockMvc'
@@ -1655,12 +1739,12 @@ publishing {
             artifact verifierStubsJar
         }
     }
-}

4.1.8 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as +}

5.6 Configure Plugin

To change the default configuration, add a contracts snippet to your Gradle config, as shown here:

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

4.1.9 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +}

5.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to Explicit for real HTTP calls.
  • imports: Creates an array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default, it creates an empty array.
  • staticImports: Creates an array with static imports that should be included in @@ -1688,7 +1772,7 @@ closure to set it up.
  • cont downloaded, the path defaults to groupid/artifactid where groupid is slash separated. Otherwise, it scans contracts under the provided directory.
  • contractsMode: Specifies the mode of downloading contracts (whether the JAR is available offline, remotely etc.)
  • deleteStubsAfterTest: If set to false will not remove any downloaded -contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.1.10 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +contracts from temporary directories

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

5.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base specification for all generated acceptance tests. In this class, you need to point to an endpoint, which should be verified.

abstract class BaseMockMvcSpec extends Specification {
 
@@ -1707,7 +1791,7 @@ endpoint, which should be verified.

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

4.1.11 Different Base Classes for Contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +only option to test the JAX-RS API is to start a web server.

5.9 Different Base Classes for Contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • Provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set the value of the packageWithBaseClasses property to com.example.base, then Spring Cloud Contract @@ -1726,14 +1810,14 @@ baseClassMappings { - src/test/resources/contract/foo/

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

4.1.12 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

4.1.13 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

5.10 Invoking Generated Tests

To ensure that the provider side is compliant with defined contracts, you need to invoke:

./gradlew generateContractTests test

5.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to the repository. To do that, it’s enough to call the pushStubsToScm -task. Example:

$ ./gradlew pushStubsToScm

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +task. Example:

$ ./gradlew pushStubsToScm

Under Section 11.6, “Using the SCM Stub Downloader” you can find all possible configuration options that you can pass either via the contractsProperties field e.g. contracts { contractsProperties = [foo:"bar"] }, via contractsProperties method e.g. contracts { contractsProperties([foo:"bar"]) }, -a system property or an environment variable.

4.1.14 Spring Cloud Contract Verifier on the Consumer Side

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +a system property or an environment variable.

5.12 Spring Cloud Contract Verifier on the Consumer Side

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

./gradlew generateClientStubs
[Note]Note

The stubsOutputDir option has to be set for stub generation to work.

When present, JSON stubs can be used in automated tests of consuming a service.

@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
@@ -1757,8 +1841,8 @@ WireMock JSON stubs using:

./gradlew generateClie
 	loanApplication.rejectionReason == null
  }
 }

LoanApplication makes a call to FraudDetection service. This request is handled by a -WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

4.2 Maven Project

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

4.2.1 Add maven plugin

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

<dependencyManagement>
+WireMock server configured with stubs generated by Spring Cloud Contract Verifier.

5.13 Maven Project

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

5.13.1 Add maven plugin

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

<dependencyManagement>
 	<dependencies>
 		<dependency>
 			<groupId>org.springframework.cloud</groupId>
@@ -1779,7 +1863,7 @@ following sections:

    </configuration> </plugin>

You can read more in the Spring -Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

4.2.2 Maven and Rest Assured 2.0

By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Cloud Contract Maven Plugin Documentation (example for 2.0.0.RELEASE version).

5.13.2 Maven and Rest Assured 2.0

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

<plugin>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-contract-maven-plugin</artifactId>
@@ -1825,7 +1909,7 @@ Assured 2.x by adding it to the plugins classpath, as shown here:

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

4.2.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your +and modifies the imports accordingly.

5.13.3 Snapshot versions for Maven

For Snapshot and Milestone versions, you have to add the following section to your pom.xml, as shown here:

<repositories>
 	<repository>
 		<id>spring-snapshots</id>
@@ -1877,16 +1961,16 @@ and modifies the imports accordingly.

<enabled>false</enabled> </snapshots> </pluginRepository> -</pluginRepositories>

4.2.4 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +</pluginRepositories>

5.13.4 Add stubs

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

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

Spring Cloud Contract Verifier creates a test class named defaultBasePackage.MyService -with two methods

  • shouldCreateUser()
  • shouldReturnUser()

4.2.5 Run plugin

The plugin goal generateTests is assigned to be invoked in the phase called +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

5.13.5 Run plugin

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

4.2.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin +anything. If you just want to generate tests, invoke the generateTests goal.

5.13.6 Configure plugin

To change the default configuration, just add a configuration section to the plugin definition or the execution definition, as shown here:

<plugin>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-contract-maven-plugin</artifactId>
@@ -1903,7 +1987,7 @@ definition or the execution definition, as shown he
         <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
         <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
     </configuration>
-</plugin>

4.2.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, +</plugin>

5.13.7 Configuration Options

  • testMode: Defines the mode for acceptance tests. By default, the mode is MockMvc, which is based on Spring’s MockMvc. It can also be changed to WebTestClient, JaxRsClient or to Explicit for real HTTP calls.
  • basePackageForTests: Specifies the base package for all generated tests. If not set, the value is picked from baseClassForTests’s package and from `packageWithBaseClasses. @@ -1933,7 +2017,7 @@ the following options:

      groupid/artifactid where gropuid is slash separated.
    • contractsMode: Picks the mode in which stubs will be found and registered
    • deleteStubsAfterTest: If set to false will not remove any downloaded contracts from temporary directories
    • contractsRepositoryUrl: URL to a repo with the artifacts that have contracts. If it is not provided, use the current Maven ones.
    • contractsRepositoryUsername: The user name to be used to connect to the repo with contracts.
    • contractsRepositoryPassword: The password to be used to connect to the repo with contracts.
    • contractsRepositoryProxyHost: The proxy host to be used to connect to the repo with contracts.
    • contractsRepositoryProxyPort: The proxy port to be used to connect to the repo with contracts.

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

    Below you can find a list of experimental features you can turn on via the plugin:

    • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
    • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

4.2.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base ++ or 1.0.0.BUILD-SNAPSHOT won’t get cached). By default, this feature is turned on.

Below you can find a list of experimental features you can turn on via the plugin:

  • convertToYaml: converts all DSLs to the declarative, YAML format. This can be extremely useful when you’re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to true) you will not need to add the library dependency on the consumer side.
  • assertJsonSize: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.

5.13.8 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base specification for all generated acceptance tests. In this class, you need to point to an endpoint, which should be verified.

package org.mycompany.tests
 
@@ -1986,7 +2070,7 @@ similarly, as you might find in regular integration tests.

"http://localhost:" + this.port;
 	}
 }

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

4.2.9 Different base classes for contracts

If your base classes differ between contracts, you can tell the Spring Cloud Contract +now, the only option to test the JAX-RS API is to start a web server.

5.13.9 Different base classes for contracts

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

  • Follow a convention by providing the packageWithBaseClasses
  • provide explicit mapping via baseClassMappings

By Convention

The convention is such that if you have a contract under (for example) src/test/resources/contract/foo/bar/baz/ and set the value of the packageWithBaseClasses property to com.example.base, then Spring Cloud Contract @@ -2019,7 +2103,7 @@ name of the base class for the matched contract. You have to provide a list call * 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.

4.2.10 Invoking generated tests

The Spring Cloud Contract Maven Plugin generates verification code in a directory called +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

5.13.10 Invoking generated tests

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

For Groovy Spock code, use the following:

<plugin>
 	<groupId>org.codehaus.gmavenplus</groupId>
@@ -2049,7 +2133,7 @@ goal.

For Groovy Spock code, use the following:

</testSources>
 	</configuration>
 </plugin>

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

4.2.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and +mvn generateTest test.

5.13.11 Pushing stubs to SCM

If you’re using the SCM repository to keep the contracts and stubs, you might want to automate the step of pushing stubs to the repository. To do that, it’s enough to add the pushStubsToScm goal. Example:

<plugin>
@@ -2085,10 +2169,10 @@ goal. Example:

</goals>
         </execution>
     </executions>
-</plugin>

Under Section 10.6, “Using the SCM Stub Downloader” you can find all possible +</plugin>

Under Section 11.6, “Using the SCM Stub Downloader” you can find all possible configuration options that you can pass either via the <configuration><contractProperties> map, a system property -or an environment variable.

4.2.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

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

 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
+or an environment variable.

5.13.12 Maven Plugin and STS

If you see the following exception while using STS:

STS Exception

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

 plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
  cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
  org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
 ...
@@ -2125,13 +2209,13 @@ or an environment variable.

</plugin> </plugins> </pluginManagement> -</build>

4.2.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract +</build>

5.13.13 Maven Plugin with Spock Tests

You can select the Spock Framework for creating and executing the auto-generated contract verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward, in Maven you will require some additional setup in order to make the tests compile and execute properly.

First of all, you will have to use a plugin, such as GMavenPlus plugin, to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the path where your base test classes are defined and the path were the generated contract tests are added. Please refer to the example below:

If you uphold to the Spock convention of ending the test class names with Spec, you will also need to adjust your Maven -Surefire plugin setup, like in the following example:

4.3 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +Surefire plugin setup, like in the following example:

5.14 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One problem that arises is that, when reusing the stubs, you can mistakenly import all of that stub’s dependencies. When building a Maven artifact, even though you have a couple of different jars, all of them share one pom:

├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
@@ -2148,7 +2232,7 @@ when you include the github-webhook stubs in anothe
 dependency gets downloaded by Stub Runner) then, since all of the dependencies are
 optional, they will not get downloaded.

Create a separate artifactid for the stubs

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

Exclude dependencies on the consumer side

As a consumer, if you add the stub dependency to your classpath, you can explicitly -exclude the unwanted dependencies.

4.4 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +exclude the unwanted dependencies.

5.15 Scenarios

You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to the proper naming convention while creating your contracts. The convention requires including an order number followed by an underscore. This will work regardles of whether you’re working with YAML or Groovy. Example:

my_contracts_dir\
@@ -2157,10 +2241,10 @@ requires including an order number followed by an underscore. This will work reg
     2_showCart.groovy
     3_logout.groovy

Such a tree causes Spring Cloud Contract Verifier to generate WireMock’s scenario with a name of scenario1 and the three following steps:

  1. login marked as Started pointing to…​
  2. showCart marked as Step1 pointing to…​
  3. logout marked as Step2 which will close the scenario.

More details about WireMock scenarios can be found at -https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

4.5 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image +https://wiremock.org/docs/stateful-behaviour/

Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.

5.16 Docker Project

We’re publishing a springcloud/spring-cloud-contract Docker image that contains a project that will generate tests and execute them in EXPLICIT mode against a running application.

[Tip]Tip

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

4.5.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to +real requests and not the mocked ones.

5.16.1 Short intro to Maven, JARs and Binary storage

Since the Docker image can be used by non JVM projects, it’s good to explain the basic terms behind Spring Cloud Contract packaging defaults.

Part of the following definitions were taken from the Maven Glossary

  • Project: Maven thinks in terms of projects. Everything that you will build are projects. Those projects follow a well defined “Project Object Model”. Projects can depend on other projects, @@ -2187,7 +2271,7 @@ like them to be available for others to download / reference or reuse. In case of the JVM world those artifacts would be JARs, for Ruby these are gems and for Docker those would be Docker images. You can store those artifacts in a manager. Examples of such managers can be Artifactory -or Nexus.

4.5.2 How it works

The image searches for contracts under the /contracts folder. +or Nexus.

5.16.2 How it works

The image searches for contracts under the /contracts folder. The output from running the tests will be available under /spring-cloud-contract/build folder (it’s useful for debugging purposes).

It’s enough for you to mount your contracts, pass the environment variables @@ -2202,8 +2286,8 @@ for group id foo.bar and artifact id .m2. Mount your local .m2 as a volume available at the container’s /root/.m2 path. You must not set both EXTERNAL_CONTRACTS_WORK_OFFLINE and EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL.

These environment variables are used when tests are executed:

  • APPLICATION_BASE_URL - url against which tests should be executed. Remember that it has to be accessible from the Docker container (e.g. localhost -will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application

4.5.3 Example of usage

Let’s take a look at a simple MVC application

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

The contracts are available under /contracts folder.

4.5.4 Server side (nodejs)

Since we want to run tests, we could just execute:

$ npm test

however, for learning purposes, let’s split it into pieces:

# Stop docker infra (nodejs, artifactory)
+will not work)
  • APPLICATION_USERNAME - (optional) username for basic authentication to your application
  • APPLICATION_PASSWORD - (optional) password for basic authentication to your application
  • 5.16.3 Example of usage

    Let’s take a look at a simple MVC application

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

    The contracts are available under /contracts folder.

    5.16.4 Server side (nodejs)

    Since we want to run tests, we could just execute:

    $ npm test

    however, for learning purposes, let’s split it into pieces:

    # Stop docker infra (nodejs, artifactory)
     $ ./stop_infra.sh
     # Start docker infra (nodejs, artifactory)
     $ ./setup_infra.sh
    @@ -2235,9 +2319,9 @@ stateful situation

      • the contracts will be taken from /contracts folder.
      • the output of the test execution is available under node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.
  • To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

    5. Spring Cloud Contract Verifier Messaging

    Spring Cloud Contract Verifier lets you verify applications that use messaging as a +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    To see how the client side looks like check out the Section 7.9, “Stub Runner Docker” section.

    6. 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.

    5.1 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 +but you can also create one of your own and use that.

    6.1 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]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]Important

    If you want to use Spring Cloud Stream, remember to add a dependency on @@ -2249,7 +2333,7 @@ work.

    </dependency>

    Gradle. 

    testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

    -

    5.2 Manual Integration Testing

    The main interface used by the tests is +

    6.2 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 @@ -2263,14 +2347,14 @@ Here’s an example:

    private MessageVerifier verifier;
       ...
     }
    [Note]Note

    If your tests require stubs as well, then @AutoConfigureStubRunner includes the -messaging configuration, so you only need the one annotation.

    5.3 Publisher-Side Test Generation

    Having the input or outputMessage sections in your DSL results in creation of tests +messaging configuration, so you only need the one annotation.

    6.3 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 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]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).

    5.3.1 Scenario 1: No Input Message

    For the given contract:

    Groovy DSL.  +jms).

    6.3.1 Scenario 1: No Input Message

    For the given contract:

    Groovy DSL. 

    			def contractDsl = Contract.make {
     				label 'some_label'
     				input {
    @@ -2323,7 +2407,7 @@ outputMessage:
       DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
       assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
     
    -'''

    5.3.2 Scenario 2: Output Triggered by Input

    For the given contract:

    Groovy DSL.  +'''

    6.3.2 Scenario 2: Output Triggered by Input

    For the given contract:

    Groovy DSL. 

    			def contractDsl = Contract.make {
     				label 'some_label'
     				input {
    @@ -2394,7 +2478,7 @@ then:
     and:
        DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
        assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
    -"""

    5.3.3 Scenario 3: No Output Message

    For the given contract:

    Groovy DSL.  +"""

    6.3.3 Scenario 3: No Output Message

    For the given contract:

    Groovy DSL. 

    			def contractDsl = Contract.make {
     				label 'some_label'
     				input {
    @@ -2442,8 +2526,8 @@ when:
     then:
     	 noExceptionThrown()
     	 bookWasDeleted()
    -'''

    5.4 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 Chapter 7, Stub Runner for Messaging section.

    Maven.  +'''

    6.4 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 Chapter 8, Stub Runner for Messaging section.

    Maven. 

    <dependencies>
     	<dependency>
     		<groupId>org.springframework.cloud</groupId>
    @@ -2492,11 +2576,11 @@ publishing {
     		}
     	}
     }

    -

    6. Spring Cloud Contract Stub Runner

    One of the issues that you might encounter while using Spring Cloud Contract Verifier is +

    7. 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.

    6.1 Snapshot versions

    Add the additional snapshot repository to your build.gradle file to use snapshot +automatically download and run the stubs for you.

    7.1 Snapshot versions

    Add the additional snapshot repository to your build.gradle file to use snapshot versions, which are automatically uploaded after every successful build:

    Maven. 

    <repositories>
     	<repository>
    @@ -2551,7 +2635,28 @@ versions, which are automatically uploaded after every successful build:

    </pluginRepository> </pluginRepositories>

    Gradle.  -

    buildscript {
    +

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

    "https://repo.spring.io/milestone" } maven { url "https://repo.spring.io/release" } }

    -

    6.2 Publishing Stubs as JARs

    The easiest approach would be to centralize the way stubs are kept. For example, you can +

    7.2 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]Tip

    For both Maven and Gradle, the setup comes ready to work. However, you can customize it if you want to.

    Maven. 

    <!-- First disable the default jar setup in the properties section -->
    @@ -2649,9 +2754,9 @@ publishing {
     		}
     	}
     }

    -

    6.3 Stub Runner Core

    Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of +

    7.3 Stub Runner Core

    Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of Consumer Driven Contracts.

    Stub Runner allows you to automatically download the stubs of the provided dependencies (or pick those from the classpath), start WireMock servers for them and feed them with proper stub definitions. -For messaging, special stub routes are defined.

    6.3.1 Retrieving stubs

    You can pick the following options of acquiring stubs

    • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
    • Classpath scanning solution that searches classpath via pattern to retrieve stubs
    • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    The latter example is described in the Custom Stub Runner section.

    Stub downloading

    You can control the stub downloading via the stubsMode switch. It picks value from the +For messaging, special stub routes are defined.

    7.3.1 Retrieving stubs

    You can pick the following options of acquiring stubs

    • Aether based solution that downloads JARs with stubs from Artifactory / Nexus
    • Classpath scanning solution that searches classpath via pattern to retrieve stubs
    • Write your own implementation of the org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder for full customization

    The latter example is described in the Custom Stub Runner section.

    Stub downloading

    You can control the stub downloading via the stubsMode switch. It picks value from the StubRunnerProperties.StubsMode enum. You can use the following options

    • StubRunnerProperties.StubsMode.CLASSPATH (default value) - will pick stubs from the classpath
    • StubRunnerProperties.StubsMode.LOCAL - will pick stubs from a local storage (e.g. .m2)
    • StubRunnerProperties.StubsMode.REMOTE - will pick stubs from a remote location

    Example:

    @AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)

    Classpath scanning

    If you set the stubsMode property to StubRunnerProperties.StubsMode.CLASSPATH (or set nothing since CLASSPATH is the default value) then classpath will get scanned. Let’s look at the following example:

    @AutoConfigureStubRunner(ids = {
    @@ -2738,7 +2843,7 @@ case might be starting WireMock for the given artifact id, on an HTTPs port. Exa
     	}
     }

    You can then reuse it via the annotation

    @AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
    -		httpServerStubConfigurer = HttpsForFraudDetection)

    Whenever an https port is found, it will take precedence over the http one.

    6.3.2 Running stubs

    Running using main app

    You can set the following options to the main class:

    -c, --classifier                Suffix for the jar containing stubs (e.
    +		httpServerStubConfigurer = HttpsForFraudDetection)

    Whenever an https port is found, it will take precedence over the http one.

    7.3.2 Running stubs

    Running using main app

    You can set the following options to the main class:

    -c, --classifier                Suffix for the jar containing stubs (e.
                                       g. 'stubs' if the stub jar would
                                       have a 'stubs' classifier for stubs:
                                       foobar-stubs ). Defaults to 'stubs'
    @@ -2801,7 +2906,7 @@ mappings available for the given server:

    ["uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
     },
     ...
    -]

    Messaging Stubs

    Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

    6.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

    Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

    @ClassRule
    +]

    Messaging Stubs

    Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.

    7.4 Stub Runner JUnit Rule and Stub Runner JUnit5 Extension

    Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

    @ClassRule
     public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
     		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
     		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
    @@ -2951,9 +3056,9 @@ def 'should outp
     	}
     }

    Check the Common properties for JUnit and Spring for more information on how to apply global configuration of Stub Runner.

    [Important]Important

    To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the MessageVerifier interface to the rule builder (e.g. rule.messageVerifier(new MyMessageVerifier())). -If you don’t do this, then whenever you try to send a message an exception will be thrown.

    6.4.1 Maven settings

    The stub downloader honors Maven settings for a different local repository folder. -Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

    6.4.2 Providing fixed ports

    You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of -JUnit rule.

    6.4.3 Fluent API

    When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

    @ClassRule
    +If you don’t do this, then whenever you try to send a message an exception will be thrown.

    7.4.1 Maven settings

    The stub downloader honors Maven settings for a different local repository folder. +Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

    7.4.2 Providing fixed ports

    You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of +JUnit rule.

    7.4.3 Fluent API

    When using the StubRunnerRule or StubRunnerExtension you can add a stub to download and then pass the port for the last downloaded stub.

    @ClassRule
     public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
     		.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
     		.downloadStub("org.springframework.cloud.contract.verifier.stubs",
    @@ -2969,7 +3074,7 @@ JUnit rule.

    You can see that for this example the following test is valid:

    then(rule.findStubUrl("loanIssuance"))
     		.isEqualTo(URI.create("http://localhost:12345").toURL());
     then(rule.findStubUrl("fraudDetectionServer"))
    -		.isEqualTo(URI.create("http://localhost:12346").toURL());

    6.4.4 Stub Runner with Spring

    Sets up Spring configuration of the Stub Runner project.

    By providing a list of stubs inside your configuration file the Stub Runner automatically downloads + .isEqualTo(URI.create("http://localhost:12346").toURL());

    7.4.4 Stub Runner with Spring

    Sets up Spring configuration of the Stub Runner project.

    By providing a list of stubs inside your configuration file the Stub Runner automatically downloads and registers in WireMock the selected stubs.

    If you want to find the URL of your stubbed dependency you can autowire the StubFinder interface and use its methods as presented below:

    @ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
     @SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
    @@ -3106,7 +3211,7 @@ Value of the annotation can be the groupid:artifactidcom.example:foo, com.example:bar.

    @StubRunnerPort("foo")
     int fooPort;
     @StubRunnerPort("com.example:bar")
    -int barPort;

    6.5 Stub Runner Spring Cloud

    Stub Runner can integrate with Spring Cloud.

    For real life examples you can check the

    6.5.1 Stubbing Service Discovery

    The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

    • DiscoveryClient
    • Ribbon ServerList

    that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. +int barPort;

    7.5 Stub Runner Spring Cloud

    Stub Runner can integrate with Spring Cloud.

    For real life examples you can check the

    7.5.1 Stubbing Service Discovery

    The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

    • DiscoveryClient
    • Ribbon ServerList

    that means that regardless of the fact whether you’re using Zookeeper, Consul, Eureka or anything else, you don’t need that in your tests. We’re starting WireMock instances of your dependencies and we’re telling your application whenever you’re using Feign, load balanced RestTemplate or DiscoveryClient directly, to call those stubbed servers instead of calling the real Service Discovery tool.

    For example this test will pass

    def 'should make service discovery work'() {
     	expect: 'WireMocks are running'
    @@ -3125,16 +3230,16 @@ via a static block like presented below (example for Eureka)

    static {
             System.setProperty("eureka.client.enabled", "false");
             System.setProperty("spring.cloud.config.failFast", "false");
    -    }

    6.5.2 Additional Configuration

    You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. + }

    7.5.2 Additional Configuration

    You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false You can disable Stub Runner support by providing: stubrunner.cloud.enabled equal to false

    [Tip]Tip

    By default all service discovery will be stubbed. That means that regardless of the fact if you have an existing DiscoveryClient its results will be ignored. However, if you want to reuse it, just set stubrunner.cloud.delegate.enabled to true and then your existing DiscoveryClient results will be merged with the stubbed ones.

    The default Maven configuration used by Stub Runner can be tweaked either -via the following system properties or environment variables

    • maven.repo.local - path to the custom maven local repository location
    • org.apache.maven.user-settings - path to custom maven user settings location
    • org.apache.maven.global-settings - path to maven global settings location

    6.6 Stub Runner Boot Application

    Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to +via the following system properties or environment variables

    • maven.repo.local - path to the custom maven local repository location
    • org.apache.maven.user-settings - path to custom maven user settings location
    • org.apache.maven.global-settings - path to maven global settings location

    7.6 Stub Runner Boot Application

    Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to trigger the messaging labels and to access started WireMock servers.

    One of the use-cases is to run some smoke (end to end) tests on a deployed application. You can check out the Spring Cloud Pipelines -project for more information.

    6.6.1 How to use it?

    Stub Runner Server

    Just add the

    compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

    Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

    For the properties check the Stub Runner Spring section.

    Stub Runner Server Fat Jar

    You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

    $ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
    +project for more information.

    7.6.1 How to use it?

    Stub Runner Server

    Just add the

    compile "org.springframework.cloud:spring-cloud-starter-stub-runner"

    Annotate a class with @EnableStubRunnerServer, build a fat-jar and you’re ready to go!

    For the properties check the Stub Runner Spring section.

    Stub Runner Server Fat Jar

    You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:

    $ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
     $ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...

    Spring Cloud CLI

    Starting from 1.4.0.RELEASE version of the Spring Cloud CLI project you can start Stub Runner Boot by executing spring cloud stubrunner.

    In order to pass the configuration just create a stubrunner.yml file in the current working directory or a subdirectory called config or in ~/.spring-cloud. The file could look like this @@ -3144,7 +3249,7 @@ or a subdirectory called config or in spring cloud stubrunner from your terminal window to start -the Stub Runner server. It will be available at port 8750.

    6.6.2 Endpoints

    HTTP

    • GET /stubs - returns a list of all running stubs in ivy:integer notation
    • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    Messaging

    For Messaging

    • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
    • POST /triggers/{label} - executes a trigger with label
    • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    6.6.3 Example

    @ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
    +the Stub Runner server. It will be available at port 8750.

    7.6.2 Endpoints

    HTTP

    • GET /stubs - returns a list of all running stubs in ivy:integer notation
    • GET /stubs/{ivy} - returns a port for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    Messaging

    For Messaging

    • GET /triggers - returns a list of all running labels in ivy : [ label1, label2 …​] notation
    • POST /triggers/{label} - executes a trigger with label
    • POST /triggers/{ivy}/{label} - executes a trigger with label for the given ivy notation (when calling the endpoint ivy can also be artifactId only)

    7.6.3 Example

    @ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
     @SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
     @ActiveProfiles("test")
     class StubRunnerBootSpec extends Specification {
    @@ -3231,7 +3336,7 @@ the Stub Runner server. It will be available at port 8750<
     			e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
     	}
     
    -}

    6.6.4 Stub Runner Boot with Service Discovery

    One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? +}

    7.6.4 Stub Runner Boot with Service Discovery

    One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? Let’s assume that you don’t want to deploy 50 microservice to a test environment in order to check if your application is working fine. You’ve already executed a suite of tests during the build process but you would also like to ensure that the packaging of your application is fine. What you can do @@ -3266,7 +3371,7 @@ and we want to have the stub runner feature turned on @Aut * be picked (3) - we provide a list of stubs to download (4) - we provide a list of

    That way your deployed application can send requests to started WireMock servers via the service discovery. Most likely points 1-3 could be set by default in application.yml cause they are not likely to change. That way you can provide only the list of stubs to download whenever you start -the Stub Runner Boot.

    6.7 Stubs Per Consumer

    There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

    [Tip]Tip

    This approach also allows you to immediately know which consumer is using which part of your API. +the Stub Runner Boot.

    7.7 Stubs Per Consumer

    There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

    [Tip]Tip

    This approach also allows you to immediately know which consumer is using which part of your API. You can remove part of a response that your API produces and you can see which of your autogenerated tests fails. If none fails then you can safely delete that part of the response cause nobody is using it.

    Let’s look at the following example for contract defined for the producer called producer. There are 2 consumers: foo-consumer and bar-consumer.

    Consumer foo-service

    request {
    @@ -3319,25 +3424,25 @@ Or set the test as follows:

    Then only the stubs registered under a path that contains the foo-consumer in its name (i.e. those from the src/test/resources/contracts/foo-consumer/some/contracts/…​ folder) will be allowed to be referenced.

    You can check out issue 224 for more -information about the reasons behind this change.

    6.8 Common

    This section briefly describes common properties, including:

    6.8.1 Common Properties for JUnit and Spring

    You can set repetitive properties by using system properties or Spring configuration +information about the reasons behind this change.

    7.8 Common

    This section briefly describes common properties, including:

    7.8.1 Common Properties for JUnit and Spring

    You can set repetitive properties by using system properties or Spring configuration properties. Here are their names with their default values:

    Property nameDefault valueDescription

    stubrunner.minPort

    10000

    Minimum value of a port for a started WireMock with stubs.

    stubrunner.maxPort

    15000

    Maximum value of a port for a started WireMock with stubs.

    stubrunner.repositoryRoot

     

    Maven repo URL. If blank, then call the local maven repo.

    stubrunner.classifier

    stubs

    Default classifier for the stub artifacts.

    stubrunner.stubsMode

    CLASSPATH

    The way you want to fetch and register the stubs

    stubrunner.ids

     

    Array of Ivy notation stubs to download.

    stubrunner.username

     

    Optional username to access the tool that stores the JARs with stubs.

    stubrunner.password

     

    Optional password to access the tool that stores the JARs with stubs.

    stubrunner.stubsPerConsumer

    false

    Set to true if you want to use different stubs for each consumer instead of registering all stubs for every consumer.

    stubrunner.consumerName

     

    If you want to use a stub for each consumer and want to -override the consumer name just change this value.

    6.8.2 Stub Runner Stubs IDs

    You can provide the stubs to download via the stubrunner.ids system property. They +override the consumer name just change this value.

    7.8.2 Stub Runner Stubs IDs

    You can provide the stubs to download via the stubrunner.ids system property. They follow this pattern:

    groupId:artifactId:version:classifier:port

    Note that version, classifier and port are optional.

    • If you do not provide the port, a random one will be picked.
    • If you do not provide the classifier, the default is used. (Note that you can pass an empty classifier this way: groupId:artifactId:version:).
    • If you do not provide the version, then the + will be passed and the latest one is downloaded.

    port means the port of the WireMock server.

    [Important]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 Aether versioning -ranges here.

    6.9 Stub Runner Docker

    We’re publishing a spring-cloud/spring-cloud-contract-stub-runner Docker image +ranges here.

    7.9 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 Section 4.5, “Docker Project”.

    6.9.1 How to use it

    Just execute the docker image. You can pass any of the Section 6.8.1, “Common Properties for JUnit and Spring” +group ids, classifiers and Artifact Managers, just click here Section 5.16, “Docker Project”.

    7.9.1 How to use it

    Just execute the docker image. You can pass any of the Section 7.8.1, “Common Properties for JUnit and Spring” as environment variables. The convention is that all the letters should be upper case. The camel case notation should and the dot (.) should be separated via underscore (_). E.g. the stubrunner.repositoryRoot property should be represented - as a STUBRUNNER_REPOSITORY_ROOT environment variable.

    6.9.2 Example of client side usage in a non JVM project

    We’d like to use the stubs created in this Section 4.5.4, “Server side (nodejs)” step. + as a STUBRUNNER_REPOSITORY_ROOT environment variable.

    7.9.2 Example of client side usage in a non JVM project

    We’d like to use the stubs created in this Section 5.16.4, “Server side (nodejs)” step. Let’s assume that we want to run the stubs on port 9876. The NodeJS code is available here:

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

    Let’s run the Stub Runner Boot application with the stubs.

    # Provide the Spring Cloud Contract Docker version
    @@ -3357,11 +3462,11 @@ $ curl -H "Conte
     $ curl -X GET http://localhost:9876/api/books
     # You will receive contents of the JSON
    [Important]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"

    7. Stub Runner for Messaging

    Stub Runner can run the published stubs in memory. It can integrate with the following +the volume of your local m2 -v "${HOME}/.m2/:/root/.m2:ro"

    8. 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]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.

    7.1 Stub triggering

    To trigger a message, use the StubTrigger interface:

    package org.springframework.cloud.contract.stubrunner;
    +That way the only remaining framework is Spring AMQP.

    8.1 Stub triggering

    To trigger a message, use the StubTrigger interface:

    package org.springframework.cloud.contract.stubrunner;
     
     import java.util.Collection;
     import java.util.Map;
    @@ -3408,10 +3513,10 @@ That way the only remaining framework is Spring AMQP.

    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:

    7.1.1 Trigger by Label

    stubFinder.trigger('return_book_1')

    7.1.2 Trigger by Group and Artifact Ids

    stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

    7.1.3 Trigger by Artifact Ids

    stubFinder.trigger('streamService', 'return_book_1')

    7.1.4 Trigger All Messages

    stubFinder.trigger()

    7.2 Stub Runner Camel

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. +or the other in your tests.

    StubTrigger gives you the following options to trigger a message:

    8.1.1 Trigger by Label

    stubFinder.trigger('return_book_1')

    8.1.2 Trigger by Group and Artifact Ids

    stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

    8.1.3 Trigger by Artifact Ids

    stubFinder.trigger('streamService', 'return_book_1')

    8.1.4 Trigger All Messages

    stubFinder.trigger()

    8.2 Stub Runner Camel

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. For the provided artifacts it will automatically download the stubs and register the required -routes.

    7.2.1 Adding it to the project

    It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with @AutoConfigureStubRunner.

    7.2.2 Disabling the functionality

    If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

    7.2.3 Examples

    Stubs structure

    Let us assume that we have the following Maven repository with a deployed stubs for the +routes.

    8.2.1 Adding it to the project

    It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. +Remember to annotate your test class with @AutoConfigureStubRunner.

    8.2.2 Disabling the functionality

    If you need to disable this functionality just pass stubrunner.camel.enabled=false property.

    8.2.3 Examples

    Stubs structure

    Let us assume that we have the following Maven repository with a deployed stubs for the camelService application.

    └── .m2
         └── repository
             └── io
    @@ -3468,10 +3573,10 @@ receivedMessage.in.headers.get('jms:input', new BookReturned('foo'), [sample: 'header'])

    Next we’ll want to listen to the output of the message sent to jms:output

    Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)

    And the received message would pass the following assertions

    receivedMessage != null
     assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
     receivedMessage.in.headers.get('BOOK-NAME') == 'foo'

    Scenario 3 (input with no output)

    Since the route is set for you it’s enough to just send a message to the jms:output destination.

    producerTemplate.
    -		sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

    7.3 Stub Runner Integration

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to + sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])

    8.3 Stub Runner Integration

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Integration. For the provided artifacts, it automatically downloads -the stubs and registers the required routes.

    7.3.1 Adding the Runner to the Project

    You can have both Spring Integration and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    7.3.2 Disabling the functionality

    If you need to disable this functionality, set the +the stubs and registers the required routes.

    8.3.1 Adding the Runner to the Project

    You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    8.3.2 Disabling the functionality

    If you need to disable this functionality, set the stubrunner.integration.enabled=false property.

    Assume that you have the following Maven repository with deployed stubs for the integrationService application:

    └── .m2
         └── repository
    @@ -3547,7 +3652,7 @@ assertJsons(receivedMessage.payload)
     receivedMessage.headers.get('BOOK-NAME') == 'foo'

    Scenario 2 (output triggered by input)

    Since the route is set for you, you can send a message to the output destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')

    To listen to the output of the message sent to output:

    Message<?> receivedMessage = messaging.receive('outputTest')

    The received message passes the following assertions:

    receivedMessage != null
     assertJsons(receivedMessage.payload)
    -receivedMessage.headers.get('BOOK-NAME') == 'foo'

    Scenario 3 (input with no output)

    Since the route is set for you, you can send a message to the input destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

    7.4 Stub Runner Stream

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to +receivedMessage.headers.get('BOOK-NAME') == 'foo'

    Scenario 3 (input with no output)

    Since the route is set for you, you can send a message to the input destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

    8.4 Stub Runner Stream

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Stream. For the provided artifacts, it automatically downloads the stubs and registers the required routes.

    [Warning]Warning

    If Stub Runner’s integration with Stream the messageFrom or sentTo Strings are resolved first as a destination of a channel and no such destination exists, the @@ -3560,8 +3665,8 @@ destination is resolved as a channel name.

    </dependency>

    Gradle. 

    testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

    -

    7.4.1 Adding the Runner to the Project

    You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the -classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    7.4.2 Disabling the functionality

    If you need to disable this functionality, set the stubrunner.stream.enabled=false +

    8.4.1 Adding the Runner to the Project

    You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    8.4.2 Disabling the functionality

    If you need to disable this functionality, set the stubrunner.stream.enabled=false property.

    Assume that you have the following Maven repository with a deployed stubs for the streamService application:

    └── .m2
         └── repository
    @@ -3628,7 +3733,7 @@ receivedMessage.headers.get(destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')

    To listen to the output of the message sent to returnBook:

    Message<?> receivedMessage = messaging.receive('returnBook')

    The received message passes the following assertions:

    receivedMessage != null
     assertJsons(receivedMessage.payload)
     receivedMessage.headers.get('BOOK-NAME') == 'foo'

    Scenario 3 (input with no output)

    Since the route is set for you, you can send a message to the output -destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

    7.5 Stub Runner Spring AMQP

    Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to +destination:

    messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')

    8.5 Stub Runner Spring AMQP

    Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it automatically downloads the stubs and registers the required routes.

    The integration tries to work standalone (that is, without interaction with a running RabbitMQ message broker). It expects a RabbitTemplate on the application context and @@ -3641,7 +3746,7 @@ Spring AMQP stub runner integration looks for bindings on the application contex match this exchange. Then it collects the queues from the Spring exchanges and tries to find message listeners bound to these queues. The message is triggered for all matching message listeners.

    If you need to work with routing keys, it’s enough to pass them via the amqp_receivedRoutingKey -messaging header.

    7.5.1 Adding the Runner to the Project

    You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +messaging header.

    8.5.1 Adding the Runner to the Project

    You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and set the property stubrunner.amqp.enabled=true. Remember to annotate your test class with @AutoConfigureStubRunner.

    [Important]Important

    If you already have Stream and Integration on the classpath, you need to disable them explicitly by setting the stubrunner.stream.enabled=false and @@ -3714,7 +3819,7 @@ definition is matched and invoked with the contract message.

    ConnectionFactory.

    To disable the mocked ConnectionFactory, set the following property: stubrunner.amqp.mockConnection=false

    stubrunner:
       amqp:
    -    mockConnection: false

    8. Contract DSL

    Spring Cloud Contract supports out of the box 2 types of DSL. One written in + mockConnection: false

    9. Contract DSL

    Spring Cloud Contract supports out of the box 2 types of DSL. One written in Groovy and one written in YAML.

    If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy before. Knowledge of the language is not really needed, as the Contract DSL uses only a tiny subset of it (only literals, method calls and closures). Also, the DSL is statically @@ -3771,13 +3876,13 @@ response: regex: bar - key: foo3 command: andMeToo($it)

    [Tip]Tip

    You can compile contracts to stubs mapping using standalone maven command: -mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

    8.1 Limitations

    [Warning]Warning

    Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

    9.1 Limitations

    [Warning]Warning

    Spring Cloud Contract Verifier does not properly support XML. Please use JSON or help us implement this feature.

    [Warning]Warning

    The support for verifying the size of JSON arrays is experimental. If you want to turn it on, please set the value of the following system property to true: spring.cloud.contract.verifier.assert.size. By default, this feature is set to false. You can also provide the assertJsonSize property in the plugin configuration.

    [Warning]Warning

    Because JSON structure can have any form, it can be impossible to parse it properly when using the Groovy DSL and the value(consumer(…​), producer(…​)) notation in GString. That -is why you should use the Groovy Map notation.

    8.2 Common Top-Level elements

    The following sections describe the most common top-level elements:

    8.2.1 Description

    You can add a description to your contract. The description is arbitrary text. The +is why you should use the Groovy Map notation.

    9.2 Common Top-Level elements

    The following sections describe the most common top-level elements:

    9.2.1 Description

    You can add a description to your contract. The description is arbitrary text. The following code shows an example:

    Groovy DSL. 

    			org.springframework.cloud.contract.spec.Contract.make {
     				description('''
    @@ -3839,7 +3944,7 @@ response:
             regex: bar
           - key: foo3
             command: andMeToo($it)

    -

    8.2.2 Name

    You can provide a name for your contract. Assume that you provided the following name: +

    9.2.2 Name

    You can provide a name for your contract. Assume that you provided the following name: should register a user. If you do so, the name of the autogenerated test is validate_should_register_a_user. Also, the name of the stub in a WireMock stub is should_register_a_user.json.

    [Important]Important

    You must ensure that the name does not contain any characters that make the @@ -3851,14 +3956,14 @@ override each other.

    Groovy DSL.  }

    YAML. 

    name: some name

    -

    8.2.3 Ignoring Contracts

    If you want to ignore a contract, you can either set a value of ignored contracts in the +

    9.2.3 Ignoring Contracts

    If you want to ignore a contract, you can either set a value of ignored contracts in the plugin configuration or set the ignored property on the contract itself:

    Groovy DSL. 

    org.springframework.cloud.contract.spec.Contract.make {
     	ignored()
     }

    YAML. 

    ignored: true

    -

    8.2.4 Passing Values from Files

    Starting with version 1.2.0, you can pass values from files. Assume that you have the +

    9.2.4 Passing Values from Files

    Starting with version 1.2.0, you can pass values from files. Assume that you have the following resources in our project.

    └── src
         └── test
             └── resources
    @@ -3948,7 +4053,7 @@ response:
       bodyFromFileAsBytes: response.pdf
       headers:
         Content-Type: application/octet-stream

    -

    [Important]Important

    You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

    8.2.5 HTTP Top-Level Elements

    The following methods can be called in the top-level closure of a contract definition. +

    [Important]Important

    You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.

    9.2.5 HTTP Top-Level Elements

    The following methods can be called in the top-level closure of a contract definition. request and response are mandatory. priority is optional.

    Groovy DSL. 

    org.springframework.cloud.contract.spec.Contract.make {
     	// Definition of HTTP request part of the contract
    @@ -3981,7 +4086,7 @@ response:
     ...

    [Important]Important

    If you want to make your contract have a higher value of priority you need to pass a lower number to the priority tag / method. E.g. priority with -value 5 has higher priority than priority with value 10.

    8.3 Request

    The HTTP protocol requires only method and url to be specified in a request. The +value 5 has higher priority than priority with value 10.

    9.3 Request

    The HTTP protocol requires only method and url to be specified in a request. The same information is mandatory in request definition of the Contract.

    Groovy DSL. 

    org.springframework.cloud.contract.spec.Contract.make {
     	request {
    @@ -4274,7 +4379,7 @@ parametrization of either fileName or "transformers" : [ "response-template", "foo-transformer" ]
       }
     }
    -	'''

    8.4 Response

    The response must contain an HTTP status code and may contain other information. The + '''

    9.4 Response

    The response must contain an HTTP status code and may contain other information. The following code shows an example:

    Groovy DSL. 

    org.springframework.cloud.contract.spec.Contract.make {
     	request {
    @@ -4295,13 +4400,13 @@ status: 200

    Besides status, the response may contain headers, cookies and a body, both of which are specified the same way as in the request (see the previous paragraph).

    [Tip]Tip

    Via the Groovy DSL you can reference the org.springframework.cloud.contract.spec.internal.HttpStatus methods to provide a meaningful status instead of a digit. E.g. you can call -OK() for a status 200 or BAD_REQUEST() for 400.

    8.5 Dynamic properties

    The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +OK() for a status 200 or BAD_REQUEST() for 400.

    9.5 Dynamic properties

    The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not want to force the consumers to stub their clocks to always return the same value of time so that it gets matched by the stub.

    For Groovy DSL you can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in a separate section called bodyMatchers.

    [Note]Note

    Before 2.0.0 these were set using testMatchers and stubMatchers, -check out the migration guide for more information.

    For YAML you can only use the matchers section.

    8.5.1 Dynamic properties inside the body

    [Important]Important

    This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can set the properties inside the body either with the value method or, if you use +check out the migration guide for more information.

    For YAML you can only use the matchers section.

    9.5.1 Dynamic properties inside the body

    [Important]Important

    This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can set the properties inside the body either with the value method or, if you use the Groovy map notation, with $(). The following example shows how to set dynamic properties with the value method:

    value(consumer(...), producer(...))
     value(c(...), p(...))
    @@ -4310,8 +4415,8 @@ value(client(...), server(...))

    The following example shows how to set d $(c(...), p(...)) $(stub(...), test(...)) $(client(...), server(...))

    Both approaches work equally well. stub and client methods are aliases over the consumer -method. Subsequent sections take a closer look at what you can do with those values.

    8.5.2 Regular expressions

    [Important]Important

    This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can use regular expressions to write your requests in Contract DSL. Doing so is +method. Subsequent sections take a closer look at what you can do with those values.

    9.5.2 Regular expressions

    [Important]Important

    This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can use regular expressions to write your requests in Contract DSL. Doing so is particularly useful when you want to indicate that a given response should be provided for requests that follow a given pattern. Also, you can use regular expressions when you need to use patterns and not exact values both for your test and your server side tests.

    The following example shows how to use regular expressions to write a request:

    org.springframework.cloud.contract.spec.Contract.make {
    @@ -4561,8 +4666,8 @@ T anyOf(String... values)

    and this is an example of how you can referenc anyOf : $(anyOf('foo', 'bar')) ]) } -}

    8.5.3 Passing Optional Parameters

    [Important]Important

    This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    It is possible to provide optional parameters in your contract. However, you can provide +}

    9.5.3 Passing Optional Parameters

    [Important]Important

    This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    It is possible to provide optional parameters in your contract. However, you can provide optional parameters only for the following:

    • STUB side of the Request
    • TEST side of the Response

    The following example shows how to provide optional parameters:

    org.springframework.cloud.contract.spec.Contract.make {
     	priority 1
     	request {
    @@ -4627,8 +4732,8 @@ expression that must be present 0 or more times.

    If you use Spock for, the }, "priority" : 1 } -'''

    8.5.4 Executing Custom Methods on the Server Side

    [Important]Important

    This section is valid only for Groovy DSL. Check out the -Section 8.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can define a method call that executes on the server side during the test. Such a +'''

    9.5.4 Executing Custom Methods on the Server Side

    [Important]Important

    This section is valid only for Groovy DSL. Check out the +Section 9.5.7, “Dynamic Properties in the Matchers Sections” section for YAML examples of a similar feature.

    You can define a method call that executes on the server side during the test. Such a method can be added to the class defined as "baseClassForTests" in the configuration. The following code shows an example of the contract portion of the test case:

    org.springframework.cloud.contract.spec.Contract.make {
     	request {
    @@ -4691,7 +4796,7 @@ It should resemble the following code:

    "/something");
     
     // then:
    - assertThat(response.statusCode()).isEqualTo(200);

    8.5.5 Referencing the Request from the Response

    The best situation is to provide fixed values, but sometimes you need to reference a + assertThat(response.statusCode()).isEqualTo(200);

    9.5.5 Referencing the Request from the Response

    The best situation is to provide fixed values, but sometimes you need to reference a request in your response.

    If you’re writing contracts using Groovy DSL, you can use the fromRequest() method, which lets you reference a bunch of elements from the HTTP request. You can use the following options:

    • fromRequest().url(): Returns the request URL and query parameters.
    • fromRequest().query(String key): Returns the first query parameter with a given name.
    • fromRequest().query(String key, int index): Returns the nth query parameter with a @@ -4805,7 +4910,7 @@ in sending the following response body:

      }
      [Important]Important

      This feature works only with WireMock having a version greater than or equal to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’s response-template response transformer. It uses Handlebars to convert the Mustache {{{ }}} templates into -proper values. Additionally, it registers two helper functions:

      • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
      • jsonpath: For a given parameter, find an object in the request body.

    8.5.6 Registering Your Own WireMock Extension

    WireMock lets you register custom extensions. By default, Spring Cloud Contract registers +proper values. Additionally, it registers two helper functions:

    • escapejsonbody: Escapes the request body in a format that can be embedded in a JSON.
    • jsonpath: For a given parameter, find an object in the request body.

    9.5.6 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. @@ -4855,7 +4960,7 @@ org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter

    [Important]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.

    8.5.7 Dynamic Properties in the Matchers Sections

    If you work with Pact, the following discussion may seem familiar. +want the transformation to be applied only for a mapping that explicitly requires it.

    9.5.7 Dynamic Properties in the Matchers Sections

    If you work with Pact, the following discussion may seem familiar. Quite a few users are used to having a separation between the body and setting the dynamic parts of a contract.

    You can use the bodyMatchers section for two reasons:

    • Define the dynamic values that should end up in a stub. You can set it in the request or inputMessage part of your contract.
    • Verify the result of your test. @@ -5365,7 +5470,7 @@ and: assertThat(parsedJson.read("\$.events[0].eventId", String.class)).matches("^([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\$") assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+")

      As you can see, the assertion is malformed. Only the first element of the array got asserted. In order to fix this, you should apply the assertion to the whole $.events -collection and assert it with the byCommand(…​) method.

    8.6 JAX-RS Support

    The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +collection and assert it with the byCommand(…​) method.

    9.6 JAX-RS Support

    The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs to define protected WebTarget webTarget and server initialization. The only option for testing JAX-RS API is to start a web server. Also, a request with a body needs to have a content type set. Otherwise, the default of application/octet-stream gets used.

    In order to use JAX-RS mode, use the following settings:

    testMode == 'JAXRSCLIENT'

    The following example shows a generated test API:

    					'''
    @@ -5390,7 +5495,7 @@ content type set. Otherwise, the default of application/oc
      // and:
       DocumentContext parsedJson = JsonPath.parse(responseAsString);
       assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
    -'''

    8.7 Async Support

    If you’re using asynchronous communication on the server side (your controllers are +'''

    9.7 Async Support

    If you’re using asynchronous communication on the server side (your controllers are returning Callable, DeferredResult, and so on), then, inside your contract, you must provide an async() method in the response section. The following code shows an example:

    Groovy DSL. 

    org.springframework.cloud.contract.spec.Contract.make {
    @@ -5422,7 +5527,7 @@ provide an async() method in the response:
         fixedDelayMilliseconds: 1000

    -

    8.8 Working with Context Paths

    Spring Cloud Contract supports context paths.

    [Important]Important

    The only change needed to fully support context paths is the switch on the +

    9.8 Working with Context Paths

    Spring Cloud Contract supports context paths.

    [Important]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.

    Maven.  @@ -5466,7 +5571,7 @@ socket.

    Consider the following contract:

    or
     	}
     }

    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).

    8.9 Working with WebFlux

    Spring Cloud Contract offers two ways of working with WebFlux.

    8.9.1 WebFlux with WebTestClient

    One of them is via the WebTestClient mode.

    Maven.  +that information (for example, in the stubs, you have to call /my-context-path/url).

    9.9 Working with WebFlux

    Spring Cloud Contract offers two ways of working with WebFlux.

    9.9.1 WebFlux with WebTestClient

    One of them is via the WebTestClient mode.

    Maven. 

    <plugin>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    @@ -5492,7 +5597,7 @@ for WebFlux:

    new ProducerController(personToCheck -> personToCheck.age >= 20));
     	}
     }
    -}

    8.9.2 WebFlux with Explicit mode

    Another way is with the EXPLICIT mode in your generated tests +}

    9.9.2 WebFlux with Explicit mode

    Another way is with the EXPLICIT mode in your generated tests to work with WebFlux.

    Maven. 

    <plugin>
         <groupId>org.springframework.cloud</groupId>
    @@ -5531,7 +5636,7 @@ to work with WebFlux.

    Maven.  } } -}

    8.10 XML Support for REST

    For REST contracts, we also support XML request and response body. +}

    9.10 XML Support for REST

    For REST contracts, we also support XML request and response body. The XML body has to be passed within the body element as a String or GString. Also body matchers can be provided for both request and response. In place of the jsonPath(…​) method, the org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath @@ -5605,8 +5710,8 @@ and the appropriate MatchingType as second. All the assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*"); assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo"); assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype"); - }

    8.11 Messaging Top-Level Elements

    The DSL for messaging looks a little bit different than the one that focuses on HTTP. The -following sections explain the differences:

    8.11.1 Output Triggered by a Method

    The output message can be triggered by calling a method (such as a Scheduler when a was + }

    9.11 Messaging Top-Level Elements

    The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences:

    9.11.1 Output Triggered by a Method

    The output message can be triggered by calling a method (such as a Scheduler when a was started and a message was sent), as shown in the following example:

    Groovy DSL. 

    def dsl = Contract.make {
     	// Human readable description
    @@ -5651,7 +5756,7 @@ outputMessage:
     

    In the previous example case, the output message is sent to output if a method called bookReturnedTriggered is executed. On the message publisher’s side, we generate a test that calls that method to trigger the message. On the consumer side, you can use -the some_label to trigger the message.

    8.11.2 Output Triggered by a Message

    The output message can be triggered by receiving a message, as shown in the following +the some_label to trigger the message.

    9.11.2 Output Triggered by a Message

    The output message can be triggered by receiving a message, as shown in the following example:

    Groovy DSL. 

    def dsl = Contract.make {
     	description 'Some Description'
    @@ -5707,7 +5812,7 @@ outputMessage:
     received on the input destination. On the message publisher’s side, the engine
     generates a test that sends the input message to the defined destination. On the
     consumer side, you can either send a message to the input destination or use a label
    -(some_label in the example) to trigger the message.

    8.11.3 Consumer/Producer

    [Important]Important

    This section is valid only for Groovy DSL.

    In HTTP, you have a notion of client/stub and `server/test notation. You can also +(some_label in the example) to trigger the message.

    9.11.3 Consumer/Producer

    [Important]Important

    This section is valid only for Groovy DSL.

    In HTTP, you have a notion of client/stub and `server/test notation. You can also use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also provides the consumer and producer methods, as presented in the following example (note that you can use either $ or value methods to provide consumer and producer @@ -5728,10 +5833,10 @@ parts):

    					Contract.make {
     									bookName: 'foo'
     							])
     						}
    -					}

    8.11.4 Common

    In the input or outputMessage section you can call assertThat with the name + }

    9.11.4 Common

    In the input or outputMessage section you can call assertThat with the name of a method (e.g. assertThatMessageIsOnTheQueue()) that you have defined in the base class or in a static import. Spring Cloud Contract will execute that method -in the generated test.

    8.12 Multiple Contracts in One File

    You can define multiple contracts in one file. Such a contract might resemble the +in the generated test.

    9.12 Multiple Contracts in One File

    You can define multiple contracts in one file. Such a contract might resemble the following example:

    Groovy DSL. 

    import org.springframework.cloud.contract.spec.Contract
     
    @@ -5825,7 +5930,7 @@ index of the contract in the list.

    The generated stubs is shown in the fol 1_WithList.json

    As you can see, the first file got the name parameter from the contract. The second got the name of the contract file (WithList.groovy) prefixed with the index (in this case, the contract had an index of 1 in the list of contracts in the file).

    [Tip]Tip

    As you can see, it is much better if you name your contracts because doing so makes -your tests far more meaningful.

    8.13 Generating Spring REST Docs snippets from the contracts

    When you want to include the requests and responses of your API using Spring REST Docs, +your tests far more meaningful.

    9.13 Generating Spring REST Docs snippets from the contracts

    When you want to include the requests and responses of your API using Spring REST Docs, you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc. Simply include the following dependencies if you haven’t already.

    Maven. 

    <dependency>
    @@ -5919,10 +6024,10 @@ testCompile 'org
     						getClass().getSimpleName() + "_" + testName.getMethodName())));
     	}
     
    -}
    [Tip]Tip

    You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

    9. Customization

    [Important]Important

    This section is valid only for Groovy DSL

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

    9.1 Extending the DSL

    You can provide your own functions to the DSL. The key requirement for this feature is to +}

    [Tip]Tip

    You don’t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.

    10. Customization

    [Important]Important

    This section is valid only for Groovy DSL

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

    10.1 Extending the DSL

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

    • Creating a JAR with reusable classes.
    • Referencing of these classes in the DSLs.

    You can find the full example -here.

    9.1.1 Common JAR

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

    PatternUtils contains functions used by both the consumer and the producer.

    package com.example;
    +here.

    10.1.1 Common JAR

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

    PatternUtils contains functions used by both the consumer and the producer.

    package com.example;
     
     import java.util.regex.Pattern;
     
    @@ -6053,8 +6158,8 @@ maintain the static compatibility. Later in this document, you can see examples
     		return new ServerDslProperty( PatternUtils.ok(), "OK");
     	}
     }
    -//end::impl[]

    9.1.2 Adding the Dependency to the Project

    In order for the plugins and IDE to be able to reference the common JAR classes, you need -to pass the dependency to your project.

    9.1.3 Test the Dependency in the Project’s Dependencies

    First, add the common jar dependency as a test dependency. Because your contracts files +//end::impl[]

    10.1.2 Adding the Dependency to the Project

    In order for the plugins and IDE to be able to reference the common JAR classes, you need +to pass the dependency to your project.

    10.1.3 Test the Dependency in the Project’s Dependencies

    First, add the common jar dependency as a test dependency. Because your contracts files are available on the test resources path, the common jar classes automatically become visible in your Groovy files. The following examples show how to test the dependency:

    Maven. 

    <dependency>
    @@ -6065,7 +6170,7 @@ visible in your Groovy files. The following examples show how to test the depend
     </dependency>

    Gradle. 

    testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")

    -

    9.1.4 Test a Dependency in the Plugin’s Dependencies

    Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +

    10.1.4 Test a Dependency in the Plugin’s Dependencies

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

    Maven. 

    <plugin>
     	<groupId>org.springframework.cloud</groupId>
    @@ -6092,7 +6197,7 @@ following example:

    Maven.  </plugin>

    Gradle. 

    classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"

    -

    9.1.5 Referencing classes in DSLs

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

    package contracts.beer.rest
    +

    10.1.5 Referencing classes in DSLs

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

    package contracts.beer.rest
     
     import com.example.ConsumerUtils
     import com.example.ProducerUtils
    @@ -6133,12 +6238,12 @@ then:
     			contentType(applicationJson())
     		}
     	}
    -}
    [Important]Important

    You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

    10. Using the Pluggable Architecture

    You may encounter cases where you have your contracts have been defined in other formats, +}

    [Important]Important

    You can set the Spring Cloud Contract plugin up by setting convertToYaml to true. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.

    11. Using the Pluggable Architecture

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

    10.1 Custom Contract Converter

    The ContractConverter interface lets you register your own implementation of a contract +can generate stubs for other HTTP server implementations).

    11.1 Custom Contract Converter

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

    package org.springframework.cloud.contract.spec
     
     /**
    @@ -6180,7 +6285,7 @@ structure converter. The following code listing shows the 
     conversion. Also, you must define how to perform that conversion in both directions.

    [Important]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:

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

    10.1.1 Pact Converter

    Spring Cloud Contract includes support for Pact representation of +org.springframework.cloud.contract.verifier.converter.YamlContractConverter

    11.1.1 Pact Converter

    Spring Cloud Contract includes support for Pact representation of contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we present how to add Pact support for your project. Note however that not all functionality is supported. Starting with v3 you can combine multiple matcher for the same element; @@ -6190,7 +6295,7 @@ Next to that the request and path matchers are skipped during the conversion. When using a date, time or datetime value generator with a given format, the given format will be skipped and the ISO format will be used.

    In order to properly support the Spring Cloud Contract way of doing messaging with Pact you’ll have to provide some additional meta data entries. Below you can find a list of such entries:

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

    10.1.2 Pact Contract

    Consider following example of a Pact contract, which is a file under the +set a metaData entry in the Pact file, with key sentTo equal to the destination to which a message is to be sent. E.g. "metaData": { "sentTo": "activemq:output" }

    11.1.2 Pact Contract

    Consider following example of a Pact contract, which is a file under the src/test/resources/contracts folder.

    {
       "provider": {
         "name": "Provider"
    @@ -6288,7 +6393,7 @@ set a metaData entry in the Pact file, with key "version": "3.5.13"
         }
       }
    -}

    The remainder of this section about using Pact refers to the preceding file.

    10.1.3 Pact for Producers

    On the producer side, you must add two additional dependencies to your plugin +}

    The remainder of this section about using Pact refers to the preceding file.

    11.1.3 Pact for Producers

    On the producer side, you must add two additional dependencies to your plugin configuration. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use.

    Maven. 

    <plugin>
    @@ -6354,7 +6459,7 @@ test might be as follows:

    "transformers" : [ "response-template" ]
       },
    -}

    10.1.4 Pact for Consumers

    On the consumer side, you must add two additional dependencies to your project +}

    11.1.4 Pact for Consumers

    On the consumer side, you must add two additional dependencies to your project dependencies. One is the Spring Cloud Contract Pact support, and the other represents the current Pact version that you use.

    Maven. 

    <dependency>
    @@ -6364,7 +6469,7 @@ current Pact version that you use.

    Maven.  </dependency>

    Gradle. 

    testCompile "org.springframework.cloud:spring-cloud-contract-pact"

    -

    10.2 Using the Custom Test Generator

    If you want to generate tests for languages other than Java or you are not happy with the +

    11.2 Using the Custom Test Generator

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

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

    package org.springframework.cloud.contract.verifier.builder
     
    @@ -6434,7 +6539,7 @@ trait SingleTestGenerator {
     	}
     }

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

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

    10.3 Using the Custom Stub Generator

    If you want to generate stubs for stub servers other than WireMock, you can plug in your +com.example.MyGenerator

    11.3 Using the Custom Stub Generator

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

    package org.springframework.cloud.contract.verifier.converter
     
    @@ -6477,7 +6582,7 @@ own implementation of the StubGenerator interface.
     example:

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

    The default implementation is the WireMock stub generation.

    [Tip]Tip

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

    10.4 Using the Custom Stub Runner

    If you decide to use a custom stub generation, you also need a custom way of running +DSL, you can produce both WireMock stubs and Pact files.

    11.4 Using the Custom Stub Runner

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

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

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

    package org.springframework.cloud.contract.stubrunner.provider.moco
    @@ -6563,7 +6668,7 @@ HTTP Stub server implementation, which might resemble the following example:

    }

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

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

    Now you can run stubs with Moco.

    [Important]Important

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

    10.5 Using the Custom Stub Downloader

    You can customize the way your stubs are downloaded by creating an implementation of the +implementation is used. If you provide more than one, the first one on the list is used.

    11.5 Using the Custom Stub Downloader

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

    package com.example;
     
     class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
    @@ -6589,19 +6694,19 @@ org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
     com.example.CustomStubDownloaderBuilder

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

    [Important]Important

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

    10.6 Using the SCM Stub Downloader

    Whenever the repositoryRoot starts with a SCM protocol +If you provide more than one, then the first one on the list is used.

    11.6 Using the SCM Stub Downloader

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

    Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader’s behaviour. Below you can find the list of -properties

    Table 10.1. SCM Stub Downloader properties

    Type of a property

    Name of the property

    Description

    * git.branch (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

    master

    Which branch to checkout

    * git.username (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

     

    Git clone username

    * git.password (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

     

    Git clone password

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

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

    * STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

    10

    Number of attempts to push the commits to origin

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

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

    * STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

    1000

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


    10.7 Using the Pact Stub Downloader

    Whenever the repositoryRoot starts with a Pact protocol +properties

    Table 11.1. SCM Stub Downloader properties

    Type of a property

    Name of the property

    Description

    * git.branch (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_BRANCH (env prop)

    master

    Which branch to checkout

    * git.username (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_USERNAME (env prop)

     

    Git clone username

    * git.password (plugin prop)

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

    * STUBRUNNER_PROPERTIES_GIT_PASSWORD (env prop)

     

    Git clone password

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

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

    * STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS (env prop)

    10

    Number of attempts to push the commits to origin

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

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

    * STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS (env prop)

    1000

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


    11.7 Using the Pact Stub Downloader

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

    Either via environment variables, system properties, properties set inside the plugin or contracts repository configuration you can tweak the downloader’s behaviour. Below you can find the list of -properties

    Table 10.2. SCM Stub Downloader properties

    Name of a property

    Default

    Description

    * pactbroker.host (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

    Host from URL passed to repositoryRoot

    What is the URL of Pact Broker

    * pactbroker.port (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

    Port from URL passed to repositoryRoot

    What is the port of Pact Broker

    * pactbroker.protocol (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

    Protocol from URL passed to repositoryRoot

    What is the protocol of Pact Broker

    * pactbroker.tags (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

    Version of the stub, or latest if version is +

    What tags should be used to fetch the stub

    * pactbroker.auth.scheme (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

    Basic

    What kind of authentication should be used to connect to the Pact Broker

    * pactbroker.auth.username (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

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

    Username used to connect to the Pact Broker

    * pactbroker.auth.password (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

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

    Password used to connect to the Pact Broker

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

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

    false

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


    11. Spring Cloud Contract WireMock

    The Spring Cloud Contract WireMock modules let you use WireMock in a +properties

    Table 11.2. SCM Stub Downloader properties

    Name of a property

    Default

    Description

    * pactbroker.host (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_HOST (env prop)

    Host from URL passed to repositoryRoot

    What is the URL of Pact Broker

    * pactbroker.port (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PORT (env prop)

    Port from URL passed to repositoryRoot

    What is the port of Pact Broker

    * pactbroker.protocol (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL (env prop)

    Protocol from URL passed to repositoryRoot

    What is the protocol of Pact Broker

    * pactbroker.tags (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_TAGS (env prop)

    Version of the stub, or latest if version is +

    What tags should be used to fetch the stub

    * pactbroker.auth.scheme (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME (env prop)

    Basic

    What kind of authentication should be used to connect to the Pact Broker

    * pactbroker.auth.username (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME (env prop)

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

    Username used to connect to the Pact Broker

    * pactbroker.auth.password (plugin prop)

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD (env prop)

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

    Password used to connect to the Pact Broker

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

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

    * STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID (env prop)

    false

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


    12. Spring Cloud Contract WireMock

    The Spring Cloud Contract WireMock modules let you use WireMock in a Spring Boot application. Check out the samples for more details.

    If you have a Spring Boot application that uses Tomcat as an embedded server (which is @@ -6639,7 +6744,7 @@ your test. The following code shows an example:

    <
     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.

    11.1 Registering Stubs Automatically

    If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file +having the same context, the same as for Spring integration tests. Also you can inject a bean of type WireMockServer into your test.

    12.1 Registering Stubs Automatically

    If you use @AutoConfigureWireMock, it registers WireMock JSON stubs from the file system or classpath (by default, from file:src/test/resources/mappings). You can customize the locations 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 @@ -6659,7 +6764,7 @@ public class WiremockImportApplicationTests { }

    [Note]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.

    @AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

    11.2 Using Files to Specify the Stub Bodies

    WireMock can read response bodies from files on the classpath or the file system. In that +stubs are stored under /META-INF/group-id/artifact-id/versions/mappings/ folder. If you want to register all stubs from that location, from all embedded JARs, then it’s enough to use the following syntax.

    @AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")

    12.2 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 @@ -6670,7 +6775,7 @@ supported. A list of values can be given, in which case WireMock resolves the fi that exists when it needs to find a response body.

    [Note]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.

    11.3 Alternative: Using JUnit Rules

    For a more conventional WireMock experience, you can use JUnit @Rules to start and stop +effect on the stubs loaded explicitly from the stubs attribute.

    12.3 Alternative: Using JUnit Rules

    For a more conventional WireMock experience, you can use JUnit @Rules to start and stop the server. To do so, use the WireMockSpring convenience class to obtain an Options instance, as shown in the following example:

    @RunWith(SpringRunner.class)
     @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    @@ -6702,7 +6807,7 @@ instance, as shown in the following example:

    The @ClassRule means that the server shuts down after all the methods in this class -have been run.

    11.4 Relaxed SSL Validation for Rest Template

    WireMock lets you stub a "secure" server with an "https" URL protocol. If your +have been run.

    12.4 Relaxed SSL Validation for Rest Template

    WireMock lets you stub a "secure" server with an "https" URL protocol. If your application wants to contact that stub server in an integration test, it will find that the SSL certificates are not valid (the usual problem with self-installed certificates). The best option is often to re-configure the client to use "http". If that’s not an @@ -6729,7 +6834,7 @@ classpath and it is selected by the RestTemplateBuilderjava.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.

    11.5 WireMock and Spring MVC Mocks

    Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +property to false.

    12.5 WireMock and Spring MVC Mocks

    Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a Spring MockRestServiceServer. The following code shows an example:

    @RunWith(SpringRunner.class)
     @SpringBootTest(webEnvironment = WebEnvironment.NONE)
     public class WiremockForDocsMockServerApplicationTests {
    @@ -6761,7 +6866,7 @@ pattern. The JSON format is the normal WireMock format, which you can read about
     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).

    11.6 Customization of WireMock configuration

    You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type +Wiremock dependencies and exclude the Spring Boot container (if there is one).

    12.6 Customization of WireMock configuration

    You can register a bean of org.springframework.cloud.contract.wiremock.WireMockConfigurationCustomizer type in order to customize the WireMock configuration (e.g. add custom transformers). Example:

    		@Bean
     		WireMockConfigurationCustomizer optionsCustomizer() {
    @@ -6771,7 +6876,7 @@ Example:

    		// perform your customization here
     				}
     			};
    -		}

    11.7 Generating Stubs using REST Docs

    Spring REST Docs can be used to generate + }

    12.7 Generating Stubs using REST Docs

    Spring REST Docs can be used to generate documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc or WebTestClient or Rest Assured. At the same time that you generate documentation for your API, you can also generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your @@ -6873,7 +6978,7 @@ 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.

    11.8 Generating Contracts by Using REST Docs

    You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +document.

    12.8 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, @@ -6921,9 +7026,9 @@ Contract.make { } } }

    The generated document (formatted in Asciidoc in this case) contains a formatted -contract. The location of this file would be index/dsl-contract.adoc.

    12. Migrations

    [Tip]Tip

    For up to date migration guides please visit +contract. The location of this file would be index/dsl-contract.adoc.

    13. Migrations

    [Tip]Tip

    For up to date migration guides please visit the project’s wiki page.

    This section covers migrating from one version of Spring Cloud Contract Verifier to the -next version. It covers the following versions upgrade paths:

    12.1 1.0.x → 1.1.x

    This section covers upgrading from version 1.0 to version 1.1.

    12.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 +next version. It covers the following versions upgrade paths:

    13.1 1.0.x → 1.1.x

    This section covers upgrading from version 1.0 to version 1.1.

    13.1.1 New structure of generated stubs

    In 1.1.x we have introduced a change to the structure of generated stubs. If you have been using the @AutoConfigureWireMock notation to use the stubs from the classpath, it no longer works. The following example shows how the @AutoConfigureWireMock notation used to work:

    @AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084)

    You must either change the location of the stubs to: @@ -7001,20 +7106,20 @@ structure presented in the previous snippet.

    Maven.&nbs from "${project.buildDir}/resources/main/customer-stubs/META-INF/${project.group}/${project.name}/${project.version}" into "${project.buildDir}/resources/main/customer-stubs" }

    -

    12.2 1.1.x → 1.2.x

    This section covers upgrading from version 1.1 to version 1.2.

    12.2.1 Custom HttpServerStub

    HttpServerStub includes a method that was not in version 1.1. The method is +

    13.2 1.1.x → 1.2.x

    This section covers upgrading from version 1.1 to version 1.2.

    13.2.1 Custom HttpServerStub

    HttpServerStub includes a method that was not in version 1.1. The method is String registeredMappings() If you have classes that implement HttpServerStub, you now have to implement the registeredMappings() method. It should return a String representing all mappings available in a single HttpServerStub.

    See issue 355 for more -detail.

    12.2.2 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: +detail.

    13.2.2 New packages for generated tests

    The flow for setting the generated tests package name will look like this:

    • Set basePackageForTests
    • If basePackageForTests was not set, pick the package from baseClassForTests
    • If baseClassForTests was not set, pick packageWithBaseClasses
    • If nothing got set, pick the default value: org.springframework.cloud.contract.verifier.tests

    See issue 260 for more -detail.

    12.2.3 New Methods in TemplateProcessor

    In order to add support for fromRequest.path, the following methods had to be added to the +detail.

    13.2.3 New Methods in TemplateProcessor

    In order to add support for fromRequest.path, the following methods had to be added to the TemplateProcessor interface:

    • path()
    • path(int index)

    See issue 388 for more -detail.

    12.2.4 RestAssured 3.0

    Rest Assured, used in the generated test classes, got bumped to 3.0. If +detail.

    13.2.4 RestAssured 3.0

    Rest Assured, used in the generated test classes, got bumped to 3.0. If you manually set versions of Spring Cloud Contract and the release train you might see the following exception:

    Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure:
     [ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist

    This exception will occur due to the fact that the tests got generated with an old version of plugin and at test execution time you have an incompatible -version of the release train (and vice versa).

    Done via issue 267

    12.3 1.2.x → 2.0.x

    13. Links

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

    13.3 1.2.x → 2.0.x

    \ No newline at end of file diff --git a/2.1.x/spring-cloud-contract-maven-plugin/licenses.html b/2.1.x/spring-cloud-contract-maven-plugin/licenses.html index 1f6fbf9aa0..4594afdfb6 100644 --- a/2.1.x/spring-cloud-contract-maven-plugin/licenses.html +++ b/2.1.x/spring-cloud-contract-maven-plugin/licenses.html @@ -340,613 +340,8 @@ implied. See the License for the specific language governing permissions and - limitations under the License.

    [Original text] -

    Copy of the license follows:

    - -
    - -
    - -
    -
    - ApacheCon is Coming 9-12 Sept. 2019 - Las Vegas - The Apache Software Foundation -
    - -
    - Apache Support Logo -
    -
    -
    -

    Apache License, Version 2.0

    - -

    The 2.0 version of the Apache License, approved by the ASF in 2004, helps us achieve our goal of providing -reliable and long-lived software products through collaborative open source software development.

    -

    All packages produced by the ASF are implicitly licensed under the Apache -License, Version 2.0, unless otherwise explicitly stated.

    -
    - -

    -Apache License

    Version 2.0, January 2004

    -http://www.apache.org/licenses/ -

    - -

    TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

    - -

    1. Definitions.

    - -
    - -

    "License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document.

    - -

    "Licensor" shall mean the copyright owner or entity authorized by the -copyright owner that is granting the License.

    - -

    "Legal Entity" shall mean the union of the acting entity and all other -entities that control, are controlled by, or are under common control with -that entity. For the purposes of this definition, "control" means (i) the -power, direct or indirect, to cause the direction or management of such -entity, whether by contract or otherwise, or (ii) ownership of fifty -percent (50%) or more of the outstanding shares, or (iii) beneficial -ownership of such entity.

    - -

    "You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License.

    - -

    "Source" form shall mean the preferred form for making modifications, -including but not limited to software source code, documentation source, -and configuration files.

    - -

    "Object" form shall mean any form resulting from mechanical transformation -or translation of a Source form, including but not limited to compiled -object code, generated documentation, and conversions to other media types.

    - -

    "Work" shall mean the work of authorship, whether in Source or Object form, -made available under the License, as indicated by a copyright notice that -is included in or attached to the work (an example is provided in the -Appendix below).

    - -

    "Derivative Works" shall mean any work, whether in Source or Object form, -that is based on (or derived from) the Work and for which the editorial -revisions, annotations, elaborations, or other modifications represent, as -a whole, an original work of authorship. For the purposes of this License, -Derivative Works shall not include works that remain separable from, or -merely link (or bind by name) to the interfaces of, the Work and Derivative -Works thereof.

    - -

    "Contribution" shall mean any work of authorship, including the original -version of the Work and any modifications or additions to that Work or -Derivative Works thereof, that is intentionally submitted to Licensor for -inclusion in the Work by the copyright owner or by an individual or Legal -Entity authorized to submit on behalf of the copyright owner. For the -purposes of this definition, "submitted" means any form of electronic, -verbal, or written communication sent to the Licensor or its -representatives, including but not limited to communication on electronic -mailing lists, source code control systems, and issue tracking systems that -are managed by, or on behalf of, the Licensor for the purpose of discussing -and improving the Work, but excluding communication that is conspicuously -marked or otherwise designated in writing by the copyright owner as "Not a -Contribution."

    - -

    "Contributor" shall mean Licensor and any individual or Legal Entity on -behalf of whom a Contribution has been received by Licensor and -subsequently incorporated within the Work.

    - -
    - -

    2. Grant of Copyright License. Subject to the -terms and conditions of this License, each Contributor hereby grants to You -a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -copyright license to reproduce, prepare Derivative Works of, publicly -display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form.

    - -

    3. Grant of Patent License. Subject to the terms -and conditions of this License, each Contributor hereby grants to You a -perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except as stated in this section) patent license to make, have made, use, -offer to sell, sell, import, and otherwise transfer the Work, where such -license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by -combination of their Contribution(s) with the Work to which such -Contribution(s) was submitted. If You institute patent litigation against -any entity (including a cross-claim or counterclaim in a lawsuit) alleging -that the Work or a Contribution incorporated within the Work constitutes -direct or contributory patent infringement, then any patent licenses -granted to You under this License for that Work shall terminate as of the -date such litigation is filed.

    - -

    4. Redistribution. You may reproduce and -distribute copies of the Work or Derivative Works thereof in any medium, -with or without modifications, and in Source or Object form, provided that -You meet the following conditions:

    - -
      -
    1. You must give any other recipients of the Work or Derivative Works a -copy of this License; and
    2. - -
    3. You must cause any modified files to carry prominent notices stating -that You changed the files; and
    4. - -
    5. You must retain, in the Source form of any Derivative Works that You -distribute, all copyright, patent, trademark, and attribution notices from -the Source form of the Work, excluding those notices that do not pertain to -any part of the Derivative Works; and
    6. - -
    7. If the Work includes a "NOTICE" text file as part of its distribution, -then any Derivative Works that You distribute must include a readable copy -of the attribution notices contained within such NOTICE file, excluding -those notices that do not pertain to any part of the Derivative Works, in -at least one of the following places: within a NOTICE text file distributed -as part of the Derivative Works; within the Source form or documentation, -if provided along with the Derivative Works; or, within a display generated -by the Derivative Works, if and wherever such third-party notices normally -appear. The contents of the NOTICE file are for informational purposes only -and do not modify the License. You may add Your own attribution notices -within Derivative Works that You distribute, alongside or as an addendum to -the NOTICE text from the Work, provided that such additional attribution -notices cannot be construed as modifying the License. -
      -
      -You may add Your own copyright statement to Your modifications and may -provide additional or different license terms and conditions for use, -reproduction, or distribution of Your modifications, or for any such -Derivative Works as a whole, provided Your use, reproduction, and -distribution of the Work otherwise complies with the conditions stated in -this License. -
    8. - -
    - -

    5. Submission of Contributions. Unless You -explicitly state otherwise, any Contribution intentionally submitted for -inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the -terms of any separate license agreement you may have executed with Licensor -regarding such Contributions.

    - -

    6. Trademarks. This License does not grant -permission to use the trade names, trademarks, service marks, or product -names of the Licensor, except as required for reasonable and customary use -in describing the origin of the Work and reproducing the content of the -NOTICE file.

    - -

    7. Disclaimer of Warranty. Unless required by -applicable law or agreed to in writing, Licensor provides the Work (and -each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT -WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, -without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You -are solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise -of permissions under this License.

    - -

    8. Limitation of Liability. In no event and -under no legal theory, whether in tort (including negligence), contract, or -otherwise, unless required by applicable law (such as deliberate and -grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, -incidental, or consequential damages of any character arising as a result -of this License or out of the use or inability to use the Work (including -but not limited to damages for loss of goodwill, work stoppage, computer -failure or malfunction, or any and all other commercial damages or losses), -even if such Contributor has been advised of the possibility of such -damages.

    - -

    9. Accepting Warranty or Additional Liability. -While redistributing the Work or Derivative Works thereof, You may choose -to offer, and charge a fee for, acceptance of support, warranty, indemnity, -or other liability obligations and/or rights consistent with this License. -However, in accepting such obligations, You may act only on Your own behalf -and on Your sole responsibility, not on behalf of any other Contributor, -and only if You agree to indemnify, defend, and hold each Contributor -harmless for any liability incurred by, or claims asserted against, such -Contributor by reason of your accepting any such warranty or additional -liability.

    - -

    END OF TERMS AND CONDITIONS

    - -
    - -

    How to apply the Apache License to your work

    -

    To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included -on the same "printed page" as the copyright notice for easier -identification within third-party archives.

    -
    Copyright [yyyy] [name of copyright owner]
    -
    -Licensed under the Apache License, Version 2.0 (the "License");
    -you may not use this file except in compliance with the License.
    -You may obtain a copy of the License at
    -
    -    http://www.apache.org/licenses/LICENSE-2.0
    -
    -Unless required by applicable law or agreed to in writing, software
    -distributed under the License is distributed on an "AS IS" BASIS,
    -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -See the License for the specific language governing permissions and
    -limitations under the License.
    -
    - - - - - - - - - - -
    + limitations under the License.

    +

    Can't read the url [https://www.apache.org/licenses/LICENSE-2.0] : connect timed out

    diff --git a/2.1.x/spring-cloud-contract.xml b/2.1.x/spring-cloud-contract.xml index 627fafe9ae..619b30c499 100644 --- a/2.1.x/spring-cloud-contract.xml +++ b/2.1.x/spring-cloud-contract.xml @@ -2603,16 +2603,91 @@ Gradle or a Maven plugin. docs for more information -
    +
    + + Add Gradle Plugin with Dependencies -To add a Gradle plugin with dependencies, use code similar to this: -buildscript { +To add a Gradle plugin with dependencies, you can use code similar to the following: + + +Plugin DSL GA versions + +// build.gradle +plugins { + id "groovy" + // this will work only for GA versions of Spring Cloud Contract + id "org.springframework.cloud.contract" version "${GAVerifierVersion}" +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${GAVerifierVersion}" + } +} + +dependencies { + testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}" + // example with adding Spock core and Spock Spring + testCompile "org.spockframework:spock-core:${spockVersion}" + testCompile "org.spockframework:spock-spring:${spockVersion}" + testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' +} + + + +Plugin DSL non GA versions + +// settings.gradle +pluginManagement { + plugins { + id "org.springframework.cloud.contract" version "${verifierVersion}" + } + repositories { + // to pick from local .m2 + mavenLocal() + // for snapshots + maven { url "https://repo.spring.io/snapshot" } + // for milestones + maven { url "https://repo.spring.io/milestone" } + // for GA versions + gradlePluginPortal() + } +} + +// build.gradle +plugins { + id "groovy" + id "org.springframework.cloud.contract" +} + +dependencyManagement { + imports { + mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifierVersion}" + } +} + +dependencies { + testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}" + // example with adding Spock core and Spock Spring + testCompile "org.spockframework:spock-core:${spockVersion}" + testCompile "org.spockframework:spock-spring:${spockVersion}" + testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' +} + + + +Legacy Plugin Application + +// build.gradle +buildscript { repositories { mavenCentral() } dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}" classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}" + // here you can also pass additional dependencies such as Pact or Kotlin spec e.g.: + // classpath "org.springframework.cloud:spring-cloud-contract-spec-kotlin:${verifier_version}" } } @@ -2626,13 +2701,15 @@ dependencyManagement { } dependencies { - testCompile 'org.codehaus.groovy:groovy-all:2.4.6' + testCompile "org.codehaus.groovy:groovy-all:${groovyVersion}" // example with adding Spock core and Spock Spring - testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' - testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' + testCompile "org.spockframework:spock-core:${spockVersion}" + testCompile "org.spockframework:spock-spring:${spockVersion}" testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' } - + + +
    Gradle and Rest Assured 2.0 By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x @@ -2662,7 +2739,28 @@ and modifies the imports accordingly. Snapshot Versions for Gradle Add the additional snapshot repository to your build.gradle to use snapshot versions, which are automatically uploaded after every successful build, as shown here: -buildscript { +/* + We need to use the [buildscript {}] section when we have to modify + the classpath for the plugins. If that's not the case this section + can be skipped. + + If you don't need to modify the classpath (e.g. add a Pact dependency), + then you can just set the [pluginManagement {}] section in [settings.gradle] file. + + // settings.gradle + pluginManagement { + repositories { + // for snapshots + maven {url "https://repo.spring.io/snapshot"} + // for milestones + maven {url "https://repo.spring.io/milestone"} + // for GA versions + gradlePluginPortal() + } + } + + */ +buildscript { repositories { mavenCentral() mavenLocal() @@ -2979,7 +3077,6 @@ class LoanApplicationServiceSpec extends Specification { LoanApplication makes a call to FraudDetection service. This request is handled by a WireMock server configured with stubs generated by Spring Cloud Contract Verifier.
    -
    Maven Project To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the @@ -4347,7 +4444,28 @@ versions, which are automatically uploaded after every successful build: Gradle -buildscript { +/* + We need to use the [buildscript {}] section when we have to modify + the classpath for the plugins. If that's not the case this section + can be skipped. + + If you don't need to modify the classpath (e.g. add a Pact dependency), + then you can just set the [pluginManagement {}] section in [settings.gradle] file. + + // settings.gradle + pluginManagement { + repositories { + // for snapshots + maven {url "https://repo.spring.io/snapshot"} + // for milestones + maven {url "https://repo.spring.io/milestone"} + // for GA versions + gradlePluginPortal() + } + } + + */ +buildscript { repositories { mavenCentral() mavenLocal()