diff --git a/2.0.x/multi/multi__contract_dsl.html b/2.0.x/multi/multi__contract_dsl.html index 65228fc61b..2d79cedf18 100644 --- a/2.0.x/multi/multi__contract_dsl.html +++ b/2.0.x/multi/multi__contract_dsl.html @@ -1,11 +1,15 @@
-![]() | Important |
|---|---|
Remember that inside the contract file you have to provide the fully qualified name to
-the |
Contract DSL is written in Groovy, but don’t be alarmed if you didn’t use Groovy before. Knowledge of the language is not really needed as our DSL uses only -a tiny subset of it (namely literals, method calls and closures). What’s more the DSL is designed to be programmer-readable without any knowledge of the DSL itself - - it’s statically typed.
![]() | Tip |
|---|---|
Spring Cloud Contract supports defining multiple contracts in a single file! |
The Contract is present in the spring-cloud-contract-spec module of the Spring Cloud Contract Verifier repository.
Let’s look at full example of a contract definition.
org.springframework.cloud.contract.spec.Contract.make {
+ 7. Contract DSL ![[Important]](images/important.png)
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
+Contract.make { … }.
Contract DSL is written in Groovy, but do not be alarmed if you have not used Groovy
+before. Knowledge of the language is not really needed, as the Contract DSL uses only a
+tiny subset of it (only literals, method calls and closures). Also, the DSL is statically
+typed, to make it programmer-readable without any knowledge of the DSL itself.
![[Tip]](images/tip.png)
Tip Spring Cloud Contract supports defining multiple contracts in a single file.
The Contract is present in the spring-cloud-contract-spec module of the
+Spring
+Cloud Contract Verifier repository.
The following is a complete example of a contract definition:
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/api/12'
@@ -46,11 +50,16 @@ a tiny subset of it (namely literals, method calls and closures). What’s m
response {
status 200
}
-}Not all features of the DSL are used in example above. If you didn’t find what you are looking for, please check next paragraphs on this page.
You can easily compile Contracts to WireMock stubs mapping using standalone maven command: mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert.
![[Warning]](images/warning.png)
Warning Spring Cloud Contract Verifier doesn’t support XML properly. Please use JSON or help us implement this feature.
![[Warning]](images/warning.png)
Warning The support for the verification of size of JSON arrays is experimental. If you want to turn it on please provide
-the value of a system property spring.cloud.contract.verifier.assert.size equal to true. By default this feature is set to
-false. You can also provide the assertJsonSize property in the plugin configuration.
![[Warning]](images/warning.png)
Warning Due to the fact that JSON structure can have any form it’s sometimes impossible to parse it properly when using
-the value(consumer(…), producer(…)) notation when using that in GString. That’s why we highly recommend using the
-Groovy Map notation.
You can add a description to your contract that is nothing else but an arbitrary text. Example:
org.springframework.cloud.contract.spec.Contract.make {
+}![[Note]](images/note.png)
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
![[Warning]](images/warning.png)
Warning Spring Cloud Contract Verifier does not properly support XML. Please use JSON or
+help us implement this feature.
![[Warning]](images/warning.png)
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]](images/warning.png)
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.
The following sections describe the most common top-level elements:
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:
An input
@@ -59,21 +68,23 @@ when:
then:
Output
''')
- }You can provide a name of your contract. Let’s assume that you’ve provided a name should register a user.
-If you do this then the name of the autogenerated test will be equal to validate_should_register_a_user.
-Also the name of the stub will be should_register_a_user.json in case of a WireMock stub.
![[Important]](images/important.png)
Important Please ensure that the name doesn’t contain any characters that will make the generated test
- not possible to compile. Also remember that if you provide the same name for multiple contracts then your
- autogenerated tests will fail to compile and your generated stubs will override each other.
If you want to ignore a contract you can either set a value of ignored contracts in the plugin configuration
-or just set the ignored property on the contract itself:
org.springframework.cloud.contract.spec.Contract.make {
+ }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]](images/important.png)
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.
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()
-}Starting with version 1.2.0 it’s possible to pass values from files. Let’s assume that we have
-the following resources in our project.
└── src
+}
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
└── contracts
├── readFromFile.groovy
├── request.json
- └── response.jsonAnd our contract looks like this:
import org.springframework.cloud.contract.spec.Contract
+ └── response.jsonFurther assume that your contract is as follows:
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
@@ -91,10 +102,11 @@ Contract.make {
contentType(textPlain())
}
}
-}and the json files look like this:
request.json
{ "status" : "REQUEST" }
response.json
{ "status" : "RESPONSE" }
When test / stub generation takes place then the contents of the file will be
-passed to the body of request / response. All thanks to the file(…) method.
-The argument of that method needs to be a file with location relative to the
-folder in which the contract lays.
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 {
+}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.
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
// on type of contract being specified).
@@ -113,7 +125,8 @@ folder in which the contract lays.// Contract priority, which can be used for overriding
// contracts (1 is highest). Priority is optional.
priority 1
-}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).
method 'GET'
@@ -125,7 +138,8 @@ folder in which the contract lays.//...
}
-}It is possible to specify whole url instead of just path, but urlPath is the recommended way as it makes the tests host-independent.
org.springframework.cloud.contract.spec.Contract.make {
+}It is possible to specify an absolute rather than relative url, but using urlPath is
+the recommended way, as doing so makes the tests host-independent.
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
@@ -136,7 +150,8 @@ folder in which the contract lays.//...
}
-}Request may contain query parameters, which are specified in a closure nested in a call to urlPath or url.
org.springframework.cloud.contract.spec.Contract.make {
+}request may contain query parameters, which are specified in a closure nested in a
+call to urlPath or url.
org.springframework.cloud.contract.spec.Contract.make {
request {
//...
@@ -176,7 +191,7 @@ folder in which the contract lays.//...
}
-}It may contain additional request headers…
org.springframework.cloud.contract.spec.Contract.make {
+}request may contain additional request headers, as shown in the following example:
org.springframework.cloud.contract.spec.Contract.make {
request {
//...
@@ -193,7 +208,7 @@ folder in which the contract lays.//...
}
-}…and a request body.
org.springframework.cloud.contract.spec.Contract.make {
+}request may contain a request body, as shown in the following example:
org.springframework.cloud.contract.spec.Contract.make {
request {
//...
@@ -205,7 +220,8 @@ folder in which the contract lays.//...
}
-}Request may contain multipart elements. Just call the multipart() method.
org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
+}request may contain multipart elements. To include multipart elements, call the
+multipart() method, as shown in the following example
org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
request {
method "PUT"
url "/multipart"
@@ -228,12 +244,11 @@ folder in which the contract lays.200
}
-}In this example we defined parameters either directly by using the map notation,
-where the value can be a dynamic property (e.g. formParameter: $(consumer(…), producer(…)))
- or by using the named(…) method that allows you to set a named parameter.
- A named parameter can set a name and content. You can call it either via
- a method with 2 arguments: e.g. named("fileName", "fileContent") or
- via a map notation named(name: "fileName", content: "fileContent").
From this contract the generated test will look more or less like this:
// given:
+}In the preceding example, we define parameters in either of two ways:
- Directly, by using the map notation, where the value can be a dynamic property (such as
+
formParameter: $(consumer(…), producer(…))). - By using the
named(…) method that lets you set a named parameter. A named parameter
+can set a name and content. You can call it either via a method with two arguments,
+such as named("fileName", "fileContent"), or via a map notation, such as
+named(name: "fileName", content: "fileContent").
From this contract, the generated test is as follows:
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "multipart/form-data;boundary=AaB03x")
.param("formParameter", "\"formParameterValue\"")
@@ -245,7 +260,7 @@ where the value can be a dynamic property (e.g. formParame
.put("/multipart");
// then:
- assertThat(response.statusCode()).isEqualTo(200);
The WireMock stub will look more or less like this:
'''
+ assertThat(response.statusCode()).isEqualTo(200);
The WireMock stub is as follows:
'''
{
"request" : {
"url" : "/multipart",
@@ -268,7 +283,8 @@ where the value can be a dynamic property (e.g. formParame
"transformers" : [ "response-template" ]
}
}
- '''
Minimal response must contain HTTP status code.
org.springframework.cloud.contract.spec.Contract.make {
+ '''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 {
//...
}
@@ -277,19 +293,24 @@ where the value can be a dynamic property (e.g. formParame
// in response to request specified above.
status 200
}
-}Besides status response may contain headers and body, which are specified the same way as in the request (see previous paragraph).
The contract can contain some dynamic properties - timestamps / ids etc. You don’t want to enforce the consumers to stub their
-clocks to always return the same value of time so that it gets matched by the stub. That’s why we allow you to provide the dynamic
-parts in your contracts in two ways. One is to pass them directly in the
-body and one to set them in a separate section called testMatchers and stubMatchers.
You can set the properties inside the body either via the value method
value(consumer(...), producer(...))
+}
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).
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.
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(...))
value(stub(...), test(...))
-value(client(...), server(...))
or if you’re using the Groovy map notation for body you can use the $() method
$(consumer(...), producer(...))
+value(client(...), server(...))
The following example shows how to set dynamic properties with $():
$(consumer(...), producer(...))
$(c(...), p(...))
$(stub(...), test(...))
-$(client(...), server(...))
All of the aforementioned approaches are equal. That means that stub and client methods are aliases over the consumer
-method. Let’s take a closer look at what we can do with those values in the subsequent sections.
You can use regular expressions to write your requests in Contract DSL. It 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 it when you need to use patterns and not exact values both
-for your test and your server side tests.
Please see the example below:
org.springframework.cloud.contract.spec.Contract.make {
+$(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.
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 {
request {
method('GET')
url $(consumer(~/\/[0-9]{2}/), producer('/12'))
@@ -312,8 +333,9 @@ for your test and your server side tests.Please see the example below:
'Content-Type': 'text/plain'
}
}
-}You can also provide only one side of the communication using a regular expression. If you do that then automatically we’ll
-provide the generated string that matches the provided regular expression. For example:
org.springframework.cloud.contract.spec.Contract.make {
+}You can also provide only one side of the communication with a regular expression. If you
+do so, then the contract engine automatically provides the generated string that matches
+the provided regular expression. The following code shows an example:
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url value(consumer(regex('/foo/[0-9]{5}')))
@@ -333,7 +355,9 @@ provide the generated string that matches the provided regular expression. For e
contentType("application/vnd.fraud.v1+json")
}
}
-}In this example for request and response the opposite side of the communication will have the respective data generated.
Spring Cloud Contract comes with a series of predefined regular expressions that you can use in your contracts.
protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
+}
In the preceding example, the opposite side of the communication has the respective data
+generated for request and response.
Spring Cloud Contract comes with a series of predefined regular expressions that you can
+use in your contracts, as shown in the following example:
protected static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/)
protected static final Pattern NUMBER = Pattern.compile('-?\\d*(\\.\\d+)?')
protected static final Pattern IP_ADDRESS = Pattern.compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])')
@@ -406,7 +430,7 @@ Pattern nonEmpty() {
Pattern nonBlank() {
return NON_BLANK
-}
so in your contract you can use it like this
Contract dslWithOptionalsInString = Contract.make {
+}In your contract, you can use it as shown in the following example:
Contract dslWithOptionalsInString = Contract.make {
priority 1
request {
method POST()
@@ -429,7 +453,8 @@ Pattern nonBlank() {
message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
)
}
-}It is possible to provide optional parameters in your contract. It’s only possible to have optional parameter for the:
- STUB side of the Request
- TEST side of the Response
Example:
org.springframework.cloud.contract.spec.Contract.make {
+}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 {
method 'POST'
@@ -451,7 +476,8 @@ Pattern nonBlank() {
code: value(consumer("123123"), producer(optional("123123")))
)
}
-}By wrapping a part of the body with the optional() method you are in fact creating a regular expression that should be present 0 or more times.
That way for the example above the following test would be generated if you pick Spock:
"""
+}
By wrapping a part of the body with the optional() method, you create a regular
+expression that must be present 0 or more times.
If you use Spock for, the following test would be generated from the previous example:
"""
given:
def request = given()
.header("Content-Type", "application/json")
@@ -467,7 +493,7 @@ Pattern nonBlank() {
and:
DocumentContext parsedJson = JsonPath.parse(response.body.asString())
assertThatJson(parsedJson).field("['code']").matches("(123123)?")
-"""
and the following stub:
'''
+"""
The following stub would also be generated:
'''
{
"request" : {
"url" : "/users/password",
@@ -492,8 +518,9 @@ Pattern nonBlank() {
},
"priority" : 1
}
-'''
It is also possible to define a method call to be executed on the server side during the test. Such a method can be added to the class defined as "baseClassForTests"
-in the configuration. Example:
Contract
org.springframework.cloud.contract.spec.Contract.make {
+'''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 {
method 'PUT'
url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12'))
@@ -513,7 +540,7 @@ in the configuration. Example:Contract200
}
-}
Base class
abstract class BaseMockMvcSpec extends Specification {
+}
The following code shows the base class portion of the test case:
abstract class BaseMockMvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
@@ -527,13 +554,13 @@ in the configuration. Example:Contract![[Important]](images/important.png)
Important You can’t use both a String and execute to perform concatenation. E.g. calling
-header('Authorization', 'Bearer ' + execute('authToken()')) will lead to improper results.
-To make this work just call header('Authorization', execute('authToken()')) and ensure that
-the authToken() method returns everything that you need.
The type of the object read from the JSON can be one of the followings depending on the
-JSON path:
String if you point to a String value in a JSONJSONArray if you point to a List in a JSONMap if you point to a Map in a JSON- proper
Number if you point to Integer, Double etc. in a JSON Boolean if you point to a Boolean in a JSON
In the request part of the contract you can specify that the body should be
-taken from a method.
![[Important]](images/important.png)
Important You have to provide both the consumer and the producer side
-and the execute part can be applied for the whole body. Not for parts of it!
Example:
Contract contractDsl = Contract.make {
+}![[Important]](images/important.png)
Important You cannot use both a String and execute to perform concatenation. For
+example, calling header('Authorization', 'Bearer ' + execute('authToken()')) leads to
+improper results. Instead, call header('Authorization', execute('authToken()')) and
+ensure that the authToken() method returns everything you need.
The type of the object read from the JSON can be one of the following, depending on the
+JSON path:
String: If you point to a String value in the JSON.JSONArray: If you point to a List in the JSON.Map: If you point to a Map in the JSON.Number: If you point to Integer, Double etc. in the JSON.Boolean: If you point to a Boolean in the JSON.
In the request part of the contract, you can specify that the body should be taken from
+a method.
![[Important]](images/important.png)
Important You must provide both the consumer and the producer side. The execute part
+is applied for the whole body - not for parts of it.
The following example shows how to read an object from JSON:
Contract contractDsl = Contract.make {
request {
method 'GET'
url '/something'
@@ -544,8 +571,8 @@ and the execute part can be applied for the whole b
response {
status 200
}
-}This will result in calling the hashCode() method in the request body.
-It would more or less like this:
// given:
+}The preceding example results in calling the hashCode() method in the request body.
+It should resemble the following code:
// given:
MockMvcRequestSpecification request = given()
.body(hashCode());
@@ -554,9 +581,12 @@ It would more or less like this:
"/something");
// then:
- assertThat(response.statusCode()).isEqualTo(200);
The best situation is to provide fixed values but sometimes you need to reference a request in your response.
-In order to do this you can profit from the fromRequest() method that allows you to reference a bunch
-of elements from the HTTP request. You can use the following options:
fromRequest().url() - return the request URL and query parametersfromRequest().query(String key) - return the first query parameter with a given namefromRequest().query(String key, int index) - return the nth query parameter with a given namefromRequest().path() - return the full pathfromRequest().path(int index) - return the nth path elementfromRequest().header(String key) - return the first header with a given namefromRequest().header(String key, int index) - return the nth header with a given namefromRequest().body() - return the full request bodyfromRequest().body(String jsonPath) - return the element from the request that matches the JSON Path
Let’s take a look at the following contract
Contract contractDsl = Contract.make {
+ assertThat(response.statusCode()).isEqualTo(200);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
+given name.fromRequest().path(): Returns the full path.fromRequest().path(int index): Returns the nth path element.fromRequest().header(String key): Returns the first header with a given name.fromRequest().header(String key, int index): Returns the nth header with a given name.fromRequest().body(): Returns the full request body.fromRequest().body(String jsonPath): Returns the element from the request that
+matches the JSON Path.
Consider the following contract:
Contract contractDsl = Contract.make {
request {
method 'GET'
url('/api/v1/xxxx') {
@@ -590,7 +620,7 @@ of elements from the HTTP request. You can use the following options:"Bla bla ${fromRequest().body('$.foo')} bla bla"
)
}
-}Running a JUnit test generation will lead in creation of a test looking more or less like this
// given:
+}Running a JUnit test generation leads to a test that resembles the following example:
// given:
MockMvcRequestSpecification request = given()
.header("Authorization", "secret")
.header("Authorization", "secret2")
@@ -617,7 +647,7 @@ of elements from the HTTP request. You can use the following options:"['responseBaz']").isEqualTo(5);
assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&foo=bar2");
- assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");As you can see elements from the request have been properly referenced in the response.
The generated WireMock stub will look more or less like this:
{
+ assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");
As you can see, elements from the request have been properly referenced in the response.
The generated WireMock stub should resemble the following example:
{
"request" : {
"urlPath" : "/api/v1/xxxx",
"method" : "POST",
@@ -645,8 +675,8 @@ of elements from the HTTP request. You can use the following options:},
"transformers" : [ "response-template" ]
}
-}So sending a request as the one presented in the request part of the contract will lead in sending the following
-response body
{
+}
Sending a request such as the one presented in the request part of the contract results
+in sending the following response body:
{
"url" : "/api/v1/xxxx?foo=bar&foo=bar2",
"path" : "/api/v1/xxxx",
"pathIndex" : "v1",
@@ -658,34 +688,33 @@ response body"responseFoo" : "bar",
"responseBaz" : 5,
"responseBaz2" : "Bla bla bar bla bla"
-}
![[Important]](images/important.png)
Important This feature will work only with WireMock having version greater or equal to 2.5.1. We’re using WireMock’s
-response-template response transformer. It’s using Handlebars to convert the Mustache {{{ }}} templates into
-proper values. Additionally we’re registering 2 helper functions. escapejsonbody - that escapes the request
-body in a format that can be embedded in a JSON. Another is jsonpath that for a given parameter knows how to
-find an object in the request body.
If you’ve been working with Pact this might seem familiar. Quite a few users
-are used to having a separation between the body and setting dynamic parts of your contract.
That’s why you can profit from two separate sections. One is called stubMatchers where you can
-define the dynamic values that should end up in a stub. You can set it in the request or inputMessage
-part of your contract. The other is called testMatchers which is present in the response or
-outputMessage side of the contract.
Currently we support only JSON Path based matchers with the following matching possibilities.
-For stubMatchers:
byEquality() - the value taken from the response via the provided JSON Path needs
-to be equal to the provided value in the contractbyRegex(…) - the value taken from the response via the provided JSON Path needs
-to match the regexbyDate() - the value taken from the response via the provided JSON Path needs to
-match the regex for ISO DatebyTimestamp() - the value taken from the response via the provided JSON Path needs
-to match the regex for ISO DateTimebyTime() - the value taken from the response via the provided JSON Path needs to
-match the regex for ISO Time
For testMatchers:
byEquality() - the value taken from the response via the provided JSON Path needs
-to be equal to the provided value in the contractbyRegex(…) - the value taken from the response via the provided JSON Path needs
-to match the regexbyDate() - the value taken from the response via the provided JSON Path needs to
-match the regex for ISO DatebyTimestamp() - the value taken from the response via the provided JSON Path needs
-to match the regex for ISO DateTimebyTime() - the value taken from the response via the provided JSON Path needs to
-match the regex for ISO TimebyType() - the value taken from the response via the provided JSON Path needs to
-be of the same type as the type defined in the body of the response in the contract.
-byType can take a closure where you can set minOccurrence and maxOccurrence.
-That way you can assert on the size of the flattened collection. To check the size
-of an unflattened collection, use a custom method via byCommand(…) testMatcher.byCommand(…) - the value taken from the response via the provided JSON Path will be
-passed as an input to the custom method that you’re providing. E.g. byCommand('foo($it)')
-will result in calling a foo method to which the value matching the JSON Path will get
- passed.
The type of the object read from the JSON can be one of the followings depending on the
-JSON path:
String if you point to a String value in a JSONJSONArray if you point to a List in a JSONMap if you point to a Map in a JSON- proper
Number if you point to Integer, Double etc. in a JSON Boolean if you point to a Boolean in a JSON
Let’s take a look at the following example:
Contract contractDsl = Contract.make {
+}![[Important]](images/important.png)
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.
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
+contract.
Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the
+following matching possibilities:
For stubMatchers:
byEquality(): The value taken from the response via the provided JSON Path must be
+equal to the value provided in the contract.byRegex(…): The value taken from the response via the provided JSON Path must
+match the regex.byDate(): The value taken from the response via the provided JSON Path must
+match the regex for an ISO Date value.byTimestamp(): The value taken from the response via the provided JSON Path must
+match the regex for an ISO DateTime value.byTime(): The value taken from the response via the provided JSON Path must
+match the regex for an ISO Time value.
For testMatchers:
byEquality(): The value taken from the response via the provided JSON Path must be
+equal to the provided value in the contract.byRegex(…): The value taken from the response via the provided JSON Path must
+match the regex.byDate(): The value taken from the response via the provided JSON Path must match
+the regex for an ISO Date value.byTimestamp(): The value taken from the response via the provided JSON Path must
+match the regex for an ISO DateTime value.byTime(): The value taken from the response via the provided JSON Path must match
+the regex for an ISO Time value.byType(): The value taken from the response via the provided JSON Path needs to be
+of the same type as the type defined in the body of the response in the contract.
+byType can take a closure, in which you can set minOccurrence and maxOccurrence.
+That way, you can assert the size of the flattened collection. To check the size of an
+unflattened collection, use a custom method with the byCommand(…) testMatcher.byCommand(…): The value taken from the response via the provided JSON Path is
+passed as an input to the custom method that you provide. For example,
+byCommand('foo($it)') results in calling a foo method to which the value matching the
+JSON Path gets passed. The type of the object read from the JSON can be one of the
+following, depending on the JSON path:
String: If you point to a String value.JSONArray: If you point to a List.Map: If you point to a Map.Number: If you point to Integer, Double, or other kind of number.Boolean: If you point to a Boolean.
Consider the following example:
Contract contractDsl = Contract.make {
request {
method 'GET'
urlPath '/get'
@@ -791,15 +820,20 @@ JSON path:valueWithoutAMatcher we’re setting
- explicitly the values of regular expressions we’d like the stub to contain. For the valueWithoutAMatcher
- the verification will take place in the same way as without the usage of matchers - the test
- will perform an equality check in this case.For the response side in the testMatchers section we’re defining all the dynamic parts
- in a similar manner. The only difference is that we have the byType matchers too. In that
- case we’re checking 4 fields in the way that we’re verifying whether the response from the test
- has a value whose JSON path matching the given field is of the same type as the one defined in the response body and:
- for
$.valueWithTypeMatch - we’re just checking the whether the type is the same - for
$.valueWithMin - we’re checking the type and assert if the size is greater or equal to the min occurrence - for
$.valueWithMax - we’re checking the type and assert if the size is smaller or equal to the max occurrence - for
$.valueWithMinMax - we’re checking the type and assert if the size is between the min and max occurrence
The resulting test would look more or less like this (note that we’re separating the autogenerated
-assertions and the one from matchers with an and section):
// given:
+}In the preceding example, you can see the dynamic portions of the contract in the
+matchers sections. For the request part, you can see that, for all fields but
+valueWithoutAMatcher, the values of the regular expressions that the stub should
+contain are explicitly set. For the valueWithoutAMatcher, the verification takes place
+in the same way as without the use of matchers. In that case, the test performs an
+equality check.
For the response side in the testMatchers section, we define the dynamic parts in a
+similar manner. The only difference is that the byType matchers are also present. The
+verifier engine checks four fields to verify whether the response from the test
+has a value for which the JSON path matches the given field, is of the same type as the one
+defined in the response body, and passes the following check (based on the method being called):
- For
$.valueWithTypeMatch, the engine checks whether the type is the same. - For
$.valueWithMin, the engine check the type and asserts whether the size is greater
+than or equal to the minimum occurrence. - For
$.valueWithMax, the engine checks the type and asserts whether the size is
+smaller than or equal to the maximum occurrence. - For
$.valueWithMinMax, the engine checks the type and asserts whether the size is
+between the min and maximum occurrence.
The resulting test would resemble the following example (note that an and section
+separates the autogenerated assertions and the assertion from matchers):
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"duck\":123,\"alpha\":\"abc\",\"number\":123,\"aBoolean\":true,\"date\":\"2017-01-01\",\"dateTime\":\"2017-01-01T01:23:45\",\"time\":\"01:02:34\",\"valueWithoutAMatcher\":\"foo\",\"valueWithTypeMatch\":\"string\"}");
@@ -835,10 +869,11 @@ assertions and the one from matchers with an and se
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).hasSizeGreaterThanOrEqualTo(0);
assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).hasSizeLessThanOrEqualTo(0);
- assertThatValueIsANumber(parsedJson.read("$.duck"));
![[Important]](images/important.png)
Important Notice that for the byCommand method we are calling the assertThatValueIsANumber. This method needs
-to be defined in the test base class or should be statically imported to your tests.
-Notice that the byCommand call was converted to assertThatValueIsANumber(parsedJson.read("$.duck"));. That means
-that we took the method name and passed the proper JSON path as a parameter to it.
and the WireMock stub like this:
'''
+ assertThatValueIsANumber(parsedJson.read("$.duck"));
![[Important]](images/important.png)
Important Notice that, for the byCommand method, the example calls the
+assertThatValueIsANumber. This method must be defined in the test base class or be
+statically imported to your tests. Notice that the byCommand call was converted to
+assertThatValueIsANumber(parsedJson.read("$.duck"));. That means that the engine took
+the method name and passed the proper JSON path as a parameter to it.
The resulting WireMock stub is in the following example:
'''
{
"request" : {
"urlPath" : "/get",
@@ -888,9 +923,10 @@ that we took the method name and passed the proper JSON path as a parameter to i
}
}
}
-'''
![[Important]](images/important.png)
Important If you use a matcher then the part of the request / response that the matcher is addressing
-via the JSON Path will get removed from assertion. In case of verifying a collection you have to create
-matchers for all elements of the collection.
Let’s look at the following example:
Contract.make {
+'''![[Important]](images/important.png)
Important If you use a matcher, then the part of the request aned response that the
+matcher addresses with the JSON Path gets removed from the assertion. In the case of
+verifying a collection, you must create matchers for all the elements of the
+collection.
Consider the following example:
Contract.make {
request {
method 'GET'
url("/foo")
@@ -914,7 +950,7 @@ matchers for all elements of the co
jsonPath('$.events[0].status', byRegex('.+'))
}
}
-}This will lead in creating the following test (showing just the assertion section)
and:
+}
The preceding code leads to creating the following test (the code block shows only the assertion section):
and:
DocumentContext parsedJson = JsonPath.parse(response.body.asString())
assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("16f1ed75-0bcc-4f0d-a04d-3121798faf99")
assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("EXPORT")
@@ -924,9 +960,12 @@ matchers for all elements of the co
and:
assertThat(parsedJson.read("\$.events[0].operation", String.class)).matches(".+")
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. That’s because only the first element of the array got asserted.
-In order to fix this it’s best to apply the assertion to the whole $.events collection and assert it
-via the byCommand(…) method.
We support JAX-RS 2 Client API. Base class needs to define protected WebTarget webTarget and server initialization, right now the only option how to test JAX-RS API is to start a web server.
Request with a body needs to have a content type set otherwise application/octet-stream is going to be used.
In order to use JAX-RS mode, use the following settings:
testMode == 'JAXRSCLIENT'Example of a test API generated:
'''
+ 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.
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:
'''
// when:
Response response = webTarget
.path("/users")
@@ -948,9 +987,9 @@ via the byCommand(…) method.
// and:
DocumentContext parsedJson = JsonPath.parse(responseAsString);
assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
-'''
If you’re using asynchronous communication on the server side (your controllers are returning
-Callable, DeferredResult etc. then inside your contract you have to provide in the response
-section a async() method. Example:
org.springframework.cloud.contract.spec.Contract.make {
+'''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 {
method GET()
url '/get'
@@ -960,8 +999,10 @@ section a async() method. Example:'Passed'
async()
}
-}Spring Cloud Contract supports context paths.
![[Important]](images/important.png)
Important The only thing that changes in order to fully support context paths is the switch
-on the PRODUCER side. The autogenerated tests need to be using the EXPLICIT mode.
The consumer side remains untouched, in order for the generated test to pass you have to switch the EXPLICIT mode.
Maven.
+}
Spring Cloud Contract supports context paths.
![[Important]](images/important.png)
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.
<plugin>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
@@ -975,8 +1016,9 @@ on the PRODUCER side. The autogener
contracts {
testMode = 'EXPLICIT'
}
-
That way you’ll generate a test that DOES NOT use MockMvc. It means that you’re generating
-real requests and you need to setup your generated test’s base class to work on a real socket.
Let’s imagine the following contract:
org.springframework.cloud.contract.spec.Contract.make {
+That way, you generate a test that DOES NOT use MockMvc. It means that you generate
+real requests and you need to setup your generated test’s base class to work on a real
+socket.
Consider the following contract:
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/my-context-path/url'
@@ -984,7 +1026,7 @@ real requests and you need to setup your generated test’s base class to wo
response {
status 200
}
-}Here is an example of how to set up a base class and Rest Assured for everything to work correctly.
import io.restassured.RestAssured;
+}The following example shows how to set up a base class and Rest Assured:
import io.restassured.RestAssured;
import org.junit.Before;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
@@ -999,8 +1041,11 @@ real requests and you need to setup your generated test’s base class to wo
RestAssured.baseURI = "http://localhost";
RestAssured.port = this.port;
}
-}
That way all:
- all your requests in the autogenerated tests will be sent to the real endpoint with your context path included (e.g.
/my-context-path/url) - your contracts reflect that you have a context path, thus your generated stubs will also
-have that information (e.g. in the stubs you’ll see that you have too call
/my-context-path/url)
The DSL for messaging looks a little bit different than the one that focuses on HTTP.
The output message can be triggered by calling a method (e.g. a Scheduler was started and a message was sent)
def dsl = Contract.make {
+}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).
The DSL for messaging looks a little bit different than the one that focuses on HTTP. The
+following sections explain the differences:
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'
// Label by means of which the output message can be triggered
@@ -1021,8 +1066,11 @@ have that information (e.g. in the stubs you’ll see that you have too call
header('BOOK-NAME', 'foo')
}
}
-}In this case the output message will be sent to output if a method called bookReturnedTriggered will be executed. In the message publisher’s side
-we will generate a test that will call that method to trigger the message. On the consumer side you can use the some_label to trigger the message.
The output message can be triggered by receiving a message.
def dsl = Contract.make {
+}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.
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'
// input is a message
@@ -1047,10 +1095,15 @@ we will generate a test that will call that method to trigger the message. On th
header('BOOK-NAME', 'foo')
}
}
-}In this case the output message will be sent to output if a proper message will be received on the input destination. In the message publisher’s side
-we will generate a test that will send the input message to the defined destination. On the consumer side you can either send a message to the input
-destination or use the some_label to trigger the message.
In HTTP you have a notion of client/stub and `server/test notation. You can use them also in messaging but we’re providing also the consumer and produer methods
-as presented below (note you can use either $ or value methods to provide consumer and producer parts)
Contract.make {
+}In the preceding example, the output message is sent to output if a proper message is
+received on the input destination. On the message publisher’s side, the engine
+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.
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
+parts):
Contract.make {
label 'some_label'
input {
messageFrom value(consumer('jms:output'), producer('jms:input'))
@@ -1067,7 +1120,8 @@ as presented below (note you can use either $ or 'foo'
])
}
-} You can define multiple contracts in one file. Such a contract might resemble the
+following example:
import org.springframework.cloud.contract.spec.Contract
[
Contract.make {
@@ -1089,8 +1143,8 @@ as presented below (note you can use either $ or 200
}
}
-]
In this example one contract has the name field and the other doesn’t. This will lead to generation of
-two tests that will look more or less like this:
package org.springframework.cloud.contract.verifier.tests.com.hello;
+]In the preceding example, one contract has the name field and the other does not. This
+leads to generation of two tests that look more or less like this:
package org.springframework.cloud.contract.verifier.tests.com.hello;
import com.example.TestBase;
import com.jayway.jsonpath.DocumentContext;
@@ -1131,11 +1185,11 @@ two tests that will look more or less like this:
assertThat(response.statusCode()).isEqualTo(200);
}
-}Notice that for the contract that has the name field the generated test method is named
-validate_should_post_a_user. For the one that doesn’t have the name it’s called
+}
Notice that, for the contract that has the name field, the generated test method is named
+validate_should_post_a_user. For the one that does not have the name, it is called
validate_withList_1. It corresponds to the name of the file WithList.groovy and the
-index of the contract in the list.
The generated stubs will look like this
should post a user.json
-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
-contract had index 1 in the list of contracts in the file).
![[Tip]](images/tip.png)
Tip As you can see it’s much better if you name your contracts since then your tests
- are far more meaningful.
\ No newline at end of file
+index of the contract in the list.The generated stubs is shown in the following example:
should post a user.json
+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]](images/tip.png)
Tip As you can see, it iss much better if you name your contracts because doing so makes
+your tests far more meaningful.