diff --git a/multi/multi__contract_dsl.html b/multi/multi__contract_dsl.html index a488f4b6e2..9cab6299d4 100644 --- a/multi/multi__contract_dsl.html +++ b/multi/multi__contract_dsl.html @@ -1,6 +1,6 @@ - 8. Contract DSL

8. Contract DSL

[Important]Important

Remember that, inside the contract file, you have to provide the fully + 7. Contract DSL

7. Contract DSL

[Important]Important

Remember that, inside the contract file, you have to provide the fully qualified name to the Contract class and make static imports, such as org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to the Contract class: import org.springframework.cloud.spec.Contract and then call @@ -52,13 +52,13 @@ Cloud Contract Verifier repository.

The following is a complete exampl } }

[Note]Note

The preceding example does not contain all the features of the DSL appear. The remainder of this section describes the other features.

You can compile Contracts to WireMock 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

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

7.2 Common Top-Level elements

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

7.2.1 Description

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

		org.springframework.cloud.contract.spec.Contract.make {
 			description('''
 given:
@@ -68,16 +68,16 @@ when:
 then:
 	Output
 ''')
-		}

8.2.2 Name

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

7.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 generated test not compile. Also, remember that, if you provide the same name for multiple contracts, your autogenerated tests fail to compile and your generated stubs -override each other.

8.2.3 Ignoring Contracts

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

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

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

8.2.4 Passing Values from Files

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

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

Further assume that the JSON files is as follows:

request.json

{ "status" : "REQUEST" }

response.json

{ "status" : "RESPONSE" }

When test or stub generation takes place, the contents of the file is passed to the body of a request or a response. That works because of the file(…​) method. The argument of that method needs to be a file with location relative to the folder in which the contract -lays.

8.2.5 HTTP Top-Level Elements

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

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

org.springframework.cloud.contract.spec.Contract.make {
 	// Definition of HTTP request part of the contract
 	// (this can be a valid request or invalid depending
@@ -125,7 +125,7 @@ lays.

// Contract priority, which can be used for overriding // contracts (1 is highest). Priority is optional. priority 1 -}

8.3 Request

The HTTP protocol requires only method and address to be specified in a request. The +}

7.3 Request

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

org.springframework.cloud.contract.spec.Contract.make {
 	request {
 		// HTTP request method (GET/POST/PUT/DELETE).
@@ -283,7 +283,7 @@ such as named("fileName", "fileContent"), or via a
 	"transformers" : [ "response-template", "foo-transformer" ]
   }
 }
-	'''

8.4 Response

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

7.4 Response

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

org.springframework.cloud.contract.spec.Contract.make {
 	request {
 		//...
@@ -294,11 +294,11 @@ following code shows an example:

org.springframew
 		status 200
 	}
 }

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

8.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +specified the same way as in the request (see the previous paragraph).

7.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. You can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in separate sections called -testMatchers and stubMatchers.

8.5.1 Dynamic properties inside the body

You can set the properties inside the body either with the value method or, if you use +testMatchers and stubMatchers.

7.5.1 Dynamic properties inside the body

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(...))
@@ -307,7 +307,7 @@ 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

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.

7.5.2 Regular expressions

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 {
@@ -453,7 +453,7 @@ String nonBlank() {
 				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
 		)
 	}
-}

8.5.3 Passing Optional Parameters

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

7.5.3 Passing Optional Parameters

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 {
@@ -518,7 +518,7 @@ 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

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

7.5.4 Executing Custom Methods on the Server Side

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 {
@@ -581,7 +581,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);

7.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. To do so, 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 @@ -691,7 +691,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:

7.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. @@ -723,7 +723,7 @@ org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExte } }

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

7.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 two separate sections:

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.

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

'''
@@ -1019,7 +1019,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 +'''

7.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 a sync() method in the response section. The following code shows an example:

org.springframework.cloud.contract.spec.Contract.make {
     request {
@@ -1031,7 +1031,7 @@ provide a sync() method in the 'Passed'
         async()
     }
-}

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 +}

7.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.  @@ -1075,8 +1075,8 @@ 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 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.9.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was +that information (for example, in the stubs, you have to call /my-context-path/url).

7.9 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:

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

def dsl = Contract.make {
 	// Human readable description
 	description 'Some description'
@@ -1101,7 +1101,7 @@ started and a message was sent), as shown in the following example:

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

7.9.2 Output Triggered by a Message

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

def dsl = Contract.make {
 	description 'Some Description'
 	label 'some_label'
@@ -1131,7 +1131,7 @@ example:

def dsl = Contract.make {
 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.9.3 Consumer/Producer

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.

7.9.3 Consumer/Producer

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 @@ -1152,10 +1152,10 @@ parts):

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

8.9.4 Common

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

7.9.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 Pipelines will execute that method -in the genertaed test.

8.10 Multiple Contracts in One File

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

7.10 Multiple Contracts in One File

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

import org.springframework.cloud.contract.spec.Contract
 
 [
@@ -1227,4 +1227,4 @@ 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 iss much better if you name your contracts because doing so makes -your tests far more meaningful.

\ No newline at end of file +your tests far more meaningful.

\ No newline at end of file diff --git a/multi/multi__customization.html b/multi/multi__customization.html index f193132145..36e9b9db44 100644 --- a/multi/multi__customization.html +++ b/multi/multi__customization.html @@ -1,9 +1,9 @@ - 9. Customization

9. Customization

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 + 8. Customization

8. Customization

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

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

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

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

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

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

8.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())
 		}
 	}
-}
\ No newline at end of file +}
\ No newline at end of file diff --git a/multi/multi__links.html b/multi/multi__links.html index f5821a78a6..f5a700fde3 100644 --- a/multi/multi__links.html +++ b/multi/multi__links.html @@ -1,6 +1,6 @@ - 13. Links \ No newline at end of file diff --git a/multi/multi__migrations.html b/multi/multi__migrations.html index 7e5efdbd88..2063895a22 100644 --- a/multi/multi__migrations.html +++ b/multi/multi__migrations.html @@ -1,7 +1,7 @@ - 12. Migrations

12. Migrations

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 + 11. Migrations

11. Migrations

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

11.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

11.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: @@ -79,17 +79,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 +

11.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

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

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

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

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

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

Done via issue 267

\ No newline at end of file diff --git a/multi/multi__spring_cloud_contract_stub_runner.html b/multi/multi__spring_cloud_contract_stub_runner.html index d9b5d5ee77..77789785a9 100644 --- a/multi/multi__spring_cloud_contract_stub_runner.html +++ b/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 + 5. Spring Cloud Contract Stub Runner

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

5.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>
@@ -67,7 +67,7 @@ versions, which are automatically uploaded after every successful build:

"http://repo.spring.io/milestone" } maven { url "http://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 +

5.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 -->
@@ -155,9 +155,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 +

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

If you provide the stubrunner.repositoryRoot or stubrunner.workOffline flag will be set +For messaging, special stub routes are defined.

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

If you provide the stubrunner.repositoryRoot or stubrunner.workOffline flag will be set to true then Stub Runner will connect to the given server and download the required jars. It will then unpack the JAR to a temporary folder and reference those files in further contract processing.

Example:

@AutoConfigureStubRunner(repositoryRoot="http://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095")

Classpath scanning

If you DON’T provide the stubrunner.repositoryRoot and stubrunner.workOffline flag will @@ -218,7 +218,7 @@ structure in your stubs jar.

└──
                 │       └── contract2.groovy
                 └── mappings
                     └── mapping.json

By maintaining this structure classpath gets scanned and you can profit from the messaging / -HTTP stubs without the need to download artifacts.

6.3.2 Running stubs

Limitations

[Important]Important

There might be a problem with StubRunner shutting down ports between tests. You might +HTTP stubs without the need to download artifacts.

5.3.2 Running stubs

Limitations

[Important]Important

There might be a problem with StubRunner shutting down ports between tests. You might have a situation in which you get port conflicts. As long as you use the same context across tests everything works fine. But when the context are different (e.g. different stubs or different profiles) then you have to either use @DirtiesContext to shut down the stub servers, or else run them on @@ -285,7 +285,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

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()
+]

Messaging Stubs

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

5.4 Stub Runner JUnit Rule

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())
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");

After that rule gets executed Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

  • download them
  • cache them locally
  • unzip them to a temporary folder
  • start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port
  • feed the WireMock server with all JSON files that are valid WireMock definitions
  • can also send messages (remember to pass an implementation of MessageVerifier interface)

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. @@ -368,14 +368,14 @@ def 'should outp then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer"); }

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 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 you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule public static StubRunnerRule rule = new StubRunnerRule()
+If you don’t do this then whenever you try to send a message an exception will be thrown.

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

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

5.4.3 Fluent API

When using the StubRunnerRule 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())
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
 		.withPort(12345)
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");

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 +then(rule.findStubUrl("fraudDetectionServer")).isEqualTo(URI.create("http://localhost:12346").toURL());

5.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",
@@ -473,7 +473,7 @@ Below you can find an example of achieving the same result by setting values on
 		"org.springframework.cloud.contract.verifier.stubs:bootService"],
 		repositoryRoot = "classpath:m2repo/repository/")

Stub Runner Spring registers environment variables in the following manner for every registered WireMock server. Example for Stub Runner ids - com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.bar.port

Which you can reference in your code.

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. + com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.bar.port

Which you can reference in your code.

5.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

5.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'
@@ -497,15 +497,15 @@ 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. + }

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

6.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to + merged with the stubbed ones.

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

Spring Cloud CLI

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project for more information.

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

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 (example for running stubs installed locally)

stubrunner.yml.  @@ -514,7 +514,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.

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

5.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
 @SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
 @ActiveProfiles("test")
 class StubRunnerBootSpec extends Specification {
@@ -600,7 +600,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? +}

5.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 @@ -633,7 +633,7 @@ and we want to have the stub runner feature turned on @Aut (4) - we provide a list of artifactId to serviceId mapping

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.

5.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 {
@@ -686,16 +686,16 @@ Or set the test as follows:

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.

5.8 Common

This section briefly describes common properties, including:

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

false

If true, then do not contact any remote repositories to download stubs.

stubrunner.ids

 

Array of Ivy notation stubs to download.

stubrunner.username

 

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

stubrunner.password

 

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

stubrunner.stubsPerConsumer

false

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

stubrunner.consumerName

 

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

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.

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

\ No newline at end of file +ranges here.

\ No newline at end of file diff --git a/multi/multi__spring_cloud_contract_verifier_introduction.html b/multi/multi__spring_cloud_contract_verifier_introduction.html index 7e65d06d49..eb78d3bd8c 100644 --- a/multi/multi__spring_cloud_contract_verifier_introduction.html +++ b/multi/multi__spring_cloud_contract_verifier_introduction.html @@ -1,6 +1,6 @@ - 2. Spring Cloud Contract Verifier Introduction

2. Spring Cloud Contract Verifier Introduction

[Tip]Tip

The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski + 2. Spring Cloud Contract Verifier Introduction

2. Spring Cloud Contract Verifier Introduction

[Tip]Tip

The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski (codearte.io)

Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of JVM-based applications. It moves TDD to the level of software architecture.

Spring Cloud Contract Verifier ships with Contract Definition Language (CDL). Contract definitions are used to produce the following resources:

  • JSON stub definitions to be used by WireMock when doing integration testing on the @@ -446,4 +446,4 @@ achieving the same thing by changing the properties.

    spring-cloud-starter-contract-verifier.

2.6 Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some may be outdated, because the Spring Cloud Contract Verifier project is under constant development.

2.6.1 Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

2.7 Samples

You can find some samples at -samples.

\ No newline at end of file +samples.

\ No newline at end of file diff --git a/multi/multi__spring_cloud_contract_verifier_messaging.html b/multi/multi__spring_cloud_contract_verifier_messaging.html index 9ee04b8bc5..a548ea96a8 100644 --- a/multi/multi__spring_cloud_contract_verifier_messaging.html +++ b/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 uses messaging as a + 4. Spring Cloud Contract Verifier Messaging

4. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that uses messaging as a means of communication. All of the integrations shown in this document work with Spring, -but you can also create one of your own and use that.

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.

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

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

4.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 tests are created. However, there is also a possibility to create Spock tests.

There are 3 main scenarios that we should take into consideration:

  • Scenario 1: There is no input message that produces an output 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

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+jms).

4.3.1 Scenario 1: No Input Message

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		triggeredBy('bookReturnedTriggered()')
@@ -75,7 +75,7 @@ it is resolved as a channel name. For Camel"bookName").isEqualTo("foo")
 
-'''

5.3.2 Scenario 2: Output Triggered by Input

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+'''

4.3.2 Scenario 2: Output Triggered by Input

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		messageFrom('jms:input')
@@ -130,7 +130,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

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+"""

4.3.3 Scenario 3: No Output Message

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		messageFrom('jms:delete')
@@ -167,7 +167,7 @@ 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 +'''

4.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 the Stub Runner Messaging sections.

Maven.  @@ -219,4 +219,4 @@ publishing { } } }

-

\ No newline at end of file +

\ No newline at end of file diff --git a/multi/multi__spring_cloud_contract_verifier_setup.html b/multi/multi__spring_cloud_contract_verifier_setup.html index 9668ba050b..c5cb664a4d 100644 --- a/multi/multi__spring_cloud_contract_verifier_setup.html +++ b/multi/multi__spring_cloud_contract_verifier_setup.html @@ -1,10 +1,10 @@ - 4. Spring Cloud Contract Verifier Setup

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in either of two 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 + 3. Spring Cloud Contract Verifier Setup

3. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in either of two ways

3.1 Gradle Project

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

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

3.1.2 Add Gradle Plugin with Dependencies

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

buildscript {
 	repositories {
 		mavenCentral()
 	}
@@ -29,7 +29,7 @@ dependencies {
 	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 +}

3.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()
@@ -48,7 +48,7 @@ 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, +and modifies the imports accordingly.

3.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()
@@ -57,16 +57,16 @@ which are automatically uploaded after every successful build, as shown here:

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

4.1.5 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +}

3.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 +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

3.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 +tests, invoke the generateContractTests task.

3.1.7 Default Setup

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

contracts {
     targetFramework = 'JUNIT'
     testMode = 'MockMvc'
@@ -110,12 +110,12 @@ publishing {
             artifact verifierStubsJar
         }
     }
-}

4.1.8 Configure Plugin

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

3.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, +}

3.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 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 @@ -143,7 +143,7 @@ closure to set it up. separated. Otherwise, it scans contracts under the provided directory. * contractsWorkOffline: Specifies whether to download the dependencies each time, so that you can work online. In other words, it specifies whether to reuses the local Maven -repo.

4.1.10 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +repo.

3.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 {
 
@@ -162,7 +162,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.

3.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 @@ -181,7 +181,7 @@ 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 Spring Cloud Contract Verifier on the Consumer Side

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

3.1.12 Invoking Generated Tests

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

./gradlew generateContractTests test

3.1.13 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)
@@ -205,8 +205,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.

3.2 Maven Project

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

3.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>
@@ -226,7 +226,7 @@ following sections:

    </configuration> </plugin>

You can read more in the Spring -Cloud Contract Maven Plugin Documentation.

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.

3.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>
@@ -272,7 +272,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.

3.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>
@@ -324,16 +324,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>

3.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 +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

3.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 +anything. If you just want to generate tests, invoke the generateTests goal.

3.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>
@@ -350,7 +350,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>

3.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 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. @@ -380,7 +380,7 @@ closure: URL to a repo with the artifacts that have contracts. I use the current Maven ones.
  • contractRepository - Lets you use a closure where you can define properties related to repository with contracts.
  • username: The user name to be used to connect to the repo.
  • password: The password to be used to connect to the repo.
  • proxyHost: The proxy host to be used to connect to the repo.
  • proxyPort: The proxy port to be used to connect to the repo.
  • cacheDownloadedContracts - Specifies whether to reuse downloaded JARs that contain contract definitions.

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.

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.

3.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
 
@@ -395,7 +395,7 @@ endpoint, which should be verified.

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

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.

3.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 @@ -428,7 +428,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.

3.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>
@@ -458,7 +458,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 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-
+mvn generateTest test.

3.2.11 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
 ...
@@ -495,7 +495,7 @@ goal.

For Groovy Spock code, use the following:

</plugin>
         </plugins>
     </pluginManagement>
-</build>

4.2.12 Spring Cloud Contract Verifier on the Consumer Side

You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use +</build>

3.2.12 Spring Cloud Contract Verifier on the Consumer Side

You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use the plugin so that it only converts the contracts and generates the stubs. To achieve that, you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as you would for a provider. You need to copy contracts stored in @@ -536,7 +536,7 @@ repository.

Here is a sample configuration:

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

4.3 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +Verifier.

3.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
@@ -553,7 +553,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.

3.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, as shown in this example:

my_contracts_dir\
   scenario1\
@@ -561,4 +561,4 @@ requires including an order number followed by an underscore, as shown in this e
     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 -http://wiremock.org/stateful-behaviour.html

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

\ No newline at end of file +http://wiremock.org/stateful-behaviour.html

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

\ No newline at end of file diff --git a/multi/multi__spring_cloud_contract_wiremock.html b/multi/multi__spring_cloud_contract_wiremock.html index 326e85a640..af68c5c433 100644 --- a/multi/multi__spring_cloud_contract_wiremock.html +++ b/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 + 10. Spring Cloud Contract WireMock

10. 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 @@ -30,7 +30,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.

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.

10.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 @@ -49,7 +49,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.

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 +also specify a files root as described in the next section of this document.

10.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 @@ -60,7 +60,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.

10.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 followin example:

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@@ -86,7 +86,7 @@ instance, as shown in the followin 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.

10.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 @@ -112,7 +112,7 @@ annotation or the stub runner. If you use the JUnit @Rule< classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL errors. If you use the default java.net client, you do not need the annotation (but it won’t do any harm). There is no support currently for other clients, but it may be added -in future releases.

11.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +in future releases.

10.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 {
@@ -143,7 +143,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 Generating Stubs using REST Docs

Spring REST Docs can be used to generate +Wiremock dependencies and exclude the Spring Boot container (if there is one).

10.6 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 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 @@ -229,7 +229,7 @@ available on the classpath (by 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.7 Generating Contracts by Using REST Docs

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

10.7 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, @@ -278,4 +278,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/multi/multi__stub_runner_for_messaging.html b/multi/multi__stub_runner_for_messaging.html index cf1354d00c..2a58d918f1 100644 --- a/multi/multi__stub_runner_for_messaging.html +++ b/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 + 6. Stub Runner for Messaging

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

6.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;
@@ -45,10 +45,10 @@ That way the only remaining framework is Spring AMQP.

Map<String, Collection<String>> labels(); }

For convenience, the StubFinder interface extends StubTrigger, so you only need one -or the other in your tests.

StubTrigger gives you the following options to trigger a message:

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:camelService', 'return_book_1')

7.1.3 Trigger by Artifact Ids

stubFinder.trigger('camelService', '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 +or the other in your tests.

StubTrigger gives you the following options to trigger a message:

6.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

6.1.2 Trigger by Group and Artifact Ids

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

6.1.3 Trigger by Artifact Ids

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

6.1.4 Trigger All Messages

stubFinder.trigger()

6.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 automatically downloads the -stubs and registers the required routes.

7.2.1 Adding the Runner to the Project

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

7.2.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.camel.enabled=false +stubs and registers the required routes.

6.2.1 Adding the Runner to the Project

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

6.2.2 Disabling the functionality

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

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

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

You can listen to the output of the message sent to jms:output:

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

The received message passes 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, you can send a message to the jms:output -destination:

camelContext.createProducerTemplate().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 +destination:

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

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

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

6.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
@@ -186,7 +186,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')

6.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 @@ -199,8 +199,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 +

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

6.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
@@ -267,7 +267,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')

6.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 @@ -279,7 +279,7 @@ queues. Bindings connect an exchange to a queue. If message contracts are trigge Spring AMQP stub runner integration looks for bindings on the application context that match this exchange. Then it collects the queues from the Spring exchanges and tries to find message listeners bound to these queues. The message is triggered for all matching -message listeners.

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 +message listeners.

6.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 @@ -351,4 +351,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/multi/multi__using_the_pluggable_architecture.html b/multi/multi__using_the_pluggable_architecture.html index 6879bb1be8..a2eb345370 100644 --- a/multi/multi__using_the_pluggable_architecture.html +++ b/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, + 9. Using the Pluggable Architecture

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

Assume that your contract is written in a YAML file as follows:

request:
+can generate stubs for other HTTP server implementations).

9.1 Custom Contract Converter

Assume that your contract is written in a YAML file as follows:

request:
   url: /foo
   method: PUT
   headers:
@@ -138,9 +138,9 @@ example:

return yamlContract
 		}
 	}
-}

10.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of +}

9.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of contracts. Instead of using the Groovy DSL, you can use Pact files. In this section, we -present how to add Pact support for your project.

10.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the +present how to add Pact support for your project.

9.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"
@@ -194,7 +194,7 @@ present how to add Pact support for your project.

"version": "2.4.18" } } -}

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

10.1.3 Pact for Producers

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

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

9.1.3 Pact for Producers

On the producer side, you mustadd 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>
@@ -264,7 +264,7 @@ test might be as follows:

"Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
     }
   }
-}

10.1.4 Pact for Consumers

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

9.1.4 Pact for Consumers

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

Maven. 

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

Maven. 

Gradle. 

testCompile "org.springframework.cloud:spring-cloud-contract-spec-pact"
 testCompile 'au.com.dius:pact-jvm-model:2.4.18'

-

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 +

9.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
 
@@ -316,7 +316,7 @@ following code listing shows the 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

9.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
 
@@ -358,7 +358,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.

9.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
@@ -441,7 +441,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.

9.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 {
@@ -468,4 +468,4 @@ com.example.CustomStubDownloaderBuilder

Now you can pick a folder with t If you use the repositoryRoot property or the workOffline flag, then an Aether-based implementation that downloads stubs from a remote repository is used. If you do not provide these values, the ClasspathStubProvider (which will scan the classpath) is -used. If you provide more than one, then the first one on the list is used.

\ No newline at end of file +used. If you provide more than one, then the first one on the list is used.

\ No newline at end of file diff --git a/multi/multi_spring-cloud-contract.html b/multi/multi_spring-cloud-contract.html index f3c3707c9f..c5c9c65e4b 100644 --- a/multi/multi_spring-cloud-contract.html +++ b/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. Why a Contract Verifier?
2.1.1. Testing issues
2.2. Purposes
2.3. How It Works
2.3.1. Defining the contract
2.3.2. Client Side
2.3.3. Server Side
2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.4.1. Technical note
2.4.2. Consumer side (Loan Issuance)
2.4.3. Producer side (Fraud Detection server)
2.4.4. Consumer Side (Loan Issuance) Final Step
2.5. Dependencies
2.6. Additional Links
2.6.1. Spring Cloud Contract video
2.6.2. Readings
2.7. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. What is this value(consumer(), producer()) ?
3.3. How to do Stubs versioning?
3.3.1. API Versioning
3.3.2. JAR versioning
3.3.3. Dev or prod stubs
3.4. Common repo with contracts
3.4.1. Repo structure
3.4.2. Workflow
3.4.3. Consumer
3.4.4. Producer
3.5. Can I have multiple base classes for tests?
3.6. How can I debug the request/response being sent by the generated tests client?
3.6.1. How can I debug the mapping/request/response being sent by WireMock?
3.6.2. How can I see what got registered in the HTTP server stub?
3.6.3. Can I reference the request from the response?
3.6.4. 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. 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. Maven Plugin and STS
4.2.12. Spring Cloud Contract Verifier on the Consumer Side
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
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
6.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule
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
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
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 the Runner to the Project
7.2.2. Disabling the functionality
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. Messaging Top-Level Elements
8.9.1. Output Triggered by a Method
8.9.2. Output Triggered by a Message
8.9.3. Consumer/Producer
8.9.4. Common
8.10. Multiple Contracts in One File
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
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. Generating Stubs using REST Docs
11.7. 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
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. Why a Contract Verifier?
2.1.1. Testing issues
2.2. Purposes
2.3. How It Works
2.3.1. Defining the contract
2.3.2. Client Side
2.3.3. Server Side
2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.4.1. Technical note
2.4.2. Consumer side (Loan Issuance)
2.4.3. Producer side (Fraud Detection server)
2.4.4. Consumer Side (Loan Issuance) Final Step
2.5. Dependencies
2.6. Additional Links
2.6.1. Spring Cloud Contract video
2.6.2. Readings
2.7. Samples
3. Spring Cloud Contract Verifier Setup
3.1. Gradle Project
3.1.1. Prerequisites
3.1.2. Add Gradle Plugin with Dependencies
3.1.3. Gradle and Rest Assured 2.0
3.1.4. Snapshot Versions for Gradle
3.1.5. Add stubs
3.1.6. Run the Plugin
3.1.7. Default Setup
3.1.8. Configure Plugin
3.1.9. Configuration Options
3.1.10. Single Base Class for All Tests
3.1.11. Different Base Classes for Contracts
3.1.12. Invoking Generated Tests
3.1.13. Spring Cloud Contract Verifier on the Consumer Side
3.2. Maven Project
3.2.1. Add maven plugin
3.2.2. Maven and Rest Assured 2.0
3.2.3. Snapshot versions for Maven
3.2.4. Add stubs
3.2.5. Run plugin
3.2.6. Configure plugin
3.2.7. Configuration Options
3.2.8. Single Base Class for All Tests
3.2.9. Different base classes for contracts
3.2.10. Invoking generated tests
3.2.11. Maven Plugin and STS
3.2.12. Spring Cloud Contract Verifier on the Consumer Side
3.3. Stubs and Transitive Dependencies
3.4. Scenarios
4. Spring Cloud Contract Verifier Messaging
4.1. Integrations
4.2. Manual Integration Testing
4.3. Publisher-Side Test Generation
4.3.1. Scenario 1: No Input Message
4.3.2. Scenario 2: Output Triggered by Input
4.3.3. Scenario 3: No Output Message
4.4. Consumer Stub Generation
5. Spring Cloud Contract Stub Runner
5.1. Snapshot versions
5.2. Publishing Stubs as JARs
5.3. Stub Runner Core
5.3.1. Retrieving stubs
Stub downloading
Classpath scanning
5.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
5.4. Stub Runner JUnit Rule
5.4.1. Maven settings
5.4.2. Providing fixed ports
5.4.3. Fluent API
5.4.4. Stub Runner with Spring
5.5. Stub Runner Spring Cloud
5.5.1. Stubbing Service Discovery
Test profiles and service discovery
5.5.2. Additional Configuration
5.6. Stub Runner Boot Application
5.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
5.6.2. Endpoints
HTTP
Messaging
5.6.3. Example
5.6.4. Stub Runner Boot with Service Discovery
5.7. Stubs Per Consumer
5.8. Common
5.8.1. Common Properties for JUnit and Spring
5.8.2. Stub Runner Stubs IDs
6. Stub Runner for Messaging
6.1. Stub triggering
6.1.1. Trigger by Label
6.1.2. Trigger by Group and Artifact Ids
6.1.3. Trigger by Artifact Ids
6.1.4. Trigger All Messages
6.2. Stub Runner Camel
6.2.1. Adding the Runner to the Project
6.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.3. Stub Runner Integration
6.3.1. Adding the Runner to the Project
6.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.4. Stub Runner Stream
6.4.1. Adding the Runner to the Project
6.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.5. Stub Runner Spring AMQP
6.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
7. Contract DSL
7.1. Limitations
7.2. Common Top-Level elements
7.2.1. Description
7.2.2. Name
7.2.3. Ignoring Contracts
7.2.4. Passing Values from Files
7.2.5. HTTP Top-Level Elements
7.3. Request
7.4. Response
7.5. Dynamic properties
7.5.1. Dynamic properties inside the body
7.5.2. Regular expressions
7.5.3. Passing Optional Parameters
7.5.4. Executing Custom Methods on the Server Side
7.5.5. Referencing the Request from the Response
7.5.6. Registering Your Own WireMock Extension
7.5.7. Dynamic Properties in the Matchers Sections
7.6. JAX-RS Support
7.7. Async Support
7.8. Working with Context Paths
7.9. Messaging Top-Level Elements
7.9.1. Output Triggered by a Method
7.9.2. Output Triggered by a Message
7.9.3. Consumer/Producer
7.9.4. Common
7.10. Multiple Contracts in One File
8. Customization
8.1. Extending the DSL
8.1.1. Common JAR
8.1.2. Adding the Dependency to the Project
8.1.3. Test the Dependency in the Project’s Dependencies
8.1.4. Test a Dependency in the Plugin’s Dependencies
8.1.5. Referencing classes in DSLs
9. Using the Pluggable Architecture
9.1. Custom Contract Converter
9.1.1. Pact Converter
9.1.2. Pact Contract
9.1.3. Pact for Producers
9.1.4. Pact for Consumers
9.2. Using the Custom Test Generator
9.3. Using the Custom Stub Generator
9.4. Using the Custom Stub Runner
9.5. Using the Custom Stub Downloader
10. Spring Cloud Contract WireMock
10.1. Registering Stubs Automatically
10.2. Using Files to Specify the Stub Bodies
10.3. Alternative: Using JUnit Rules
10.4. Relaxed SSL Validation for Rest Template
10.5. WireMock and Spring MVC Mocks
10.6. Generating Stubs using REST Docs
10.7. Generating Contracts by Using REST Docs
11. Migrations
11.1. 1.0.x → 1.1.x
11.1.1. New structure of generated stubs
11.2. 1.1.x → 1.2.x
11.2.1. Custom HttpServerStub
11.2.2. New packages for generated tests
11.2.3. New Methods in TemplateProcessor
11.2.4. RestAssured 3.0
12. Links
\ No newline at end of file diff --git a/single/spring-cloud-contract.html b/single/spring-cloud-contract.html index 2f311ef685..2289a4caeb 100644 --- a/single/spring-cloud-contract.html +++ b/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. Why a Contract Verifier?
2.1.1. Testing issues
2.2. Purposes
2.3. How It Works
2.3.1. Defining the contract
2.3.2. Client Side
2.3.3. Server Side
2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.4.1. Technical note
2.4.2. Consumer side (Loan Issuance)
2.4.3. Producer side (Fraud Detection server)
2.4.4. Consumer Side (Loan Issuance) Final Step
2.5. Dependencies
2.6. Additional Links
2.6.1. Spring Cloud Contract video
2.6.2. Readings
2.7. Samples
3. Spring Cloud Contract FAQ
3.1. Why use Spring Cloud Contract Verifier and not X ?
3.2. What is this value(consumer(), producer()) ?
3.3. How to do Stubs versioning?
3.3.1. API Versioning
3.3.2. JAR versioning
3.3.3. Dev or prod stubs
3.4. Common repo with contracts
3.4.1. Repo structure
3.4.2. Workflow
3.4.3. Consumer
3.4.4. Producer
3.5. Can I have multiple base classes for tests?
3.6. How can I debug the request/response being sent by the generated tests client?
3.6.1. How can I debug the mapping/request/response being sent by WireMock?
3.6.2. How can I see what got registered in the HTTP server stub?
3.6.3. Can I reference the request from the response?
3.6.4. 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. 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. Maven Plugin and STS
4.2.12. Spring Cloud Contract Verifier on the Consumer Side
4.3. Stubs and Transitive Dependencies
4.4. Scenarios
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
6.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
6.4. Stub Runner JUnit Rule
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
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
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 the Runner to the Project
7.2.2. Disabling the functionality
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. Messaging Top-Level Elements
8.9.1. Output Triggered by a Method
8.9.2. Output Triggered by a Message
8.9.3. Consumer/Producer
8.9.4. Common
8.10. Multiple Contracts in One File
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
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. Generating Stubs using REST Docs
11.7. 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
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. Why a Contract Verifier?
2.1.1. Testing issues
2.2. Purposes
2.3. How It Works
2.3.1. Defining the contract
2.3.2. Client Side
2.3.3. Server Side
2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
2.4.1. Technical note
2.4.2. Consumer side (Loan Issuance)
2.4.3. Producer side (Fraud Detection server)
2.4.4. Consumer Side (Loan Issuance) Final Step
2.5. Dependencies
2.6. Additional Links
2.6.1. Spring Cloud Contract video
2.6.2. Readings
2.7. Samples
3. Spring Cloud Contract Verifier Setup
3.1. Gradle Project
3.1.1. Prerequisites
3.1.2. Add Gradle Plugin with Dependencies
3.1.3. Gradle and Rest Assured 2.0
3.1.4. Snapshot Versions for Gradle
3.1.5. Add stubs
3.1.6. Run the Plugin
3.1.7. Default Setup
3.1.8. Configure Plugin
3.1.9. Configuration Options
3.1.10. Single Base Class for All Tests
3.1.11. Different Base Classes for Contracts
3.1.12. Invoking Generated Tests
3.1.13. Spring Cloud Contract Verifier on the Consumer Side
3.2. Maven Project
3.2.1. Add maven plugin
3.2.2. Maven and Rest Assured 2.0
3.2.3. Snapshot versions for Maven
3.2.4. Add stubs
3.2.5. Run plugin
3.2.6. Configure plugin
3.2.7. Configuration Options
3.2.8. Single Base Class for All Tests
3.2.9. Different base classes for contracts
3.2.10. Invoking generated tests
3.2.11. Maven Plugin and STS
3.2.12. Spring Cloud Contract Verifier on the Consumer Side
3.3. Stubs and Transitive Dependencies
3.4. Scenarios
4. Spring Cloud Contract Verifier Messaging
4.1. Integrations
4.2. Manual Integration Testing
4.3. Publisher-Side Test Generation
4.3.1. Scenario 1: No Input Message
4.3.2. Scenario 2: Output Triggered by Input
4.3.3. Scenario 3: No Output Message
4.4. Consumer Stub Generation
5. Spring Cloud Contract Stub Runner
5.1. Snapshot versions
5.2. Publishing Stubs as JARs
5.3. Stub Runner Core
5.3.1. Retrieving stubs
Stub downloading
Classpath scanning
5.3.2. Running stubs
Limitations
Running using main app
HTTP Stubs
Viewing registered mappings
Messaging Stubs
5.4. Stub Runner JUnit Rule
5.4.1. Maven settings
5.4.2. Providing fixed ports
5.4.3. Fluent API
5.4.4. Stub Runner with Spring
5.5. Stub Runner Spring Cloud
5.5.1. Stubbing Service Discovery
Test profiles and service discovery
5.5.2. Additional Configuration
5.6. Stub Runner Boot Application
5.6.1. How to use it?
Stub Runner Server
Spring Cloud CLI
5.6.2. Endpoints
HTTP
Messaging
5.6.3. Example
5.6.4. Stub Runner Boot with Service Discovery
5.7. Stubs Per Consumer
5.8. Common
5.8.1. Common Properties for JUnit and Spring
5.8.2. Stub Runner Stubs IDs
6. Stub Runner for Messaging
6.1. Stub triggering
6.1.1. Trigger by Label
6.1.2. Trigger by Group and Artifact Ids
6.1.3. Trigger by Artifact Ids
6.1.4. Trigger All Messages
6.2. Stub Runner Camel
6.2.1. Adding the Runner to the Project
6.2.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.3. Stub Runner Integration
6.3.1. Adding the Runner to the Project
6.3.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.4. Stub Runner Stream
6.4.1. Adding the Runner to the Project
6.4.2. Disabling the functionality
Scenario 1 (no input message)
Scenario 2 (output triggered by input)
Scenario 3 (input with no output)
6.5. Stub Runner Spring AMQP
6.5.1. Adding the Runner to the Project
Triggering the message
Spring AMQP Test Configuration
7. Contract DSL
7.1. Limitations
7.2. Common Top-Level elements
7.2.1. Description
7.2.2. Name
7.2.3. Ignoring Contracts
7.2.4. Passing Values from Files
7.2.5. HTTP Top-Level Elements
7.3. Request
7.4. Response
7.5. Dynamic properties
7.5.1. Dynamic properties inside the body
7.5.2. Regular expressions
7.5.3. Passing Optional Parameters
7.5.4. Executing Custom Methods on the Server Side
7.5.5. Referencing the Request from the Response
7.5.6. Registering Your Own WireMock Extension
7.5.7. Dynamic Properties in the Matchers Sections
7.6. JAX-RS Support
7.7. Async Support
7.8. Working with Context Paths
7.9. Messaging Top-Level Elements
7.9.1. Output Triggered by a Method
7.9.2. Output Triggered by a Message
7.9.3. Consumer/Producer
7.9.4. Common
7.10. Multiple Contracts in One File
8. Customization
8.1. Extending the DSL
8.1.1. Common JAR
8.1.2. Adding the Dependency to the Project
8.1.3. Test the Dependency in the Project’s Dependencies
8.1.4. Test a Dependency in the Plugin’s Dependencies
8.1.5. Referencing classes in DSLs
9. Using the Pluggable Architecture
9.1. Custom Contract Converter
9.1.1. Pact Converter
9.1.2. Pact Contract
9.1.3. Pact for Producers
9.1.4. Pact for Consumers
9.2. Using the Custom Test Generator
9.3. Using the Custom Stub Generator
9.4. Using the Custom Stub Runner
9.5. Using the Custom Stub Downloader
10. Spring Cloud Contract WireMock
10.1. Registering Stubs Automatically
10.2. Using Files to Specify the Stub Bodies
10.3. Alternative: Using JUnit Rules
10.4. Relaxed SSL Validation for Rest Template
10.5. WireMock and Spring MVC Mocks
10.6. Generating Stubs using REST Docs
10.7. Generating Contracts by Using REST Docs
11. Migrations
11.1. 1.0.x → 1.1.x
11.1.1. New structure of generated stubs
11.2. 1.1.x → 1.2.x
11.2.1. Custom HttpServerStub
11.2.2. New packages for generated tests
11.2.3. New Methods in TemplateProcessor
11.2.4. RestAssured 3.0
12. 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

1.2.0.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), @@ -451,309 +451,11 @@ achieving the same thing by changing the properties.

spring-cloud-starter-contract-verifier.

2.6 Additional Links

Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some may be outdated, because the Spring Cloud Contract Verifier project is under constant development.

2.6.1 Spring Cloud Contract video

You can check out the video from the Warsaw JUG about Spring Cloud Contract:

2.7 Samples

You can find some samples at -samples.

3. Spring Cloud Contract FAQ

3.1 Why use Spring Cloud Contract Verifier and not X ?

For the time being Spring Cloud Contract Verifier is a JVM based tool. So it could be your first pick when you’re already creating -software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make -Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:

  • Possibility to do CDC with messaging
  • Clear and easy to use, statically typed DSL
  • Possibility to copy paste your current JSON file to the contract and only edit its elements
  • Automatic generation of tests from the defined Contract
  • Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory
  • Spring Cloud integration - no discovery service is needed for integration tests

3.2 What is this value(consumer(), producer()) ?

One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. -What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. -Imagine the following JSON request

{
-    "time" : "2016-10-10 20:10:15",
-    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
-    "body" : "foo"
-}

and JSON response

{
-    "time" : "2016-10-10 21:10:15",
-    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
-    "body" : "bar"
-}

Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the -database) by changing the clock in the system or providing stub implementations of data providers. The same is related -to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​

So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system -will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned -JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words -you would like the stub to work like this:

{
-    "time" : "SOMETHING THAT MATCHES TIME",
-    "id" : "SOMETHING THAT MATCHES UUID",
-    "body" : "foo"
-}

As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid

{
-    "time" : "2016-10-10 21:10:15",
-    "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
-    "body" : "bar"
-}

As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks -much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. -So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the -producer’s backend can work on. Such a JSON would be a valid one:

{
-    "time" : "2016-10-10 20:10:15",
-    "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
-    "body" : "foo"
-}

On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to -contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d -have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side -what you might want is the following response:

{
-    "time" : "SOMETHING THAT MATCHES TIME",
-    "id" : "SOMETHING THAT MATCHES UUID",
-    "body" : "bar"
-}

How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? -In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both -sides of the communication. You can pass the values:

Either via the value method

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

or using the $() method

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

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

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. -Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). -Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

[Tip]Tip

If on one side you have passed the regular expression and you haven’t passed the other, then the -other side will get auto-generated.

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression -for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example):

org.springframework.cloud.contract.spec.Contract.make {
-				request {
-					method 'GET'
-					url '/someUrl'
-					body([
-					    time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
-					    id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
-					    body: "foo"
-					])
-				}
-			response {
-				status 200
-				body([
-					    time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
-					    id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
-					    body: "bar"
-					])
-			}
-}
[Important]Important

Please read the Groovy docs related to JSON to understand how to -properly structure the request / response bodies.

3.3 How to do Stubs versioning?

3.3.1 API Versioning

Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are -different approaches.

  • use Hypermedia, links and do not version your API by any means
  • pass versions through headers / urls

I will not try to answer a question which approach is better. Whatever suit your needs and allows you to generate -business value should be picked.

Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. -You can create a subfolder for every version or append it to th contract name - whatever suits you more.

3.3.2 JAR versioning

If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.

Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of -the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version -looks like this (it got built on the 20.10.2016 at 20:15:21) :

1.0.0.20161020-201521-RELEASE

In that case your generated stub jar will look like this.

1.0.0.20161020-201521-RELEASE-stubs.jar

In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the - latest version of the stubs. You can do that by passing the + sign. Example

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar -version. Example for 2.1.1.

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})

3.3.3 Dev or prod stubs

You can manipulate the classifier to run the tests against current development version of the stubs of other services - or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier - once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.

Example of tests using development version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})

Example of tests using production version of stubs

@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})

You can pass those values also via properties from your deployment pipeline.

3.4 Common repo with contracts

Another way of storing contracts other than having them with the producer is keeping them in a common place. -It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep -contracts in a single place then you, as a producer, will know how many consumers you have and which -consumer will you break with your local changes.

3.4.1 Repo structure

Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, -client2, client3. Then in the repository with common contracts you would have the following setup -(which you can checkout here:

├── com
-│   └── example
-│       └── server
-│           ├── client1
-│           │   └── expectation.groovy
-│           ├── client2
-│           │   └── expectation.groovy
-│           ├── client3
-│           │   └── expectation.groovy
-│           └── pom.xml
-├── mvnw
-├── mvnw.cmd
-├── pom.xml
-└── src
-    └── assembly
-        └── contracts.xml

As you can see the under the slash-delimited groupid / artifact id folder (com/example/server) you have -expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL -contract files as described throughout this documentation. This repository has to produce a JAR file that maps -one to one to the contents of the repo.

Example of a pom.xml inside the server folder.

<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-	<modelVersion>4.0.0</modelVersion>
-
-	<groupId>com.example</groupId>
-	<artifactId>server</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-
-	<name>Server Stubs</name>
-	<description>POM used to install locally stubs for consumer side</description>
-
-	<parent>
-		<groupId>org.springframework.boot</groupId>
-		<artifactId>spring-boot-starter-parent</artifactId>
-		<version>1.5.4.RELEASE</version>
-		<relativePath />
-	</parent>
-
-	<properties>
-		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-		<java.version>1.8</java.version>
-		<spring-cloud-contract.version>1.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
-		<spring-cloud-dependencies.version>Edgware.BUILD-SNAPSHOT</spring-cloud-dependencies.version>
-		<excludeBuildFolders>true</excludeBuildFolders>
-	</properties>
-
-	<dependencyManagement>
-		<dependencies>
-			<dependency>
-				<groupId>org.springframework.cloud</groupId>
-				<artifactId>spring-cloud-dependencies</artifactId>
-				<version>${spring-cloud-dependencies.version}</version>
-				<type>pom</type>
-				<scope>import</scope>
-			</dependency>
-		</dependencies>
-	</dependencyManagement>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.springframework.cloud</groupId>
-				<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-				<version>${spring-cloud-contract.version}</version>
-				<extensions>true</extensions>
-				<configuration>
-					<!-- By default it would search under src/test/resources/ -->
-					<contractsDirectory>${project.basedir}</contractsDirectory>
-				</configuration>
-			</plugin>
-		</plugins>
-	</build>
-
-	<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>
-
-</project>

As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. -Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install - stubs of the producer project.

The pom.xml in the root folder can look like this:

<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-	<modelVersion>4.0.0</modelVersion>
-
-	<groupId>com.example.standalone</groupId>
-	<artifactId>contracts</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-
-	<name>Contracts</name>
-	<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the producers to generate tests and stubs</description>
-
-	<properties>
-		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-	</properties>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.apache.maven.plugins</groupId>
-				<artifactId>maven-assembly-plugin</artifactId>
-				<executions>
-					<execution>
-						<id>contracts</id>
-						<phase>prepare-package</phase>
-						<goals>
-							<goal>single</goal>
-						</goals>
-						<configuration>
-							<attach>true</attach>
-							<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
-							<!-- If you want an explicit classifier remove the following line -->
-							<appendAssemblyId>false</appendAssemblyId>
-						</configuration>
-					</execution>
-				</executions>
-			</plugin>
-		</plugins>
-	</build>
-
-</project>

It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
-		  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
-	<id>project</id>
-	<formats>
-		<format>jar</format>
-	</formats>
-	<includeBaseDirectory>false</includeBaseDirectory>
-	<fileSets>
-		<fileSet>
-			<directory>${project.basedir}</directory>
-			<outputDirectory>/</outputDirectory>
-			<useDefaultExcludes>true</useDefaultExcludes>
-			<excludes>
-				<exclude>**/${project.build.directory}/**</exclude>
-				<exclude>mvnw</exclude>
-				<exclude>mvnw.cmd</exclude>
-				<exclude>.mvn/**</exclude>
-				<exclude>src/**</exclude>
-			</excludes>
-		</fileSet>
-	</fileSets>
-</assembly>

3.4.2 Workflow

The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference - is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on - common contracts in a common repository.

3.4.3 Consumer

When the consumer wants to work on the contracts offline, instead of cloning the producer code, the -consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) -and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts.

[Tip]Tip

You need to have Maven installed locally

3.4.4 Producer

As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency -of the JAR containing the contracts:

<plugin>
-	<groupId>org.springframework.cloud</groupId>
-	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
-	<configuration>
-		<contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
-		<contractDependency>
-			<groupId>com.example.standalone</groupId>
-			<artifactId>contracts</artifactId>
-		</contractDependency>
-	</configuration>
-</plugin>

With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded -from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder -and contracts present under the com/example/server will be picked as the ones used to generate the -tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken -when some incompatible changes are done.

The rest of the flow looks the same.

3.5 Can I have multiple base classes for tests?

Yes! Check out the Different base classes for contracts sections -of either Gradle or Maven plugins.

3.6 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.6.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.6.2 How can I see what got registered in the HTTP server stub?

You can use the mappingsOutputFolder property on @AutoConfigureStubRunner or StubRunnerRule -to dump all mappings per artifact id. Also the port at which the given stub server was -started will be attached.

3.6.3 Can I reference the request from the response?

Yes! With version 1.1.0 we’ve added such a possibility. On the HTTP stub server side we’re providing support -for this for WireMock. In case of other HTTP server stubs you’ll have to implement the approach yourself.

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

4. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in either of two ways

3. Spring Cloud Contract Verifier Setup

You can set up Spring Cloud Contract Verifier in either of two ways

3.1 Gradle Project

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

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

3.1.2 Add Gradle Plugin with Dependencies

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

buildscript {
 	repositories {
 		mavenCentral()
 	}
@@ -778,7 +480,7 @@ dependencies {
 	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 +}

3.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()
@@ -797,7 +499,7 @@ 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, +and modifies the imports accordingly.

3.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()
@@ -806,16 +508,16 @@ which are automatically uploaded after every successful build, as shown here:

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

4.1.5 Add stubs

By default, Spring Cloud Contract Verifier is looking for stubs in the +}

3.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 +with two methods:

  • shouldCreateUser()
  • shouldReturnUser()

3.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 +tests, invoke the generateContractTests task.

3.1.7 Default Setup

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

contracts {
     targetFramework = 'JUNIT'
     testMode = 'MockMvc'
@@ -859,12 +561,12 @@ publishing {
             artifact verifierStubsJar
         }
     }
-}

4.1.8 Configure Plugin

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

3.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, +}

3.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 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 @@ -892,7 +594,7 @@ closure to set it up. separated. Otherwise, it scans contracts under the provided directory. * contractsWorkOffline: Specifies whether to download the dependencies each time, so that you can work online. In other words, it specifies whether to reuses the local Maven -repo.

4.1.10 Single Base Class for All Tests

When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +repo.

3.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 {
 
@@ -911,7 +613,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.

3.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 @@ -930,7 +632,7 @@ 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 Spring Cloud Contract Verifier on the Consumer Side

In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +com.example.ComBase, whereas the rest of the tests extend com.example.FooBase.

3.1.12 Invoking Generated Tests

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

./gradlew generateContractTests test

3.1.13 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)
@@ -954,8 +656,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.

3.2 Maven Project

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

3.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>
@@ -975,7 +677,7 @@ following sections:

    </configuration> </plugin>

You can read more in the Spring -Cloud Contract Maven Plugin Documentation.

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.

3.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>
@@ -1021,7 +723,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.

3.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>
@@ -1073,16 +775,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>

3.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 +with two methods

  • shouldCreateUser()
  • shouldReturnUser()

3.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 +anything. If you just want to generate tests, invoke the generateTests goal.

3.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>
@@ -1099,7 +801,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>

3.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 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. @@ -1129,7 +831,7 @@ closure: URL to a repo with the artifacts that have contracts. I use the current Maven ones.
  • contractRepository - Lets you use a closure where you can define properties related to repository with contracts.
  • username: The user name to be used to connect to the repo.
  • password: The password to be used to connect to the repo.
  • proxyHost: The proxy host to be used to connect to the repo.
  • proxyPort: The proxy port to be used to connect to the repo.
  • cacheDownloadedContracts - Specifies whether to reuse downloaded JARs that contain contract definitions.

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.

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.

3.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
 
@@ -1144,7 +846,7 @@ endpoint, which should be verified.

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

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.

3.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 @@ -1177,7 +879,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.

3.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>
@@ -1207,7 +909,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 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-
+mvn generateTest test.

3.2.11 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
 ...
@@ -1244,7 +946,7 @@ goal.

For Groovy Spock code, use the following:

</plugin>
         </plugins>
     </pluginManagement>
-</build>

4.2.12 Spring Cloud Contract Verifier on the Consumer Side

You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use +</build>

3.2.12 Spring Cloud Contract Verifier on the Consumer Side

You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use the plugin so that it only converts the contracts and generates the stubs. To achieve that, you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as you would for a provider. You need to copy contracts stored in @@ -1285,7 +987,7 @@ repository.

Here is a sample configuration:

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

4.3 Stubs and Transitive Dependencies

The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +Verifier.

3.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
@@ -1302,7 +1004,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.

3.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, as shown in this example:

my_contracts_dir\
   scenario1\
@@ -1310,9 +1012,9 @@ requires including an order number followed by an underscore, as shown in this e
     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 -http://wiremock.org/stateful-behaviour.html

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

5. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that uses messaging as a +http://wiremock.org/stateful-behaviour.html

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

4. Spring Cloud Contract Verifier Messaging

Spring Cloud Contract Verifier lets you verify applications that uses messaging as a means of communication. All of the integrations shown in this document work with Spring, -but you can also create one of your own and use that.

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.

4.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 @@ -1324,7 +1026,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 +

4.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 @@ -1338,14 +1040,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.

4.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 tests are created. However, there is also a possibility to create Spock tests.

There are 3 main scenarios that we should take into consideration:

  • Scenario 1: There is no input message that produces an output 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

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+jms).

4.3.1 Scenario 1: No Input Message

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		triggeredBy('bookReturnedTriggered()')
@@ -1385,7 +1087,7 @@ it is resolved as a channel name. For Camel"bookName").isEqualTo("foo")
 
-'''

5.3.2 Scenario 2: Output Triggered by Input

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+'''

4.3.2 Scenario 2: Output Triggered by Input

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		messageFrom('jms:input')
@@ -1440,7 +1142,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

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
+"""

4.3.3 Scenario 3: No Output Message

Here is an example for Camel. For the given contract:

def contractDsl = Contract.make {
 	label 'some_label'
 	input {
 		messageFrom('jms:delete')
@@ -1477,7 +1179,7 @@ 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 +'''

4.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 the Stub Runner Messaging sections.

Maven.  @@ -1529,11 +1231,11 @@ publishing { } } }

-

6. Spring Cloud Contract Stub Runner

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

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

5.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>
@@ -1596,7 +1298,7 @@ versions, which are automatically uploaded after every successful build:

"http://repo.spring.io/milestone" } maven { url "http://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 +

5.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 -->
@@ -1684,9 +1386,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 +

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

If you provide the stubrunner.repositoryRoot or stubrunner.workOffline flag will be set +For messaging, special stub routes are defined.

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

If you provide the stubrunner.repositoryRoot or stubrunner.workOffline flag will be set to true then Stub Runner will connect to the given server and download the required jars. It will then unpack the JAR to a temporary folder and reference those files in further contract processing.

Example:

@AutoConfigureStubRunner(repositoryRoot="http://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095")

Classpath scanning

If you DON’T provide the stubrunner.repositoryRoot and stubrunner.workOffline flag will @@ -1747,7 +1449,7 @@ structure in your stubs jar.

└──
                 │       └── contract2.groovy
                 └── mappings
                     └── mapping.json

By maintaining this structure classpath gets scanned and you can profit from the messaging / -HTTP stubs without the need to download artifacts.

6.3.2 Running stubs

Limitations

[Important]Important

There might be a problem with StubRunner shutting down ports between tests. You might +HTTP stubs without the need to download artifacts.

5.3.2 Running stubs

Limitations

[Important]Important

There might be a problem with StubRunner shutting down ports between tests. You might have a situation in which you get port conflicts. As long as you use the same context across tests everything works fine. But when the context are different (e.g. different stubs or different profiles) then you have to either use @DirtiesContext to shut down the stub servers, or else run them on @@ -1814,7 +1516,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

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()
+]

Messaging Stubs

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

5.4 Stub Runner JUnit Rule

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())
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");

After that rule gets executed Stub Runner connects to your Maven repository and for the given list of dependencies tries to:

  • download them
  • cache them locally
  • unzip them to a temporary folder
  • start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port
  • feed the WireMock server with all JSON files that are valid WireMock definitions
  • can also send messages (remember to pass an implementation of MessageVerifier interface)

Stub Runner uses Eclipse Aether mechanism to download the Maven dependencies. @@ -1897,14 +1599,14 @@ def 'should outp then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name")).isEqualTo("fraudDetectionServer"); }

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 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 you can add a stub to download and then pass the port for the last downloaded stub.

@ClassRule public static StubRunnerRule rule = new StubRunnerRule()
+If you don’t do this then whenever you try to send a message an exception will be thrown.

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

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

5.4.3 Fluent API

When using the StubRunnerRule 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())
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
 		.withPort(12345)
 		.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");

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 +then(rule.findStubUrl("fraudDetectionServer")).isEqualTo(URI.create("http://localhost:12346").toURL());

5.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",
@@ -2002,7 +1704,7 @@ Below you can find an example of achieving the same result by setting values on
 		"org.springframework.cloud.contract.verifier.stubs:bootService"],
 		repositoryRoot = "classpath:m2repo/repository/")

Stub Runner Spring registers environment variables in the following manner for every registered WireMock server. Example for Stub Runner ids - com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.bar.port

Which you can reference in your code.

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. + com.example:foo, com.example:bar.

  • stubrunner.runningstubs.foo.port
  • stubrunner.runningstubs.bar.port

Which you can reference in your code.

5.5 Stub Runner Spring Cloud

Stub Runner can integrate with Spring Cloud.

For real life examples you can check the

5.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'
@@ -2026,15 +1728,15 @@ 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. + }

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

6.6 Stub Runner Boot Application

Spring Cloud Contract Stub Runner Boot is a Spring Boot application that exposes REST endpoints to + merged with the stubbed ones.

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

Spring Cloud CLI

Starting from 1.4.0.RELEASE version of the Spring Cloud CLI +project for more information.

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

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 (example for running stubs installed locally)

stubrunner.yml.  @@ -2043,7 +1745,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.

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

5.6.3 Example

@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
 @SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
 @ActiveProfiles("test")
 class StubRunnerBootSpec extends Specification {
@@ -2129,7 +1831,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? +}

5.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 @@ -2162,7 +1864,7 @@ and we want to have the stub runner feature turned on @Aut (4) - we provide a list of artifactId to serviceId mapping

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.

5.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 {
@@ -2215,23 +1917,23 @@ Or set the test as follows:

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.

5.8 Common

This section briefly describes common properties, including:

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

false

If true, then do not contact any remote repositories to download stubs.

stubrunner.ids

 

Array of Ivy notation stubs to download.

stubrunner.username

 

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

stubrunner.password

 

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

stubrunner.stubsPerConsumer

false

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

stubrunner.consumerName

 

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

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.

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

7. Stub Runner for Messaging

Stub Runner can run the published stubs in memory. It can integrate with the following +ranges here.

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

6.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;
@@ -2272,10 +1974,10 @@ That way the only remaining framework is Spring AMQP.

Map<String, Collection<String>> labels(); }

For convenience, the StubFinder interface extends StubTrigger, so you only need one -or the other in your tests.

StubTrigger gives you the following options to trigger a message:

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:camelService', 'return_book_1')

7.1.3 Trigger by Artifact Ids

stubFinder.trigger('camelService', '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 +or the other in your tests.

StubTrigger gives you the following options to trigger a message:

6.1.1 Trigger by Label

stubFinder.trigger('return_book_1')

6.1.2 Trigger by Group and Artifact Ids

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

6.1.3 Trigger by Artifact Ids

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

6.1.4 Trigger All Messages

stubFinder.trigger()

6.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 automatically downloads the -stubs and registers the required routes.

7.2.1 Adding the Runner to the Project

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

7.2.2 Disabling the functionality

If you need to disable this functionality, set the stubrunner.camel.enabled=false +stubs and registers the required routes.

6.2.1 Adding the Runner to the Project

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

6.2.2 Disabling the functionality

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

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

└── .m2
     └── repository
@@ -2334,10 +2036,10 @@ receivedMessage.in.headers.get(
camelContext.createProducerTemplate().sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])

You can listen to the output of the message sent to jms:output:

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

The received message passes 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, you can send a message to the jms:output -destination:

camelContext.createProducerTemplate().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 +destination:

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

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

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

6.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
@@ -2413,7 +2115,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')

6.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 @@ -2426,8 +2128,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 +

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

6.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
@@ -2494,7 +2196,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')

6.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 @@ -2506,7 +2208,7 @@ queues. Bindings connect an exchange to a queue. If message contracts are trigge Spring AMQP stub runner integration looks for bindings on the application context that match this exchange. Then it collects the queues from the Spring exchanges and tries to find message listeners bound to these queues. The message is triggered for all matching -message listeners.

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 +message listeners.

6.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 @@ -2578,7 +2280,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

[Important]Important

Remember that, inside the contract file, you have to provide the fully + mockConnection: false

7. Contract DSL

[Important]Important

Remember that, inside the contract file, you have to provide the fully qualified name to the Contract class and make static imports, such as org.springframework.cloud.spec.Contract.make { …​ }. You can also provide an import to the Contract class: import org.springframework.cloud.spec.Contract and then call @@ -2630,13 +2332,13 @@ Cloud Contract Verifier repository.

The following is a complete exampl } }

[Note]Note

The preceding example does not contain all the features of the DSL appear. The remainder of this section describes the other features.

You can compile Contracts to WireMock 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

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

7.2 Common Top-Level elements

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

7.2.1 Description

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

		org.springframework.cloud.contract.spec.Contract.make {
 			description('''
 given:
@@ -2646,16 +2348,16 @@ when:
 then:
 	Output
 ''')
-		}

8.2.2 Name

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

7.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 generated test not compile. Also, remember that, if you provide the same name for multiple contracts, your autogenerated tests fail to compile and your generated stubs -override each other.

8.2.3 Ignoring Contracts

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

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

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

8.2.4 Passing Values from Files

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

7.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
@@ -2683,7 +2385,7 @@ Contract.make {
 }

Further assume that the JSON files is as follows:

request.json

{ "status" : "REQUEST" }

response.json

{ "status" : "RESPONSE" }

When test or stub generation takes place, the contents of the file is passed to the body of a request or a response. That works because of the file(…​) method. The argument of that method needs to be a file with location relative to the folder in which the contract -lays.

8.2.5 HTTP Top-Level Elements

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

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

org.springframework.cloud.contract.spec.Contract.make {
 	// Definition of HTTP request part of the contract
 	// (this can be a valid request or invalid depending
@@ -2703,7 +2405,7 @@ lays.

// Contract priority, which can be used for overriding // contracts (1 is highest). Priority is optional. priority 1 -}

8.3 Request

The HTTP protocol requires only method and address to be specified in a request. The +}

7.3 Request

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

org.springframework.cloud.contract.spec.Contract.make {
 	request {
 		// HTTP request method (GET/POST/PUT/DELETE).
@@ -2861,7 +2563,7 @@ such as named("fileName", "fileContent"), or via a
 	"transformers" : [ "response-template", "foo-transformer" ]
   }
 }
-	'''

8.4 Response

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

7.4 Response

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

org.springframework.cloud.contract.spec.Contract.make {
 	request {
 		//...
@@ -2872,11 +2574,11 @@ following code shows an example:

org.springframew
 		status 200
 	}
 }

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

8.5 Dynamic properties

The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +specified the same way as in the request (see the previous paragraph).

7.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. You can provide the dynamic parts in your contracts in two ways: pass them directly in the body or set them in separate sections called -testMatchers and stubMatchers.

8.5.1 Dynamic properties inside the body

You can set the properties inside the body either with the value method or, if you use +testMatchers and stubMatchers.

7.5.1 Dynamic properties inside the body

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(...))
@@ -2885,7 +2587,7 @@ 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

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.

7.5.2 Regular expressions

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 {
@@ -3031,7 +2733,7 @@ String nonBlank() {
 				message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
 		)
 	}
-}

8.5.3 Passing Optional Parameters

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

7.5.3 Passing Optional Parameters

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 {
@@ -3096,7 +2798,7 @@ 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

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

7.5.4 Executing Custom Methods on the Server Side

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 {
@@ -3159,7 +2861,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);

7.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. To do so, 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 @@ -3269,7 +2971,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.

7.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. @@ -3301,7 +3003,7 @@ org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExte } }

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

7.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 two separate sections:

  • stubMatchers, which lets you define the dynamic values that should end up in a stub. You can set it in the request or inputMessage part of your contract.
  • testMatchers, which is present in the response or outputMessage side of the @@ -3572,7 +3274,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.

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

'''
@@ -3597,7 +3299,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 +'''

7.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 a sync() method in the response section. The following code shows an example:

org.springframework.cloud.contract.spec.Contract.make {
     request {
@@ -3609,7 +3311,7 @@ provide a sync() method in the 'Passed'
         async()
     }
-}

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 +}

7.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.  @@ -3653,8 +3355,8 @@ 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 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.9.1 Output Triggered by a Method

The output message can be triggered by calling a method (such as a Scheduler when a was +that information (for example, in the stubs, you have to call /my-context-path/url).

7.9 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:

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

def dsl = Contract.make {
 	// Human readable description
 	description 'Some description'
@@ -3679,7 +3381,7 @@ started and a message was sent), as shown in the following example:

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

7.9.2 Output Triggered by a Message

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

def dsl = Contract.make {
 	description 'Some Description'
 	label 'some_label'
@@ -3709,7 +3411,7 @@ example:

def dsl = Contract.make {
 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.9.3 Consumer/Producer

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.

7.9.3 Consumer/Producer

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 @@ -3730,10 +3432,10 @@ parts):

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

8.9.4 Common

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

7.9.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 Pipelines will execute that method -in the genertaed test.

8.10 Multiple Contracts in One File

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

7.10 Multiple Contracts in One File

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

import org.springframework.cloud.contract.spec.Contract
 
 [
@@ -3805,10 +3507,10 @@ 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 iss much better if you name your contracts because doing so makes -your tests far more meaningful.

9. Customization

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 +your tests far more meaningful.

8. Customization

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

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

8.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;
 
@@ -3939,8 +3641,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[]

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

8.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>
@@ -3951,7 +3653,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-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 +

8.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>
@@ -3978,7 +3680,7 @@ following example:

Maven.  </plugin>

Gradle. 

classpath "com.example:beer-common:0.0.1-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
+

8.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
@@ -4019,12 +3721,12 @@ then:
 			contentType(applicationJson())
 		}
 	}
-}

10. Using the Pluggable Architecture

You may encounter cases where you have your contracts have been defined in other formats, +}

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

Assume that your contract is written in a YAML file as follows:

request:
+can generate stubs for other HTTP server implementations).

9.1 Custom Contract Converter

Assume that your contract is written in a YAML file as follows:

request:
   url: /foo
   method: PUT
   headers:
@@ -4157,9 +3859,9 @@ example:

return yamlContract
 		}
 	}
-}

10.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of +}

9.1.1 Pact Converter

Spring Cloud Contract includes support for Pact representation of contracts. Instead of using the Groovy DSL, you can use Pact files. In this section, we -present how to add Pact support for your project.

10.1.2 Pact Contract

Consider following example of a Pact contract, which is a file under the +present how to add Pact support for your project.

9.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"
@@ -4213,7 +3915,7 @@ present how to add Pact support for your project.

"version": "2.4.18" } } -}

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

10.1.3 Pact for Producers

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

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

9.1.3 Pact for Producers

On the producer side, you mustadd 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>
@@ -4283,7 +3985,7 @@ test might be as follows:

"Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
     }
   }
-}

10.1.4 Pact for Consumers

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

9.1.4 Pact for Consumers

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

Maven. 

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

Maven. 

Gradle. 

testCompile "org.springframework.cloud:spring-cloud-contract-spec-pact"
 testCompile 'au.com.dius:pact-jvm-model:2.4.18'

-

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 +

9.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
 
@@ -4335,7 +4037,7 @@ following code listing shows the 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

9.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
 
@@ -4377,7 +4079,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.

9.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
@@ -4460,7 +4162,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.

9.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 {
@@ -4487,7 +4189,7 @@ com.example.CustomStubDownloaderBuilder

Now you can pick a folder with t If you use the repositoryRoot property or the workOffline flag, then an Aether-based implementation that downloads stubs from a remote repository is used. If you do not provide these values, the ClasspathStubProvider (which will scan the classpath) is -used. If you provide more than one, then the first one on the list is used.

11. Spring Cloud Contract WireMock

The Spring Cloud Contract WireMock modules let you use WireMock in a +used. If you provide more than one, then the first one on the list is used.

10. 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 @@ -4517,7 +4219,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.

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.

10.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 @@ -4536,7 +4238,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.

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 +also specify a files root as described in the next section of this document.

10.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 @@ -4547,7 +4249,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.

10.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 followin example:

@RunWith(SpringRunner.class)
 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@@ -4573,7 +4275,7 @@ instance, as shown in the followin 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.

10.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 @@ -4599,7 +4301,7 @@ annotation or the stub runner. If you use the JUnit @Rule< classpath and it is selected by the RestTemplateBuilder and configured to ignore SSL errors. If you use the default java.net client, you do not need the annotation (but it won’t do any harm). There is no support currently for other clients, but it may be added -in future releases.

11.5 WireMock and Spring MVC Mocks

Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +in future releases.

10.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 {
@@ -4630,7 +4332,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 Generating Stubs using REST Docs

Spring REST Docs can be used to generate +Wiremock dependencies and exclude the Spring Boot container (if there is one).

10.6 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 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 @@ -4716,7 +4418,7 @@ available on the classpath (by 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.7 Generating Contracts by Using REST Docs

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

10.7 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, @@ -4765,8 +4467,8 @@ 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

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 +contract. The location of this file would be index/dsl-contract.adoc.

11. Migrations

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

11.1 1.0.x → 1.1.x

This section covers upgrading from version 1.0 to version 1.1.

11.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: @@ -4844,20 +4546,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 +

11.2 1.1.x → 1.2.x

This section covers upgrading from version 1.1 to version 1.2.

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

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

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

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

13. Links

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

12. Links

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

  • Spring Cloud Contract Github Repository
  • Spring Cloud Contract Samples
  • Spring Cloud Contract Documentation
  • Accurest diff --git a/spring-cloud-contract-maven-plugin/checkstyle.rss b/spring-cloud-contract-maven-plugin/checkstyle.rss index 2baf3c0acf..8287aec20a 100644 --- a/spring-cloud-contract-maven-plugin/checkstyle.rss +++ b/spring-cloud-contract-maven-plugin/checkstyle.rss @@ -116,7 +116,7 @@ under the License. - org/springframework/cloud/contract/maven/verifier/CopyContracts.java + org/springframework/cloud/contract/maven/verifier/RunMojo.java 0 @@ -130,7 +130,7 @@ under the License. - org/springframework/cloud/contract/maven/verifier/RunMojo.java + org/springframework/cloud/contract/maven/verifier/CopyContracts.java 0 @@ -158,7 +158,7 @@ under the License. - org/springframework/cloud/contract/maven/verifier/ManifestCreator.java + org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java 0 @@ -172,7 +172,7 @@ under the License. - org/springframework/cloud/contract/maven/verifier/stubrunner/LocalStubRunner.java + org/springframework/cloud/contract/maven/verifier/ManifestCreator.java 0 diff --git a/spring-cloud-contract.xml b/spring-cloud-contract.xml index c94df052db..f9be794107 100644 --- a/spring-cloud-contract.xml +++ b/spring-cloud-contract.xml @@ -844,463 +844,6 @@ constant development. samples. - -Spring Cloud Contract FAQ -
    -Why use Spring Cloud Contract Verifier and not X ? -For the time being Spring Cloud Contract Verifier is a JVM based tool. So it could be your first pick when you’re already creating -software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make -Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are: - - -Possibility to do CDC with messaging - - -Clear and easy to use, statically typed DSL - - -Possibility to copy paste your current JSON file to the contract and only edit its elements - - -Automatic generation of tests from the defined Contract - - -Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory - - -Spring Cloud integration - no discovery service is needed for integration tests - - -
    -
    -What is this value(consumer(), producer()) ? -One of the biggest challenges related to stubs is their reusability. Only if they can be vastly used, will they serve their purpose. -What typically makes that difficult are the hard-coded values of request / response elements. For example dates or ids. -Imagine the following JSON request -{ - "time" : "2016-10-10 20:10:15", - "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a", - "body" : "foo" -} -and JSON response -{ - "time" : "2016-10-10 21:10:15", - "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051", - "body" : "bar" -} -Imagine the pain required to set proper value of the time field (let’s assume that this content is generated by the -database) by changing the clock in the system or providing stub implementations of data providers. The same is related -to the field called id. Will you create a stubbed implementation of UUID generator? Makes little sense…​ -So as a consumer you would like to send a request that matches any form of a time or any UUID. That way your system -will work as usual - will generate data and you won’t have to stub anything out. Let’s assume that in case of the aforementioned -JSON the most important part is the body field. You can focus on that and provide matching for other fields. In other words -you would like the stub to work like this: -{ - "time" : "SOMETHING THAT MATCHES TIME", - "id" : "SOMETHING THAT MATCHES UUID", - "body" : "foo" -} -As far as the response goes as a consumer you need a concrete value that you can operate on. So such a JSON is valid -{ - "time" : "2016-10-10 21:10:15", - "id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051", - "body" : "bar" -} -As you could see in the previous sections we generate tests from contracts. So from the producer’s side the situation looks -much different. We’re parsing the provided contract and in the test we want to send a real request to your endpoints. -So for the case of a producer for the request we can’t have any sort of matching. We need concrete values that the -producer’s backend can work on. Such a JSON would be a valid one: -{ - "time" : "2016-10-10 20:10:15", - "id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a", - "body" : "foo" -} -On the other hand from the point of view of the validity of the contract the response doesn’t necessarily have to -contain concrete values of time or id. Let’s say that you generate those on the producer side - again, you’d -have to do a lot of stubbing to ensure that you always return the same values. That’s why from the producer’s side -what you might want is the following response: -{ - "time" : "SOMETHING THAT MATCHES TIME", - "id" : "SOMETHING THAT MATCHES UUID", - "body" : "bar" -} -How can you then provide one time a matcher for the consumer and a concrete value for the producer and vice versa? -In Spring Cloud Contract we’re allowing you to provide a dynamic value. That means that it can differ for both -sides of the communication. You can pass the values: -Either via the value method -value(consumer(...), producer(...)) -value(stub(...), test(...)) -value(client(...), server(...)) -or using the $() method -$(consumer(...), producer(...)) -$(stub(...), test(...)) -$(client(...), server(...)) -You can read more about this in the Contract DSL section. -Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. -Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). -Inside the producer() method you pass the value that should be used on the producer side (in the generated test). - -If on one side you have passed the regular expression and you haven’t passed the other, then the -other side will get auto-generated. - -Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')). -To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression -for time and UUID are simplified and most likely invalid but we want to keep things very simple in this example): -org.springframework.cloud.contract.spec.Contract.make { - request { - method 'GET' - url '/someUrl' - body([ - time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), - id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) - body: "foo" - ]) - } - response { - status 200 - body([ - time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')), - id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}')) - body: "bar" - ]) - } -} - -Please read the Groovy docs related to JSON to understand how to -properly structure the request / response bodies. - -
    -
    -How to do Stubs versioning? -
    -API Versioning -Let’s try to answer a question what versioning really means. If you’re referring to the API version then there are -different approaches. - - -use Hypermedia, links and do not version your API by any means - - -pass versions through headers / urls - - -I will not try to answer a question which approach is better. Whatever suit your needs and allows you to generate -business value should be picked. -Let’s assume that you do version your API. In that case you should provide as many contracts as many versions you support. -You can create a subfolder for every version or append it to th contract name - whatever suits you more. -
    -
    -JAR versioning -If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches. -Let’s assume that you’re doing Continuous Delivery / Deployment which means that you’re generating a new version of -the jar each time you go through the pipeline and that jar can go to production at any time. For example your jar version -looks like this (it got built on the 20.10.2016 at 20:15:21) : -1.0.0.20161020-201521-RELEASE -In that case your generated stub jar will look like this. -1.0.0.20161020-201521-RELEASE-stubs.jar -In this case you should inside your application.yml or @AutoConfigureStubRunner when referencing stubs provide the - latest version of the stubs. You can do that by passing the + sign. Example -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) -If the versioning however is fixed (e.g. 1.0.4.RELEASE or 2.1.1) then you have to set the concrete value of the jar -version. Example for 2.1.1. -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"}) -
    -
    -Dev or prod stubs -You can manipulate the classifier to run the tests against current development version of the stubs of other services - or the ones that were deployed to production. If you alter your build to deploy the stubs with the prod-stubs classifier - once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs. -Example of tests using development version of stubs -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"}) -Example of tests using production version of stubs -@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"}) -You can pass those values also via properties from your deployment pipeline. -
    -
    -
    -Common repo with contracts -Another way of storing contracts other than having them with the producer is keeping them in a common place. -It can be related to security issues where the consumers can’t clone the producer’s code. Also if you keep -contracts in a single place then you, as a producer, will know how many consumers you have and which -consumer will you break with your local changes. -
    -Repo structure -Let’s assume that we have a producer with coordinates com.example:server and 3 consumers: client1, -client2, client3. Then in the repository with common contracts you would have the following setup -(which you can checkout here: -├── com -│   └── example -│   └── server -│   ├── client1 -│   │   └── expectation.groovy -│   ├── client2 -│   │   └── expectation.groovy -│   ├── client3 -│   │   └── expectation.groovy -│   └── pom.xml -├── mvnw -├── mvnw.cmd -├── pom.xml -└── src - └── assembly - └── contracts.xml -As you can see the under the slash-delimited groupid / artifact id folder (com/example/server) you have -expectations of the 3 consumers (client1, client2 and client3). Expectations are the standard Groovy DSL -contract files as described throughout this documentation. This repository has to produce a JAR file that maps -one to one to the contents of the repo. -Example of a pom.xml inside the server folder. -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <groupId>com.example</groupId> - <artifactId>server</artifactId> - <version>0.0.1-SNAPSHOT</version> - - <name>Server Stubs</name> - <description>POM used to install locally stubs for consumer side</description> - - <parent> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-parent</artifactId> - <version>1.5.4.RELEASE</version> - <relativePath /> - </parent> - - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <java.version>1.8</java.version> - <spring-cloud-contract.version>1.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version> - <spring-cloud-dependencies.version>Edgware.BUILD-SNAPSHOT</spring-cloud-dependencies.version> - <excludeBuildFolders>true</excludeBuildFolders> - </properties> - - <dependencyManagement> - <dependencies> - <dependency> - <groupId>org.springframework.cloud</groupId> - <artifactId>spring-cloud-dependencies</artifactId> - <version>${spring-cloud-dependencies.version}</version> - <type>pom</type> - <scope>import</scope> - </dependency> - </dependencies> - </dependencyManagement> - - <build> - <plugins> - <plugin> - <groupId>org.springframework.cloud</groupId> - <artifactId>spring-cloud-contract-maven-plugin</artifactId> - <version>${spring-cloud-contract.version}</version> - <extensions>true</extensions> - <configuration> - <!-- By default it would search under src/test/resources/ --> - <contractsDirectory>${project.basedir}</contractsDirectory> - </configuration> - </plugin> - </plugins> - </build> - - <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> - -</project> -As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin. -Those poms are necessary for the consumer side to run mvn clean install -DskipTests to locally install - stubs of the producer project. -The pom.xml in the root folder can look like this: -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <groupId>com.example.standalone</groupId> - <artifactId>contracts</artifactId> - <version>0.0.1-SNAPSHOT</version> - - <name>Contracts</name> - <description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the producers to generate tests and stubs</description> - - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - </properties> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-assembly-plugin</artifactId> - <executions> - <execution> - <id>contracts</id> - <phase>prepare-package</phase> - <goals> - <goal>single</goal> - </goals> - <configuration> - <attach>true</attach> - <descriptor>${basedir}/src/assembly/contracts.xml</descriptor> - <!-- If you want an explicit classifier remove the following line --> - <appendAssemblyId>false</appendAssemblyId> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project> -It’s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here: -<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd"> - <id>project</id> - <formats> - <format>jar</format> - </formats> - <includeBaseDirectory>false</includeBaseDirectory> - <fileSets> - <fileSet> - <directory>${project.basedir}</directory> - <outputDirectory>/</outputDirectory> - <useDefaultExcludes>true</useDefaultExcludes> - <excludes> - <exclude>**/${project.build.directory}/**</exclude> - <exclude>mvnw</exclude> - <exclude>mvnw.cmd</exclude> - <exclude>.mvn/**</exclude> - <exclude>src/**</exclude> - </excludes> - </fileSet> - </fileSets> -</assembly> -
    -
    -Workflow -The workflow would look similar to the one presented in the Step by step guide to CDC. The only difference - is that the producer doesn’t own the contracts anymore. So the consumer and the producer have to work on - common contracts in a common repository. -
    -
    -Consumer -When the consumer wants to work on the contracts offline, instead of cloning the producer code, the -consumer team clones the common repository, goes to the required producer’s folder (e.g. com/example/server) -and runs mvn clean install -DskipTests to install locally the stubs converted from the contracts. - -You need to have Maven installed locally - -
    -
    -Producer -As a producer it’s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency -of the JAR containing the contracts: -<plugin> - <groupId>org.springframework.cloud</groupId> - <artifactId>spring-cloud-contract-maven-plugin</artifactId> - <configuration> - <contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl> - <contractDependency> - <groupId>com.example.standalone</groupId> - <artifactId>contracts</artifactId> - </contractDependency> - </configuration> -</plugin> -With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded -from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder -and contracts present under the com/example/server will be picked as the ones used to generate the -tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken -when some incompatible changes are done. -The rest of the flow looks the same. -
    -
    -
    -Can I have multiple base classes for tests? -Yes! Check out the Different base classes for contracts sections -of either Gradle or Maven plugins. -
    -
    -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 -
    -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 -
    -
    -How can I see what got registered in the HTTP server stub? -You can use the mappingsOutputFolder property on @AutoConfigureStubRunner or StubRunnerRule -to dump all mappings per artifact id. Also the port at which the given stub server was -started will be attached. -
    -
    -Can I reference the request from the response? -Yes! With version 1.1.0 we’ve added such a possibility. On the HTTP stub server side we’re providing support -for this for WireMock. In case of other HTTP server stubs you’ll have to implement the approach yourself. -
    -
    -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. -
    -
    -
    Spring Cloud Contract Verifier Setup You can set up Spring Cloud Contract Verifier in either of two ways