Files
spring-cloud-contract/reference/html/spring-cloud-contract-verifier.html
2019-08-07 09:56:28 +00:00

13993 lines
515 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.7.1">
<title>Spring Cloud Contract Verifier Introduction</title>
<link rel="stylesheet" href="css/spring.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.hidden {
display: none;
}
.switch {
border-width: 1px 1px 0 1px;
border-style: solid;
border-color: #7a2518;
display: inline-block;
}
.switch--item {
padding: 10px;
background-color: #ffffff;
color: #7a2518;
display: inline-block;
cursor: pointer;
}
.switch--item:not(:first-child) {
border-width: 0 0 0 1px;
border-style: solid;
border-color: #7a2518;
}
.switch--item.selected {
background-color: #7a2519;
color: #ffffff;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
<script type="text/javascript">
function addBlockSwitches() {
$('.primary').each(function() {
primary = $(this);
createSwitchItem(primary, createBlockSwitch(primary)).item.addClass("selected");
primary.children('.title').remove();
});
$('.secondary').each(function(idx, node) {
secondary = $(node);
primary = findPrimary(secondary);
switchItem = createSwitchItem(secondary, primary.children('.switch'));
switchItem.content.addClass('hidden');
findPrimary(secondary).append(switchItem.content);
secondary.remove();
});
}
function createBlockSwitch(primary) {
blockSwitch = $('<div class="switch"></div>');
primary.prepend(blockSwitch);
return blockSwitch;
}
function findPrimary(secondary) {
candidate = secondary.prev();
while (!candidate.is('.primary')) {
candidate = candidate.prev();
}
return candidate;
}
function createSwitchItem(block, blockSwitch) {
blockName = block.children('.title').text();
content = block.children('.content').first().append(block.next('.colist'));
item = $('<div class="switch--item">' + blockName + '</div>');
item.on('click', '', content, function(e) {
$(this).addClass('selected');
$(this).siblings().removeClass('selected');
e.data.siblings('.content').addClass('hidden');
e.data.removeClass('hidden');
});
blockSwitch.append(item);
return {'item': item, 'content': content};
}
$(addBlockSwitches);
</script>
</head>
<body class="book toc2 toc-left">
<div id="header">
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_spring_cloud_contract_verifier_introduction">Spring Cloud Contract Verifier Introduction</a>
<ul class="sectlevel2">
<li><a href="#_history">History</a></li>
<li><a href="#_why_a_contract_verifier">Why a Contract Verifier?</a></li>
<li><a href="#_purposes">Purposes</a></li>
<li><a href="#_how_it_works">How It Works</a></li>
<li><a href="#_step_by_step_guide_to_consumer_driven_contracts_cdc">Step-by-step Guide to Consumer Driven Contracts (CDC)</a></li>
<li><a href="#_dependencies">Dependencies</a></li>
<li><a href="#_additional_links">Additional Links</a></li>
<li><a href="#_samples">Samples</a></li>
</ul>
</li>
<li><a href="#_spring_cloud_contract_faq">Spring Cloud Contract FAQ</a>
<ul class="sectlevel2">
<li><a href="#_why_use_spring_cloud_contract_verifier_and_not_x">Why use Spring Cloud Contract Verifier and not X ?</a></li>
<li><a href="#_i_dont_want_to_write_a_contract_in_groovy">I don&#8217;t want to write a contract in Groovy!</a></li>
<li><a href="#_what_is_this_valueconsumer_producer">What is this value(consumer(), producer()) ?</a></li>
<li><a href="#_how_to_do_stubs_versioning">How to do Stubs versioning?</a></li>
<li><a href="#_common_repo_with_contracts">Common repo with contracts</a></li>
<li><a href="#_do_i_need_a_binary_storage_cant_i_use_git">Do I need a Binary Storage? Can&#8217;t I use Git?</a></li>
<li><a href="#_can_i_use_the_pact_broker">Can I use the Pact Broker?</a></li>
<li><a href="#_how_can_i_debug_the_requestresponse_being_sent_by_the_generated_tests_client">How can I debug the request/response being sent by the generated tests client?</a></li>
</ul>
</li>
<li><a href="#_spring_cloud_contract_verifier_setup">Spring Cloud Contract Verifier Setup</a>
<ul class="sectlevel2">
<li><a href="#gradle-project">Gradle Project</a></li>
<li><a href="#maven-project">Maven Project</a></li>
<li><a href="#_stubs_and_transitive_dependencies">Stubs and Transitive Dependencies</a></li>
<li><a href="#_scenarios">Scenarios</a></li>
<li><a href="#docker-project">Docker Project</a></li>
</ul>
</li>
<li><a href="#_spring_cloud_contract_verifier_messaging">Spring Cloud Contract Verifier Messaging</a>
<ul class="sectlevel2">
<li><a href="#_integrations">Integrations</a></li>
<li><a href="#_manual_integration_testing">Manual Integration Testing</a></li>
<li><a href="#_publisher_side_test_generation">Publisher-Side Test Generation</a></li>
<li><a href="#_consumer_stub_generation">Consumer Stub Generation</a></li>
</ul>
</li>
<li><a href="#_spring_cloud_contract_stub_runner">Spring Cloud Contract Stub Runner</a>
<ul class="sectlevel2">
<li><a href="#_snapshot_versions">Snapshot versions</a></li>
<li><a href="#publishing-stubs-as-jars">Publishing Stubs as JARs</a></li>
<li><a href="#_stub_runner_core">Stub Runner Core</a></li>
<li><a href="#_stub_runner_junit_rule_and_stub_runner_junit5_extension">Stub Runner JUnit Rule and Stub Runner JUnit5 Extension</a></li>
<li><a href="#_stub_runner_spring_cloud">Stub Runner Spring Cloud</a></li>
<li><a href="#_stub_runner_boot_application">Stub Runner Boot Application</a></li>
<li><a href="#_stubs_per_consumer">Stubs Per Consumer</a></li>
<li><a href="#_common">Common</a></li>
<li><a href="#stubrunner-docker">Stub Runner Docker</a></li>
</ul>
</li>
<li><a href="#stub-runner-for-messaging">Stub Runner for Messaging</a>
<ul class="sectlevel2">
<li><a href="#_stub_triggering">Stub triggering</a></li>
<li><a href="#_stub_runner_camel">Stub Runner Camel</a></li>
<li><a href="#_stub_runner_integration">Stub Runner Integration</a></li>
<li><a href="#_stub_runner_stream">Stub Runner Stream</a></li>
<li><a href="#_stub_runner_spring_amqp">Stub Runner Spring AMQP</a></li>
</ul>
</li>
<li><a href="#contract-dsl">Contract DSL</a>
<ul class="sectlevel2">
<li><a href="#_limitations">Limitations</a></li>
<li><a href="#_common_top_level_elements">Common Top-Level elements</a></li>
<li><a href="#_request">Request</a></li>
<li><a href="#_response">Response</a></li>
<li><a href="#_dynamic_properties">Dynamic properties</a></li>
<li><a href="#_jax_rs_support">JAX-RS Support</a></li>
<li><a href="#_async_support">Async Support</a></li>
<li><a href="#_working_with_context_paths">Working with Context Paths</a></li>
<li><a href="#_working_with_webflux">Working with WebFlux</a></li>
<li><a href="#_xml_support_for_rest">XML Support for REST</a></li>
<li><a href="#_messaging_top_level_elements">Messaging Top-Level Elements</a></li>
<li><a href="#_multiple_contracts_in_one_file">Multiple Contracts in One File</a></li>
<li><a href="#_generating_spring_rest_docs_snippets_from_the_contracts">Generating Spring REST Docs snippets from the contracts</a></li>
</ul>
</li>
<li><a href="#_customization">Customization</a>
<ul class="sectlevel2">
<li><a href="#_extending_the_dsl">Extending the DSL</a></li>
</ul>
</li>
<li><a href="#_using_the_pluggable_architecture">Using the Pluggable Architecture</a>
<ul class="sectlevel2">
<li><a href="#_custom_contract_converter">Custom Contract Converter</a></li>
<li><a href="#_using_the_custom_test_generator">Using the Custom Test Generator</a></li>
<li><a href="#_using_the_custom_stub_generator">Using the Custom Stub Generator</a></li>
<li><a href="#_using_the_custom_stub_runner">Using the Custom Stub Runner</a></li>
<li><a href="#_using_the_custom_stub_downloader">Using the Custom Stub Downloader</a></li>
<li><a href="#scm-stub-downloader">Using the SCM Stub Downloader</a></li>
<li><a href="#pact-stub-downloader">Using the Pact Stub Downloader</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier_introduction"><a class="link" href="#_spring_cloud_contract_verifier_introduction">Spring Cloud Contract Verifier Introduction</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of
JVM-based applications. It moves TDD to the level of software architecture.</p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier ships with <em>Contract Definition Language</em> (CDL). Contract
definitions are used to produce the following resources:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>JSON stub definitions to be used by WireMock when doing integration testing on the
client code (<em>client tests</em>). Test code must still be written by hand, and test data is
produced by Spring Cloud Contract Verifier.</p>
</li>
<li>
<p>Messaging routes, if you&#8217;re using a messaging service. We integrate with Spring
Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your
own integrations.</p>
</li>
<li>
<p>Acceptance tests (in JUnit 4, JUnit 5, TestNG or Spock) are used to verify if server-side implementation
of the API is compliant with the contract (<em>server tests</em>). A full test is generated by
Spring Cloud Contract Verifier.</p>
</li>
</ul>
</div>
<div class="sect2">
<h3 id="_history"><a class="link" href="#_history">History</a></h3>
<div class="paragraph">
<p>Before becoming Spring Cloud Contract, this project was called <a href="https://github.com/Codearte/accurest">Accurest</a>.
It was created by <a href="https://twitter.com/mgrzejszczak">Marcin Grzejszczak</a> and <a href="https://twitter.com/jkubrynski">Jakub Kubrynski</a>
from (<a href="https://github.com/Codearte">Codearte</a>.</p>
</div>
<div class="paragraph">
<p>The <code>0.1.0</code> release took place on 26 Jan 2015 and it became stable with <code>1.0.0</code> release on 29 Feb 2016.</p>
</div>
</div>
<div class="sect2">
<h3 id="_why_a_contract_verifier"><a class="link" href="#_why_a_contract_verifier">Why a Contract Verifier?</a></h3>
<div class="paragraph">
<p>Assume that we have a system consisting of multiple microservices:</p>
</div>
<div class="sect3">
<h4 id="_testing_issues"><a class="link" href="#_testing_issues">Testing issues</a></h4>
<div class="paragraph">
<p>If we wanted to test the application in top left corner to determine whether it can
communicate with other services, we could do one of two things:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Deploy all microservices and perform end-to-end tests.</p>
</li>
<li>
<p>Mock other microservices in unit/integration tests.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Both have their advantages but also a lot of disadvantages.</p>
</div>
<div class="paragraph">
<p><strong>Deploy all microservices and perform end to end tests</strong></p>
</div>
<div class="paragraph">
<p>Advantages:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Simulates production.</p>
</li>
<li>
<p>Tests real communication between services.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Disadvantages:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>To test one microservice, we have to deploy 6 microservices, a couple of databases,
etc.</p>
</li>
<li>
<p>The environment where the tests run is locked for a single suite of tests (nobody else
would be able to run the tests in the meantime).</p>
</li>
<li>
<p>They take a long time to run.</p>
</li>
<li>
<p>The feedback comes very late in the process.</p>
</li>
<li>
<p>They are extremely hard to debug.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>Mock other microservices in unit/integration tests</strong></p>
</div>
<div class="paragraph">
<p>Advantages:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>They provide very fast feedback.</p>
</li>
<li>
<p>They have no infrastructure requirements.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Disadvantages:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The implementor of the service creates stubs that might have nothing to do with
reality.</p>
</li>
<li>
<p>You can go to production with passing tests and failing production.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was
created. The main idea is to give you very fast feedback, without the need to set up the
whole world of microservices. If you work on stubs, then the only applications you need
are those that your application directly uses.</p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were
created by the service that you&#8217;re calling. Also, if you can use them, it means that they
were tested against the producer&#8217;s side. In short, you can trust those stubs.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_purposes"><a class="link" href="#_purposes">Purposes</a></h3>
<div class="paragraph">
<p>The main purposes of Spring Cloud Contract Verifier with Stub Runner are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>To ensure that WireMock/Messaging stubs (used when developing the client) do exactly
what the actual server-side implementation does.</p>
</li>
<li>
<p>To promote ATDD method and Microservices architectural style.</p>
</li>
<li>
<p>To provide a way to publish changes in contracts that are immediately visible on both
sides.</p>
</li>
<li>
<p>To generate boilerplate test code to be used on the server side.</p>
</li>
</ul>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Spring Cloud Contract Verifier&#8217;s purpose is NOT to start writing business
features in the contracts. Assume that we have a business use case of fraud check. If a
user can be a fraud for 100 different reasons, we would assume that you would create 2
contracts, one for the positive case and one for the negative case. Contract tests are
used to test contracts between applications and not to simulate full behavior.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_how_it_works"><a class="link" href="#_how_it_works">How It Works</a></h3>
<div class="paragraph">
<p>This section explores how Spring Cloud Contract Verifier with Stub Runner works.</p>
</div>
<div class="sect3">
<h4 id="spring-cloud-contract-verifier-intro-three-second-tour"><a class="link" href="#spring-cloud-contract-verifier-intro-three-second-tour">A Three-second Tour</a></h4>
<div class="paragraph">
<p>This very brief tour walks through using Spring Cloud Contract:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#spring-cloud-contract-verifier-intro-three-second-tour-producer">On the Producer Side</a></p>
</li>
<li>
<p><a href="#spring-cloud-contract-verifier-intro-three-second-tour-consumer">On the Consumer Side</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can find a somewhat longer tour
<a href="#spring-cloud-contract-verifier-intro-three-minute-tour">here</a>.</p>
</div>
<div class="sect4">
<h5 id="spring-cloud-contract-verifier-intro-three-second-tour-producer"><a class="link" href="#spring-cloud-contract-verifier-intro-three-second-tour-producer">On the Producer Side</a></h5>
<div class="paragraph">
<p>To start working with Spring Cloud Contract, add files with <code>REST/</code> messaging contracts
expressed in either Groovy DSL or YAML to the contracts directory, which is set by the
<code>contractsDslDir</code> property. By default, it is <code>$rootDir/src/test/resources/contracts</code>.</p>
</div>
<div class="paragraph">
<p>Then add the Spring Cloud Contract Verifier dependency and plugin to your build file, as
shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-verifier&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following listing shows how to add the plugin, which should go in the build/plugins
portion of the file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Running <code>./mvnw clean install</code> automatically generates tests that verify the application
compliance with the added contracts. By default, the tests get generated under
<code>org.springframework.cloud.contract.verifier.tests.</code>.</p>
</div>
<div class="paragraph">
<p>As the implementation of the functionalities described by the contracts is not yet
present, the tests fail.</p>
</div>
<div class="paragraph">
<p>To make them pass, you must add the correct implementation of either handling HTTP
requests or messages. Also, you must add a correct base test class for auto-generated
tests to the project. This class is extended by all the auto-generated tests, and it
should contain all the setup necessary to run them (for example <code>RestAssuredMockMvc</code>
controller setup or messaging test setup).</p>
</div>
<div class="paragraph">
<p>Once the implementation and the test base class are in place, the tests pass, and both the
application and the stub artifacts are built and installed in the local Maven repository.
The changes can now be merged, and both the application and the stub artifacts may be
published in an online repository.</p>
</div>
</div>
<div class="sect4">
<h5 id="spring-cloud-contract-verifier-intro-three-second-tour-consumer"><a class="link" href="#spring-cloud-contract-verifier-intro-three-second-tour-consumer">On the Consumer Side</a></h5>
<div class="paragraph">
<p><code>Spring Cloud Contract Stub Runner</code> can be used in the integration tests to get a running
WireMock instance or messaging route that simulates the actual service.</p>
</div>
<div class="paragraph">
<p>To do so, add the dependency to <code>Spring Cloud Contract Stub Runner</code>, as shown in the
following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can get the Producer-side stubs installed in your Maven repository in either of two
ways:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>By checking out the Producer side repository and adding contracts and generating the stubs
by running the following commands:</p>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
The tests are being skipped because the Producer-side contract implementation is not
in place yet, so the automatically-generated contract tests fail.
</td>
</tr>
</table>
</div>
</li>
<li>
<p>By getting already-existing producer service stubs from a remote repository. To do so,
pass the stub artifact IDs and artifact repository URL as <code>Spring Cloud Contract
Stub Runner</code> properties, as shown in the following example:</p>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"></code></pre>
</div>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>Now you can annotate your test class with <code>@AutoConfigureStubRunner</code>. In the annotation,
provide the <code>group-id</code> and <code>artifact-id</code> values for <code>Spring Cloud Contract Stub Runner</code> to
run the collaborators' stubs for you, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Use the <code>REMOTE</code> <code>stubsMode</code> when downloading stubs from an online repository and
<code>LOCAL</code> for offline work.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Now, in your integration test, you can receive stubbed versions of HTTP responses or
messages that are expected to be emitted by the collaborator service.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="spring-cloud-contract-verifier-intro-three-minute-tour"><a class="link" href="#spring-cloud-contract-verifier-intro-three-minute-tour">A Three-minute Tour</a></h4>
<div class="paragraph">
<p>This brief tour walks through using Spring Cloud Contract:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#spring-cloud-contract-verifier-intro-three-minute-tour-producer">On the Producer Side</a></p>
</li>
<li>
<p><a href="#spring-cloud-contract-verifier-intro-three-minute-tour-consumer">On the Consumer Side</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can find an even more brief tour
<a href="#spring-cloud-contract-verifier-intro-three-second-tour">here</a>.</p>
</div>
<div class="sect4">
<h5 id="spring-cloud-contract-verifier-intro-three-minute-tour-producer"><a class="link" href="#spring-cloud-contract-verifier-intro-three-minute-tour-producer">On the Producer Side</a></h5>
<div class="paragraph">
<p>To start working with <code>Spring Cloud Contract</code>, add files with <code>REST/</code> messaging contracts
expressed in either Groovy DSL or YAML to the contracts directory, which is set by the
<code>contractsDslDir</code> property. By default, it is <code>$rootDir/src/test/resources/contracts</code>.</p>
</div>
<div class="paragraph">
<p>For the HTTP stubs, a contract defines what kind of response should be returned for a
given request (taking into account the HTTP methods, URLs, headers, status codes, and so
on). The following example shows how an HTTP stub contract in Groovy DSL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package contracts
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/fraudcheck'
body([
"client.id": $(regex('[0-9]{10}')),
loanAmount: 99999
])
headers {
contentType('application/json')
}
}
response {
status OK()
body([
fraudCheckStatus: "FRAUD",
"rejection.reason": "Amount too high"
])
headers {
contentType('application/json')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same contract expressed in YAML would look like the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">request:
method: PUT
url: /fraudcheck
body:
"client.id": 1234567890
loanAmount: 99999
headers:
Content-Type: application/json
matchers:
body:
- path: $.['client.id']
type: by_regex
value: "[0-9]{10}"
response:
status: 200
body:
fraudCheckStatus: "FRAUD"
"rejection.reason": "Amount too high"
headers:
Content-Type: application/json;charset=UTF-8</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the case of messaging, you can define:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The input and the output messages can be defined (taking into account from and where it
was sent, the message body, and the header).</p>
</li>
<li>
<p>The methods that should be called after the message is received.</p>
</li>
<li>
<p>The methods that, when called, should trigger a message.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The following example shows a Camel messaging contract expressed in Groovy DSL:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> def contractDsl = Contract.make {
name "foo"
label 'some_label'
input {
messageFrom('jms:delete')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
assertThat('bookWasDeleted()')
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows the same contract expressed in YAML:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">label: some_label
input:
messageFrom: jms:delete
messageBody:
bookName: 'foo'
messageHeaders:
sample: header
assertThat: bookWasDeleted()</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then you can add Spring Cloud Contract Verifier dependency and plugin to your build file,
as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-verifier&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following listing shows how to add the plugin, which should go in the build/plugins
portion of the file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Running <code>./mvnw clean install</code> automatically generates tests that verify the application
compliance with the added contracts. By default, the generated tests are under
<code>org.springframework.cloud.contract.verifier.tests.</code>.</p>
</div>
<div class="paragraph">
<p>The following example shows a sample auto-generated test for an HTTP contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The preceding example uses Spring&#8217;s <code>MockMvc</code> to run the tests. This is the default test
mode for HTTP contracts. However, JAX-RS client and explicit HTTP invocations can also be
used. (To do so, change the <code>testMode</code> property of the plugin to <code>JAX-RS</code> or <code>EXPLICIT</code>,
respectively.)</p>
</div>
<div class="paragraph">
<p>Since 2.1.0, it is also possible to use <code>RestAssuredWebTestClient`with Spring&#8217;s reactive `WebTestClient</code>
run under the hood. This is particularly recommended while working with Reactive, <code>Web-Flux</code>-based applications.
In order to use <code>WebTestClient</code> set <code>testMode</code> to <code>WEBTESTCLIENT</code>.</p>
</div>
<div class="paragraph">
<p>Here is an example of a test generated in <code>WEBTESTCLIENT</code> test mode:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>[source,java,indent=0]</pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre>@Test
public void validate_shouldRejectABeerIfTooYoung() throws Exception {
// given:
WebTestClientRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"age\":10}");
// when:
WebTestClientResponse response = given().spec(request)
.post("/check");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['status']").isEqualTo("NOT_OK");
}</pre>
</div>
</div>
<div class="paragraph">
<p>Apart from the default JUnit 4, you can instead use JUnit 5, TestNG or Spock tests, by setting the plugin
<code>testFramework</code> property to either <code>JUNIT5</code>, <code>TESTNG</code> or <code>Spock</code>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You can now also generate WireMock scenarios based on the contracts, by including an
order number followed by an underscore at the beginning of the contract file names.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following example shows an auto-generated test in Spock for a messaging stub contract:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>[source,groovy,indent=0]</pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre>given:
ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
\'\'\'{"bookName":"foo"}\'\'\',
['sample': 'header']
)
when:
contractVerifierMessaging.send(inputMessage, 'jms:delete')
then:
noExceptionThrown()
bookWasDeleted()</pre>
</div>
</div>
<div class="paragraph">
<p>As the implementation of the functionalities described by the contracts is not yet
present, the tests fail.</p>
</div>
<div class="paragraph">
<p>To make them pass, you must add the correct implementation of handling either HTTP
requests or messages. Also, you must add a correct base test class for auto-generated
tests to the project. This class is extended by all the auto-generated tests and should
contain all the setup necessary to run them (for example, <code>RestAssuredMockMvc</code> controller
setup or messaging test setup).</p>
</div>
<div class="paragraph">
<p>Once the implementation and the test base class are in place, the tests pass, and both the
application and the stub artifacts are built and installed in the local Maven repository.
Information about installing the stubs jar to the local repository appears in the logs, as
shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can now merge the changes and publish both the application and the stub artifacts
in an online repository.</p>
</div>
<div class="paragraph">
<p><strong>Docker Project</strong></p>
</div>
<div class="paragraph">
<p>In order to enable working with contracts while creating applications in non-JVM
technologies, the <code>springcloud/spring-cloud-contract</code> Docker image has been created. It
contains a project that automatically generates tests for HTTP contracts and executes them
in <code>EXPLICIT</code> test mode. Then, if the tests pass, it generates Wiremock stubs and,
optionally, publishes them to an artifact manager. In order to use the image, you can
mount the contracts into the <code>/contracts</code> directory and set a few environment variables.</p>
</div>
</div>
<div class="sect4">
<h5 id="spring-cloud-contract-verifier-intro-three-minute-tour-consumer"><a class="link" href="#spring-cloud-contract-verifier-intro-three-minute-tour-consumer">On the Consumer Side</a></h5>
<div class="paragraph">
<p><code>Spring Cloud Contract Stub Runner</code> can be used in the integration tests to get a running
WireMock instance or messaging route that simulates the actual service.</p>
</div>
<div class="paragraph">
<p>To get started, add the dependency to <code>Spring Cloud Contract Stub Runner</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can get the Producer-side stubs installed in your Maven repository in either of two
ways:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>By checking out the Producer side repository and adding contracts and generating the
stubs by running the following commands:</p>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The tests are skipped because the Producer-side contract implementation is not yet
in place, so the automatically-generated contract tests fail.
</td>
</tr>
</table>
</div>
</li>
<li>
<p>Getting already existing producer service stubs from a remote repository. To do so,
pass the stub artifact IDs and artifact repository URl as <code>Spring Cloud Contract Stub
Runner</code> properties, as shown in the following example:</p>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"></code></pre>
</div>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>Now you can annotate your test class with <code>@AutoConfigureStubRunner</code>. In the annotation,
provide the <code>group-id</code> and <code>artifact-id</code> for <code>Spring Cloud Contract Stub Runner</code> to run
the collaborators' stubs for you, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Use the <code>REMOTE</code> <code>stubsMode</code> when downloading stubs from an online repository and
<code>LOCAL</code> for offline work.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>In your integration test, you can receive stubbed versions of HTTP responses or messages
that are expected to be emitted by the collaborator service. You can see entries similar
to the following in the build logs:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_defining_the_contract"><a class="link" href="#_defining_the_contract">Defining the Contract</a></h4>
<div class="paragraph">
<p>As consumers of services, we need to define what exactly we want to achieve. We need to
formulate our expectations. That is why we write contracts.</p>
</div>
<div class="paragraph">
<p>Assume that you want to send a request containing the ID of a client company and the
amount it wants to borrow from us. You also want to send it to the /fraudcheck url via
the PUT method.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package contracts
org.springframework.cloud.contract.spec.Contract.make {
request { // (1)
method 'PUT' // (2)
url '/fraudcheck' // (3)
body([ // (4)
"client.id": $(regex('[0-9]{10}')),
loanAmount : 99999
])
headers { // (5)
contentType('application/json')
}
}
response { // (6)
status OK() // (7)
body([ // (8)
fraudCheckStatus : "FRAUD",
"rejection.reason": "Amount too high"
])
headers { // (9)
contentType('application/json')
}
}
}
/*
From the Consumer perspective, when shooting a request in the integration test:
(1) - If the consumer sends a request
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the response will be sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` equal to `application/json`
From the Producer perspective, in the autogenerated producer-side test:
(1) - A request will be sent to the producer
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the test will assert if the response has been sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` matching `application/json.*`
*/</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request: # (1)
method: PUT # (2)
url: /fraudcheck # (3)
body: # (4)
"client.id": 1234567890
loanAmount: 99999
headers: # (5)
Content-Type: application/json
matchers:
body:
- path: $.['client.id'] # (6)
type: by_regex
value: "[0-9]{10}"
response: # (7)
status: 200 # (8)
body: # (9)
fraudCheckStatus: "FRAUD"
"rejection.reason": "Amount too high"
headers: # (10)
Content-Type: application/json
#From the Consumer perspective, when shooting a request in the integration test:
#
#(1) - If the consumer sends a request
#(2) - With the "PUT" method
#(3) - to the URL "/fraudcheck"
#(4) - with the JSON body that
# * has a field `client.id`
# * has a field `loanAmount` that is equal to `99999`
#(5) - with header `Content-Type` equal to `application/json`
#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
#(7) - then the response will be sent with
#(8) - status equal `200`
#(9) - and JSON body equal to
# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
#(10) - with header `Content-Type` equal to `application/json`
#
#From the Producer perspective, in the autogenerated producer-side test:
#
#(1) - A request will be sent to the producer
#(2) - With the "PUT" method
#(3) - to the URL "/fraudcheck"
#(4) - with the JSON body that
# * has a field `client.id` `1234567890`
# * has a field `loanAmount` that is equal to `99999`
#(5) - with header `Content-Type` equal to `application/json`
#(7) - then the test will assert if the response has been sent with
#(8) - status equal `200`
#(9) - and JSON body equal to
# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
#(10) - with header `Content-Type` equal to `application/json`</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_client_side"><a class="link" href="#_client_side">Client Side</a></h4>
<div class="paragraph">
<p>Spring Cloud Contract generates stubs, which you can use during client-side testing.
You get a running WireMock instance/Messaging route that simulates the service.
You would like to feed that instance with a proper stub definition.</p>
</div>
<div class="paragraph">
<p>At some point in time, you need to send a request to the Fraud Detection service.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ResponseEntity&lt;FraudServiceResponse&gt; response = restTemplate.exchange(
"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
new HttpEntity&lt;&gt;(request, httpHeaders), FraudServiceResponse.class);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Annotate your test class with <code>@AutoConfigureStubRunner</code>. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {
"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {</code></pre>
</div>
</div>
<div class="paragraph">
<p>After that, during the tests, Spring Cloud Contract automatically finds the stubs
(simulating the real service) in the Maven repository and exposes them on a configured
(or random) port.</p>
</div>
</div>
<div class="sect3">
<h4 id="_server_side"><a class="link" href="#_server_side">Server Side</a></h4>
<div class="paragraph">
<p>Since you are developing your stub, you need to be sure that it actually resembles your
concrete implementation. You cannot have a situation where your stub acts in one way and
your application behaves in a different way, especially in production.</p>
</div>
<div class="paragraph">
<p>To ensure that your application behaves the way you define in your stub, tests are
generated from the stub you provide.</p>
</div>
<div class="paragraph">
<p>The autogenerated test looks, more or less, like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_step_by_step_guide_to_consumer_driven_contracts_cdc"><a class="link" href="#_step_by_step_guide_to_consumer_driven_contracts_cdc">Step-by-step Guide to Consumer Driven Contracts (CDC)</a></h3>
<div class="paragraph">
<p>Consider an example of Fraud Detection and the Loan Issuance process. The business
scenario is such that we want to issue loans to people but do not want them to steal from
us. The current implementation of our system grants loans to everybody.</p>
</div>
<div class="paragraph">
<p>Assume that <code>Loan Issuance</code> is a client to the <code>Fraud Detection</code> server. In the current
sprint, we must develop a new feature: if a client wants to borrow too much money, then
we mark the client as a fraud.</p>
</div>
<div class="paragraph">
<p>Technical remark - Fraud Detection has an <code>artifact-id</code> of <code>http-server</code>, while Loan
Issuance has an artifact-id of <code>http-client</code>, and both have a <code>group-id</code> of <code>com.example</code>.</p>
</div>
<div class="paragraph">
<p>Social remark - both client and server development teams need to communicate directly and
discuss changes while going through the process. CDC is all about communication.</p>
</div>
<div class="paragraph">
<p>The <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server">server
side code is available here</a> and <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client">the
client code here</a>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
In this case, the producer owns the contracts. Physically, all the contract are
in the producer&#8217;s repository.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_technical_note"><a class="link" href="#_technical_note">Technical note</a></h4>
<div class="paragraph">
<p>If using the <strong>SNAPSHOT</strong> / <strong>Milestone</strong> / <strong>Release Candidate</strong> versions please add the
following section to your build:</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">repositories {
mavenCentral()
mavenLocal()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/release" }
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_consumer_side_loan_issuance"><a class="link" href="#_consumer_side_loan_issuance">Consumer side (Loan Issuance)</a></h4>
<div class="paragraph">
<p>As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Start doing TDD by writing a test for your feature.</p>
</li>
<li>
<p>Write the missing implementation.</p>
</li>
<li>
<p>Clone the Fraud Detection service repository locally.</p>
</li>
<li>
<p>Define the contract locally in the repo of Fraud Detection service.</p>
</li>
<li>
<p>Add the Spring Cloud Contract Verifier plugin.</p>
</li>
<li>
<p>Run the integration tests.</p>
</li>
<li>
<p>File a pull request.</p>
</li>
<li>
<p>Create an initial implementation.</p>
</li>
<li>
<p>Take over the pull request.</p>
</li>
<li>
<p>Write the missing implementation.</p>
</li>
<li>
<p>Deploy your app.</p>
</li>
<li>
<p>Work online.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p><strong>Start doing TDD by writing a test for your feature.</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@Test
public void shouldBeRejectedDueToAbnormalLoanAmount() {
// given:
LoanApplication application = new LoanApplication(new Client("1234567890"),
99999);
// when:
LoanApplicationResult loanApplication = service.loanApplication(application);
// then:
assertThat(loanApplication.getLoanApplicationStatus())
.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Assume that you have written a test of your new feature. If a loan application for a big
amount is received, the system should reject that loan application with some description.</p>
</div>
<div class="paragraph">
<p><strong>Write the missing implementation.</strong></p>
</div>
<div class="paragraph">
<p>At some point in time, you need to send a request to the Fraud Detection service. Assume
that you need to send the request containing the ID of the client and the amount the
client wants to borrow. You want to send it to the <code>/fraudcheck</code> url via the <code>PUT</code> method.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ResponseEntity&lt;FraudServiceResponse&gt; response = restTemplate.exchange(
"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
new HttpEntity&lt;&gt;(request, httpHeaders), FraudServiceResponse.class);</code></pre>
</div>
</div>
<div class="paragraph">
<p>For simplicity, the port of the Fraud Detection service is set to <code>8080</code>, and the
application runs on <code>8090</code>.</p>
</div>
<div class="paragraph">
<p>If you start the test at this point, it breaks, because no service currently runs on port
<code>8080</code>.</p>
</div>
<div class="paragraph">
<p><strong>Clone the Fraud Detection service repository locally.</strong></p>
</div>
<div class="paragraph">
<p>You can start by playing around with the server side contract. To do so, you must first
clone it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git clone https://your-git-server.com/server-side.git local-http-server-repo</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Define the contract locally in the repo of Fraud Detection service.</strong></p>
</div>
<div class="paragraph">
<p>As a consumer, you need to define what exactly you want to achieve. You need to formulate
your expectations. To do so, write the following contract:</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Place the contract under <code>src/test/resources/contracts/fraud</code> folder. The <code>fraud</code> folder
is important because the producer&#8217;s test base class name references that folder.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package contracts
org.springframework.cloud.contract.spec.Contract.make {
request { // (1)
method 'PUT' // (2)
url '/fraudcheck' // (3)
body([ // (4)
"client.id": $(regex('[0-9]{10}')),
loanAmount : 99999
])
headers { // (5)
contentType('application/json')
}
}
response { // (6)
status OK() // (7)
body([ // (8)
fraudCheckStatus : "FRAUD",
"rejection.reason": "Amount too high"
])
headers { // (9)
contentType('application/json')
}
}
}
/*
From the Consumer perspective, when shooting a request in the integration test:
(1) - If the consumer sends a request
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the response will be sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` equal to `application/json`
From the Producer perspective, in the autogenerated producer-side test:
(1) - A request will be sent to the producer
(2) - With the "PUT" method
(3) - to the URL "/fraudcheck"
(4) - with the JSON body that
* has a field `client.id` that will have a generated value that matches a regular expression `[0-9]{10}`
* has a field `loanAmount` that is equal to `99999`
(5) - with header `Content-Type` equal to `application/json`
(6) - then the test will assert if the response has been sent with
(7) - status equal `200`
(8) - and JSON body equal to
{ "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
(9) - with header `Content-Type` matching `application/json.*`
*/</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request: # (1)
method: PUT # (2)
url: /fraudcheck # (3)
body: # (4)
"client.id": 1234567890
loanAmount: 99999
headers: # (5)
Content-Type: application/json
matchers:
body:
- path: $.['client.id'] # (6)
type: by_regex
value: "[0-9]{10}"
response: # (7)
status: 200 # (8)
body: # (9)
fraudCheckStatus: "FRAUD"
"rejection.reason": "Amount too high"
headers: # (10)
Content-Type: application/json
#From the Consumer perspective, when shooting a request in the integration test:
#
#(1) - If the consumer sends a request
#(2) - With the "PUT" method
#(3) - to the URL "/fraudcheck"
#(4) - with the JSON body that
# * has a field `client.id`
# * has a field `loanAmount` that is equal to `99999`
#(5) - with header `Content-Type` equal to `application/json`
#(6) - and a `client.id` json entry matches the regular expression `[0-9]{10}`
#(7) - then the response will be sent with
#(8) - status equal `200`
#(9) - and JSON body equal to
# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
#(10) - with header `Content-Type` equal to `application/json`
#
#From the Producer perspective, in the autogenerated producer-side test:
#
#(1) - A request will be sent to the producer
#(2) - With the "PUT" method
#(3) - to the URL "/fraudcheck"
#(4) - with the JSON body that
# * has a field `client.id` `1234567890`
# * has a field `loanAmount` that is equal to `99999`
#(5) - with header `Content-Type` equal to `application/json`
#(7) - then the test will assert if the response has been sent with
#(8) - status equal `200`
#(9) - and JSON body equal to
# { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
#(10) - with header `Content-Type` equal to `application/json`</code></pre>
</div>
</div>
<div class="paragraph">
<p>The YML contract is quite straight-forward. However when you take a look at the Contract
written using a statically typed Groovy DSL - you might wonder what the
<code>value(client(&#8230;&#8203;), server(&#8230;&#8203;))</code> parts are. By using this notation, Spring Cloud
Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case
of an identifier or a timestamp, you need not hardcode a value. You want to allow some
different ranges of values. To enable ranges of values, you can set regular expressions
matching those values for the consumer side. You can provide the body by means of either
a map notation or String with interpolations.
Consult the <a href="#contract-dsl">Contract DSL</a> section for more information. We highly recommend using the map notation!</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You must understand the map notation in order to set up contracts. Please read the
<a href="https://groovy-lang.org/json.html">Groovy docs regarding JSON</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The previously shown contract is an agreement between two sides that:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>if an HTTP request is sent with all of</p>
<div class="ulist">
<ul>
<li>
<p>a <code>PUT</code> method on the <code>/fraudcheck</code> endpoint,</p>
</li>
<li>
<p>a JSON body with a <code>client.id</code> that matches the regular expression <code>[0-9]{10}</code> and
<code>loanAmount</code> equal to <code>99999</code>,</p>
</li>
<li>
<p>and a <code>Content-Type</code> header with a value of <code>application/vnd.fraud.v1+json</code>,</p>
</li>
</ul>
</div>
</li>
<li>
<p>then an HTTP response is sent to the consumer that</p>
<div class="ulist">
<ul>
<li>
<p>has status <code>200</code>,</p>
</li>
<li>
<p>contains a JSON body with the <code>fraudCheckStatus</code> field containing a value <code>FRAUD</code> and
the <code>rejectionReason</code> field having value <code>Amount too high</code>,</p>
</li>
<li>
<p>and a <code>Content-Type</code> header with a value of <code>application/vnd.fraud.v1+json</code>.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>Once you are ready to check the API in practice in the integration tests, you need to
install the stubs locally.</p>
</div>
<div class="paragraph">
<p><strong>Add the Spring Cloud Contract Verifier plugin.</strong></p>
</div>
<div class="paragraph">
<p>We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven.
First, add the <code>Spring Cloud Contract</code> BOM.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-release.version}&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next, add the <code>Spring Cloud Contract Verifier</code> Maven plugin</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example.fraud&lt;/packageWithBaseClasses&gt;
&lt;convertToYaml&gt;true&lt;/convertToYaml&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Since the plugin was added, you get the <code>Spring Cloud Contract Verifier</code> features which,
from the provided contracts:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>generate and run tests</p>
</li>
<li>
<p>produce and install stubs</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You do not want to generate tests since you, as the consumer, want only to play with the
stubs. You need to skip the test generation and execution. When you execute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ cd local-http-server-repo
$ ./mvnw clean install -DskipTests</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the logs, you see something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following line is extremely important:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar</code></pre>
</div>
</div>
<div class="paragraph">
<p>It confirms that the stubs of the <code>http-server</code> have been installed in the local
repository.</p>
</div>
<div class="paragraph">
<p><strong>Run the integration tests.</strong></p>
</div>
<div class="paragraph">
<p>In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic
stub downloading, you must do the following in your consumer side project (<code>Loan
Application service</code>):</p>
</div>
<div class="paragraph">
<p>Add the <code>Spring Cloud Contract</code> BOM:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-release-train.version}&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Add the dependency to <code>Spring Cloud Contract Stub Runner</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Annotate your test class with <code>@AutoConfigureStubRunner</code>. In the annotation, provide the
<code>group-id</code> and <code>artifact-id</code> for the Stub Runner to download the stubs of your
collaborators. (Optional step) Because you&#8217;re playing with the collaborators offline, you
can also provide the offline work switch (<code>StubRunnerProperties.StubsMode.LOCAL</code>).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {
"com.example:http-server-dsl:+:stubs:6565" }, stubsMode = StubRunnerProperties.StubsMode.LOCAL)
public class LoanApplicationServiceTests {</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now, when you run your tests, you see something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]</code></pre>
</div>
</div>
<div class="paragraph">
<p>This output means that Stub Runner has found your stubs and started a server for your app
with group id <code>com.example</code>, artifact id <code>http-server</code> with version <code>0.0.1-SNAPSHOT</code> of
the stubs and with <code>stubs</code> classifier on port <code>8080</code>.</p>
</div>
<div class="paragraph">
<p><strong>File a pull request.</strong></p>
</div>
<div class="paragraph">
<p>What you have done until now is an iterative process. You can play around with the
contract, install it locally, and work on the consumer side until the contract works as
you wish.</p>
</div>
<div class="paragraph">
<p>Once you are satisfied with the results and the test passes, publish a pull request to
the server side. Currently, the consumer side work is done.</p>
</div>
</div>
<div class="sect3">
<h4 id="_producer_side_fraud_detection_server"><a class="link" href="#_producer_side_fraud_detection_server">Producer side (Fraud Detection server)</a></h4>
<div class="paragraph">
<p>As a developer of the Fraud Detection server (a server to the Loan Issuance service):</p>
</div>
<div class="paragraph">
<p><strong>Create an initial implementation.</strong></p>
</div>
<div class="paragraph">
<p>As a reminder, you can see the initial implementation here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RequestMapping(value = "/fraudcheck", method = PUT)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Take over the pull request.</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git checkout -b contract-change-pr master
$ git pull https://your-git-server.com/server-side-fork.git contract-change-pr</code></pre>
</div>
</div>
<div class="paragraph">
<p>You must add the dependencies needed by the autogenerated tests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-verifier&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the configuration of the Maven plugin, pass the <code>packageWithBaseClasses</code> property</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example.fraud&lt;/packageWithBaseClasses&gt;
&lt;convertToYaml&gt;true&lt;/convertToYaml&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This example uses "convention based" naming by setting the
<code>packageWithBaseClasses</code> property. Doing so means that the two last packages combine to
make the name of the base test class. In our case, the contracts were placed under
<code>src/test/resources/contracts/fraud</code>. Since you do not have two packages starting from
the <code>contracts</code> folder, pick only one, which should be <code>fraud</code>. Add the <code>Base</code> suffix and
capitalize <code>fraud</code>. That gives you the <code>FraudBase</code> test class name.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>All the generated tests extend that class. Over there, you can set up your Spring Context
or whatever is necessary. In this case, use <a href="https://github.com/rest-assured/rest-assured">Rest Assured MVC</a> to
start the server side <code>FraudDetectionController</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.fraud;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
public class FraudBase {
@Before
public void setup() {
RestAssuredMockMvc.standaloneSetup(new FraudDetectionController(),
new FraudStatsController(stubbedStatsProvider()));
}
private StatsProvider stubbedStatsProvider() {
return fraudType -&gt; {
switch (fraudType) {
case DRUNKS:
return 100;
case ALL:
return 200;
}
return 0;
};
}
public void assertThatRejectionReasonIsNull(Object rejectionReason) {
assert rejectionReason == null;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now, if you run the <code>./mvnw clean install</code>, you get something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">Results :
Tests in error:
ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...</code></pre>
</div>
</div>
<div class="paragraph">
<p>This error occurs because you have a new contract from which a test was generated and it
failed since you have not implemented the feature. The auto-generated test would look
like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you used the Groovy DSL, you can see, all the <code>producer()</code> parts of the Contract that were present in the
<code>value(consumer(&#8230;&#8203;), producer(&#8230;&#8203;))</code> blocks got injected into the test.
In case of using YAML, the same applied for the <code>matchers</code> sections of the <code>response</code>.</p>
</div>
<div class="paragraph">
<p>Note that, on the producer side, you are also doing TDD. The expectations are expressed
in the form of a test. This test sends a request to our own application with the URL,
headers, and body defined in the contract. It also is expecting precisely defined values
in the response. In other words, you have the <code>red</code> part of <code>red</code>, <code>green</code>, and
<code>refactor</code>. It is time to convert the <code>red</code> into the <code>green</code>.</p>
</div>
<div class="paragraph">
<p><strong>Write the missing implementation.</strong></p>
</div>
<div class="paragraph">
<p>Because you know the expected input and expected output, you can write the missing
implementation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RequestMapping(value = "/fraudcheck", method = PUT)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
if (amountGreaterThanThreshold(fraudCheck)) {
return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
}
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When you execute <code>./mvnw clean install</code> again, the tests pass. Since the <code>Spring Cloud
Contract Verifier</code> plugin adds the tests to the <code>generated-test-sources</code>, you can
actually run those tests from your IDE.</p>
</div>
<div class="paragraph">
<p><strong>Deploy your app.</strong></p>
</div>
<div class="paragraph">
<p>Once you finish your work, you can deploy your change. First, merge the branch:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git checkout master
$ git merge --no-ff contract-change-pr
$ git push origin master</code></pre>
</div>
</div>
<div class="paragraph">
<p>Your CI might run something like <code>./mvnw clean deploy</code>, which would publish both the
application and the stub artifacts.</p>
</div>
</div>
<div class="sect3">
<h4 id="_consumer_side_loan_issuance_final_step"><a class="link" href="#_consumer_side_loan_issuance_final_step">Consumer Side (Loan Issuance) Final Step</a></h4>
<div class="paragraph">
<p>As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):</p>
</div>
<div class="paragraph">
<p><strong>Merge branch to master.</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git checkout master
$ git merge --no-ff contract-change-pr</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Work online.</strong></p>
</div>
<div class="paragraph">
<p>Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate
where the repository with your stubs is located. At this moment the stubs of the server
side are automatically downloaded from Nexus/Artifactory. You can set the value of
<code>stubsMode</code> to <code>REMOTE</code>. The following code shows an example of
achieving the same thing by changing the properties.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml"></code></pre>
</div>
</div>
<div class="paragraph">
<p>That&#8217;s it!</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_dependencies"><a class="link" href="#_dependencies">Dependencies</a></h3>
<div class="paragraph">
<p>The best way to add dependencies is to use the proper <code>starter</code> dependency.</p>
</div>
<div class="paragraph">
<p>For <code>stub-runner</code>, use <code>spring-cloud-starter-stub-runner</code>. When you use a plugin, add
<code>spring-cloud-starter-contract-verifier</code>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_additional_links"><a class="link" href="#_additional_links">Additional Links</a></h3>
<div class="paragraph">
<p>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.</p>
</div>
<div class="sect3">
<h4 id="_spring_cloud_contract_video"><a class="link" href="#_spring_cloud_contract_video">Spring Cloud Contract video</a></h4>
<div class="paragraph">
<p>You can check out the video from the Warsaw JUG about Spring Cloud Contract:</p>
</div>
<div class="videoblock">
<div class="content">
<iframe width="640" height="480" src="https://www.youtube.com/embed/sAAklvxmPmk?rel=0&amp;start=538" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_readings"><a class="link" href="#_readings">Readings</a></h4>
<div class="ulist">
<ul>
<li>
<p><a href="https://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura">Slides from Marcin Grzejszczak&#8217;s talk about Accurest</a></p>
</li>
<li>
<p><a href="https://toomuchcoding.com/blog/categories/accurest/">Accurest related articles from Marcin Grzejszczak&#8217;s blog</a></p>
</li>
<li>
<p><a href="https://toomuchcoding.com/blog/categories/spring-cloud-contract/">Spring Cloud Contract related articles from Marcin Grzejszczak&#8217;s blog</a></p>
</li>
<li>
<p><a href="https://groovy-lang.org/json.html">Groovy docs regarding JSON</a></p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_samples"><a class="link" href="#_samples">Samples</a></h3>
<div class="paragraph">
<p>You can find some samples at
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples">samples</a>.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_faq"><a class="link" href="#_spring_cloud_contract_faq">Spring Cloud Contract FAQ</a></h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_why_use_spring_cloud_contract_verifier_and_not_x"><a class="link" href="#_why_use_spring_cloud_contract_verifier_and_not_x">Why use Spring Cloud Contract Verifier and not X ?</a></h3>
<div class="paragraph">
<p>For the time being Spring Cloud Contract is a JVM based tool. So it could be your first pick when you&#8217;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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Possibility to do CDC with messaging</p>
</li>
<li>
<p>Clear and easy to use, statically typed DSL</p>
</li>
<li>
<p>Possibility to copy paste your current JSON file to the contract and only edit its elements</p>
</li>
<li>
<p>Automatic generation of tests from the defined Contract</p>
</li>
<li>
<p>Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory</p>
</li>
<li>
<p>Spring Cloud integration - no discovery service is needed for integration tests</p>
</li>
<li>
<p>Spring Cloud Contract integrates with Pact out of the box and provides easy hooks to extend its functionality</p>
</li>
<li>
<p>Via Docker adds support for any language &amp; framework used</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_i_dont_want_to_write_a_contract_in_groovy"><a class="link" href="#_i_dont_want_to_write_a_contract_in_groovy">I don&#8217;t want to write a contract in Groovy!</a></h3>
<div class="paragraph">
<p>No problem. You can write a contract in YAML!</p>
</div>
</div>
<div class="sect2">
<h3 id="_what_is_this_valueconsumer_producer"><a class="link" href="#_what_is_this_valueconsumer_producer">What is this value(consumer(), producer()) ?</a></h3>
<div class="paragraph">
<p>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</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "2016-10-10 20:10:15",
"id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
"body" : "foo"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and JSON response</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "2016-10-10 21:10:15",
"id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
"body" : "bar"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Imagine the pain required to set proper value of the <code>time</code> field (let&#8217;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 <code>id</code>. Will you create a stubbed implementation of UUID generator? Makes little sense&#8230;&#8203;</p>
</div>
<div class="paragraph">
<p>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&#8217;t have to stub anything out. Let&#8217;s assume that in case of the aforementioned
JSON the most important part is the <code>body</code> field. You can focus on that and provide matching for other fields. In other words
you would like the stub to work like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "SOMETHING THAT MATCHES TIME",
"id" : "SOMETHING THAT MATCHES UUID",
"body" : "foo"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "2016-10-10 21:10:15",
"id" : "c4231e1f-3ca9-48d3-b7e7-567d55f0d051",
"body" : "bar"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you could see in the previous sections we generate tests from contracts. So from the producer&#8217;s side the situation looks
much different. We&#8217;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&#8217;t have any sort of matching. We need concrete values that the
producer&#8217;s backend can work on. Such a JSON would be a valid one:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "2016-10-10 20:10:15",
"id" : "9febab1c-6f36-4a0b-88d6-3b6a6d81cd4a",
"body" : "foo"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>On the other hand from the point of view of the validity of the contract the response doesn&#8217;t necessarily have to
contain concrete values of <code>time</code> or <code>id</code>. Let&#8217;s say that you generate those on the producer side - again, you&#8217;d
have to do a lot of stubbing to ensure that you always return the same values. That&#8217;s why from the producer&#8217;s side
what you might want is the following response:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"time" : "SOMETHING THAT MATCHES TIME",
"id" : "SOMETHING THAT MATCHES UUID",
"body" : "bar"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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&#8217;re allowing you to provide a <strong>dynamic value</strong>. That means that it can differ for both
sides of the communication. You can pass the values:</p>
</div>
<div class="paragraph">
<p>Either via the <code>value</code> method</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">value(consumer(...), producer(...))
value(stub(...), test(...))
value(client(...), server(...))</code></pre>
</div>
</div>
<div class="paragraph">
<p>or using the <code>$()</code> method</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">$(consumer(...), producer(...))
$(stub(...), test(...))
$(client(...), server(...))</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can read more about this in the <a href="#contract-dsl">Contract DSL</a> section.</p>
</div>
<div class="paragraph">
<p>Calling <code>value()</code> or <code>$()</code> tells Spring Cloud Contract that you will be passing a dynamic value.
Inside the <code>consumer()</code> method you pass the value that should be used on the consumer side (in the generated stub).
Inside the <code>producer()</code> method you pass the value that should be used on the producer side (in the generated test).</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
If on one side you have passed the regular expression and you haven&#8217;t passed the other, then the
other side will get auto-generated.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Most often you will use that method together with the <code>regex</code> helper method. E.g. <code>consumer(regex('[0-9]{10}'))</code>.</p>
</div>
<div class="paragraph">
<p>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):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/someUrl'
body([
time : value(consumer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
id: value(consumer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
body: "foo"
])
}
response {
status OK()
body([
time : value(producer(regex('[0-9]{4}-[0-9]{2}-[0-9]{2} [0-2][0-9]-[0-5][0-9]-[0-5][0-9]')),
id: value([producer(regex('[0-9a-zA-z]{8}-[0-9a-zA-z]{4}-[0-9a-zA-z]{4}-[0-9a-zA-z]{12}'))
body: "bar"
])
}
}</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Please read the <a href="https://groovy-lang.org/json.html">Groovy docs related to JSON</a> to understand how to
properly structure the request / response bodies.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_how_to_do_stubs_versioning"><a class="link" href="#_how_to_do_stubs_versioning">How to do Stubs versioning?</a></h3>
<div class="sect3">
<h4 id="_api_versioning"><a class="link" href="#_api_versioning">API Versioning</a></h4>
<div class="paragraph">
<p>Let&#8217;s try to answer a question what versioning really means. If you&#8217;re referring to the API version then there are
different approaches.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>use Hypermedia, links and do not version your API by any means</p>
</li>
<li>
<p>pass versions through headers / urls</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>I will not try to answer a question which approach is better. Whatever suits your needs and allows you to generate
business value should be picked.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s assume that you do version your API. In that case you should provide as many contracts as many versions you support.
You can create a subfolder for every version or append it to the contract name - whatever suits you more.</p>
</div>
</div>
<div class="sect3">
<h4 id="_jar_versioning"><a class="link" href="#_jar_versioning">JAR versioning</a></h4>
<div class="paragraph">
<p>If by versioning you mean the version of the JAR that contains the stubs then there are essentially two main approaches.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s assume that you&#8217;re doing Continuous Delivery / Deployment which means that you&#8217;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) :</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">1.0.0.20161020-201521-RELEASE</code></pre>
</div>
</div>
<div class="paragraph">
<p>In that case your generated stub jar will look like this.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">1.0.0.20161020-201521-RELEASE-stubs.jar</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this case you should inside your <code>application.yml</code> or <code>@AutoConfigureStubRunner</code> when referencing stubs provide the
latest version of the stubs. You can do that by passing the <code>+</code> sign. Example</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})</code></pre>
</div>
</div>
<div class="paragraph">
<p>If the versioning however is fixed (e.g. <code>1.0.4.RELEASE</code> or <code>2.1.1</code>) then you have to set the concrete value of the jar
version. Example for 2.1.1.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:2.1.1:stubs:8080"})</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_dev_or_prod_stubs"><a class="link" href="#_dev_or_prod_stubs">Dev or prod stubs</a></h4>
<div class="paragraph">
<p>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 <code>prod-stubs</code> classifier
once you reach production deployment then you can run tests in one case with dev stubs and one with prod stubs.</p>
</div>
<div class="paragraph">
<p>Example of tests using development version of stubs</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:8080"})</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of tests using production version of stubs</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:prod-stubs:8080"})</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can pass those values also via properties from your deployment pipeline.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_common_repo_with_contracts"><a class="link" href="#_common_repo_with_contracts">Common repo with contracts</a></h3>
<div class="paragraph">
<p>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&#8217;t clone the producer&#8217;s code. Also if you keep
contracts in a single place then you, as a producer, will know how many consumers you have and which
consumer you will break with your local changes.</p>
</div>
<div class="sect3">
<h4 id="_repo_structure"><a class="link" href="#_repo_structure">Repo structure</a></h4>
<div class="paragraph">
<p>Let&#8217;s assume that we have a producer with coordinates <code>com.example:server</code> and 3 consumers: <code>client1</code>,
<code>client2</code>, <code>client3</code>. Then in the repository with common contracts you would have the following setup
(which you can checkout <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/master/samples/standalone/contracts">here</a>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── com
│   └── example
│   └── server
│   ├── client1
│   │   └── expectation.groovy
│   ├── client2
│   │   └── expectation.groovy
│   ├── client3
│   │   └── expectation.groovy
│   └── pom.xml
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
└── assembly
└── contracts.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see under the slash-delimited groupid <code>/</code> artifact id folder (<code>com/example/server</code>) you have
expectations of the 3 consumers (<code>client1</code>, <code>client2</code> and <code>client3</code>). 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.</p>
</div>
<div class="paragraph">
<p>Example of a <code>pom.xml</code> inside the <code>server</code> folder.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.example&lt;/groupId&gt;
&lt;artifactId&gt;server&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;Server Stubs&lt;/name&gt;
&lt;description&gt;POM used to install locally stubs for consumer side&lt;/description&gt;
&lt;parent&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
&lt;version&gt;2.2.0.BUILD-SNAPSHOT&lt;/version&gt;
&lt;relativePath/&gt;
&lt;/parent&gt;
&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;java.version&gt;1.8&lt;/java.version&gt;
&lt;spring-cloud-contract.version&gt;2.2.0.BUILD-SNAPSHOT&lt;/spring-cloud-contract.version&gt;
&lt;spring-cloud-release.version&gt;Hoxton.BUILD-SNAPSHOT&lt;/spring-cloud-release.version&gt;
&lt;excludeBuildFolders&gt;true&lt;/excludeBuildFolders&gt;
&lt;/properties&gt;
&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-release.version}&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;!-- By default it would search under src/test/resources/ --&gt;
&lt;contractsDirectory&gt;${project.basedir}&lt;/contractsDirectory&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;
&lt;/project&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 <code>mvn clean install -DskipTests</code> to locally install
stubs of the producer project.</p>
</div>
<div class="paragraph">
<p>The <code>pom.xml</code> in the root folder can look like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.example.standalone&lt;/groupId&gt;
&lt;artifactId&gt;contracts&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;Contracts&lt;/name&gt;
&lt;description&gt;Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
producers to generate tests and stubs
&lt;/description&gt;
&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;/properties&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;id&gt;contracts&lt;/id&gt;
&lt;phase&gt;prepare-package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;single&lt;/goal&gt;
&lt;/goals&gt;
&lt;configuration&gt;
&lt;attach&gt;true&lt;/attach&gt;
&lt;descriptor&gt;${basedir}/src/assembly/contracts.xml&lt;/descriptor&gt;
&lt;!-- If you want an explicit classifier remove the following line --&gt;
&lt;appendAssemblyId&gt;false&lt;/appendAssemblyId&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>It&#8217;s using the assembly plugin in order to build the JAR with all the contracts. Example of such setup is here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;assembly xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd"&gt;
&lt;id&gt;project&lt;/id&gt;
&lt;formats&gt;
&lt;format&gt;jar&lt;/format&gt;
&lt;/formats&gt;
&lt;includeBaseDirectory&gt;false&lt;/includeBaseDirectory&gt;
&lt;fileSets&gt;
&lt;fileSet&gt;
&lt;directory&gt;${project.basedir}&lt;/directory&gt;
&lt;outputDirectory&gt;/&lt;/outputDirectory&gt;
&lt;useDefaultExcludes&gt;true&lt;/useDefaultExcludes&gt;
&lt;excludes&gt;
&lt;exclude&gt;**/${project.build.directory}/**&lt;/exclude&gt;
&lt;exclude&gt;mvnw&lt;/exclude&gt;
&lt;exclude&gt;mvnw.cmd&lt;/exclude&gt;
&lt;exclude&gt;.mvn/**&lt;/exclude&gt;
&lt;exclude&gt;src/**&lt;/exclude&gt;
&lt;/excludes&gt;
&lt;/fileSet&gt;
&lt;/fileSets&gt;
&lt;/assembly&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_workflow"><a class="link" href="#_workflow">Workflow</a></h4>
<div class="paragraph">
<p>The workflow would look similar to the one presented in the <code>Step by step guide to CDC</code>. The only difference
is that the producer doesn&#8217;t own the contracts anymore. So the consumer and the producer have to work on
common contracts in a common repository.</p>
</div>
</div>
<div class="sect3">
<h4 id="_consumer"><a class="link" href="#_consumer">Consumer</a></h4>
<div class="paragraph">
<p>When the <strong>consumer</strong> 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&#8217;s folder (e.g. <code>com/example/server</code>)
and runs <code>mvn clean install -DskipTests</code> to install locally the stubs converted from the contracts.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You need to have <a href="https://maven.apache.org/download.cgi">Maven installed locally</a>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_producer"><a class="link" href="#_producer">Producer</a></h4>
<div class="paragraph">
<p>As a <strong>producer</strong> it&#8217;s enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency
of the JAR containing the contracts:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;contractsMode&gt;REMOTE&lt;/contractsMode&gt;
&lt;contractsRepositoryUrl&gt;
https://link/to/your/nexus/or/artifactory/or/sth
&lt;/contractsRepositoryUrl&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;com.example.standalone&lt;/groupId&gt;
&lt;artifactId&gt;contracts&lt;/artifactId&gt;
&lt;/contractDependency&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this setup the JAR with groupid <code>com.example.standalone</code> and artifactid <code>contracts</code> will be downloaded
from <code><a href="https://link/to/your/nexus/or/artifactory/or/sth" class="bare">https://link/to/your/nexus/or/artifactory/or/sth</a></code>. It will be then unpacked in a local temporary folder
and contracts present under the <code>com/example/server</code> 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.</p>
</div>
<div class="paragraph">
<p>The rest of the flow looks the same.</p>
</div>
</div>
<div class="sect3">
<h4 id="_how_can_i_define_messaging_contracts_per_topic_not_per_producer"><a class="link" href="#_how_can_i_define_messaging_contracts_per_topic_not_per_producer">How can I define messaging contracts per topic not per producer?</a></h4>
<div class="paragraph">
<p>To avoid messaging contracts duplication in the common repo, when few producers writing messages to one topic,
we could create the structure when the rest contracts would be placed in a folder per producer and messaging
contracts in the folder per topic.</p>
</div>
<div class="sect4">
<h5 id="_for_maven_project"><a class="link" href="#_for_maven_project">For Maven Project</a></h5>
<div class="paragraph">
<p>To make it possible to work on the producer side we should specify an inclusion pattern for
filtering common repository jar by messaging topics we are interested in. <code><code>includedFiles</code></code> property of <code><code>Maven Spring Cloud Contract plugin</code></code>
allows us to do that. Also <code><code>contractsPath</code></code> need to be specified since the default path would be the common repository <code><code>groupid/artifactid</code></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;configuration&gt;
&lt;contractsMode&gt;REMOTE&lt;/contractsMode&gt;
&lt;contractsRepositoryUrl&gt;https://link/to/your/nexus/or/artifactory/or/sth&lt;/contractsRepositoryUrl&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;com.example&lt;/groupId&gt;
&lt;artifactId&gt;common-repo-with-contracts&lt;/artifactId&gt;
&lt;version&gt;+&lt;/version&gt;
&lt;/contractDependency&gt;
&lt;contractsPath&gt;/&lt;/contractsPath&gt;
&lt;baseClassMappings&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*messaging.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.services.MessagingBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*rest.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.services.TestBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;/baseClassMappings&gt;
&lt;includedFiles&gt;
&lt;includedFile&gt;**/${project.artifactId}/**&lt;/includedFile&gt;
&lt;includedFile&gt;**/${first-topic}/**&lt;/includedFile&gt;
&lt;includedFile&gt;**/${second-topic}/**&lt;/includedFile&gt;
&lt;/includedFiles&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_for_gradle_project"><a class="link" href="#_for_gradle_project">For Gradle Project</a></h5>
<div class="ulist">
<ul>
<li>
<p>Add a custom configuration for the common-repo dependency:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ext {
conractsGroupId = "com.example"
contractsArtifactId = "common-repo"
contractsVersion = "1.2.3"
}
configurations {
contracts {
transitive = false
}
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Add the common-repo dependency to your classpath:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">dependencies {
contracts "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
testCompile "${conractsGroupId}:${contractsArtifactId}:${contractsVersion}"
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Download the dependency to an appropriate folder:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">task getContracts(type: Copy) {
from configurations.contracts
into new File(project.buildDir, "downloadedContracts")
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Unzip JAR:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">task unzipContracts(type: Copy) {
def zipFile = new File(project.buildDir, "downloadedContracts/${contractsArtifactId}-${contractsVersion}.jar")
def outputDir = file("${buildDir}/unpackedContracts")
from zipTree(zipFile)
into outputDir
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Cleanup unused contracts:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">task deleteUnwantedContracts(type: Delete) {
delete fileTree(dir: "${buildDir}/unpackedContracts",
include: "**/*",
excludes: [
"**/${project.name}/**"",
"**/${first-topic}/**",
"**/${second-topic}/**"])
}</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Create task dependencies:</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">unzipContracts.dependsOn("getContracts")
deleteUnwantedContracts.dependsOn("unzipContracts")
build.dependsOn("deleteUnwantedContracts")</code></pre>
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>Configure plugin by specifying the directory containing contracts using <code>contractsDslDir</code> property</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
contractsDslDir = new File("${buildDir}/unpackedContracts")
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_do_i_need_a_binary_storage_cant_i_use_git"><a class="link" href="#_do_i_need_a_binary_storage_cant_i_use_git">Do I need a Binary Storage? Can&#8217;t I use Git?</a></h3>
<div class="paragraph">
<p>In the polyglot world, there are languages that don&#8217;t use binary storages like
Artifactory or Nexus. Starting from Spring Cloud Contract version 2.0.0 we provide
mechanisms to store contracts and stubs in a SCM repository. Currently the
only supported SCM is Git.</p>
</div>
<div class="paragraph">
<p>The repository would have to the following setup
(which you can checkout <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/contracts_git/">here</a>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>.
└── META-INF
└── com.example
└── beer-api-producer-git
└── 0.0.1-SNAPSHOT
├── contracts
│   └── beer-api-consumer
│   ├── messaging
│   │   ├── shouldSendAcceptedVerification.groovy
│   │   └── shouldSendRejectedVerification.groovy
│   └── rest
│   ├── shouldGrantABeerIfOldEnough.groovy
│   └── shouldRejectABeerIfTooYoung.groovy
└── mappings
└── beer-api-consumer
└── rest
├── shouldGrantABeerIfOldEnough.json
└── shouldRejectABeerIfTooYoung.json</code></pre>
</div>
</div>
<div class="paragraph">
<p>Under <code>META-INF</code> folder:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>we group applications via <code>groupId</code> (e.g. <code>com.example</code>)</p>
</li>
<li>
<p>then each application is represented via the <code>artifactId</code> (e.g. <code>beer-api-producer-git</code>)</p>
</li>
<li>
<p>next, the version of the application (e.g. <code>0.0.1-SNAPSHOT</code>). Starting from Spring Cloud Contract version <code>2.1.0</code>, you can specify the versions as follows (assuming that your versions follow the semantic versioning)</p>
<div class="ulist">
<ul>
<li>
<p><code>+</code> or <code>latest</code> - to find the latest version of your stubs (assuming that the snapshots are always the latest artifact for a given revision number). That means:</p>
<div class="ulist">
<ul>
<li>
<p>if you have a version <code>1.0.0.RELEASE</code>, <code>2.0.0.BUILD-SNAPSHOT</code> and <code>2.0.0.RELEASE</code> we will assume that the latest is <code>2.0.0.BUILD-SNAPSHOT</code></p>
</li>
<li>
<p>if you have a version <code>1.0.0.RELEASE</code> and <code>2.0.0.RELEASE</code> we will assume that the latest is <code>2.0.0.RELEASE</code></p>
</li>
<li>
<p>if you have a version called <code>latest</code> or <code>+</code> we will pick that folder</p>
</li>
</ul>
</div>
</li>
<li>
<p><code>release</code> - to find the latest release version of your stubs. That means:</p>
<div class="ulist">
<ul>
<li>
<p>if you have a version <code>1.0.0.RELEASE</code>, <code>2.0.0.BUILD-SNAPSHOT</code> and <code>2.0.0.RELEASE</code> we will assume that the latest is <code>2.0.0.RELEASE</code></p>
</li>
<li>
<p>if you have a version called <code>release</code> we will pick that folder</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
<li>
<p>finally, there are two folders:</p>
<div class="ulist">
<ul>
<li>
<p><code>contracts</code> - the good practice is to store the contracts required by each
consumer in the folder with the consumer name (e.g. <code>beer-api-consumer</code>). That way you
can use the <code>stubs-per-consumer</code> feature. Further directory structure is arbitrary.</p>
</li>
<li>
<p><code>mappings</code> - in this folder the Maven / Gradle Spring Cloud Contract plugins will push
the stub server mappings. On the consumer side, Stub Runner will scan this folder
to start stub servers with stub definitions. The folder structure will be a copy
of the one created in the <code>contracts</code> subfolder.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_protocol_convention"><a class="link" href="#_protocol_convention">Protocol convention</a></h4>
<div class="paragraph">
<p>In order to control the type and location of the source of contracts (whether it&#8217;s
a binary storage or an SCM repository), you can use the protocol in the URL of
the repository. Spring Cloud Contract iterates over registered protocol resolvers
and tries to fetch the contracts (via a plugin) or stubs (via Stub Runner).</p>
</div>
<div class="paragraph">
<p>For the SCM functionality, currently, we support the Git repository. To use it,
in the property, where the repository URL needs to be placed you just have to prefix
the connection URL with <code>git://</code>. Here you can find a couple of examples:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>git://file:///foo/bar
git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_producer_2"><a class="link" href="#_producer_2">Producer</a></h4>
<div class="paragraph">
<p>For the producer, to use the SCM approach, we can reuse the
same mechanism we use for external contracts. We route Spring Cloud Contract
to use the SCM implementation via the URL that contains
the <code>git://</code> protocol.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
You have to manually add the <code>pushStubsToScm</code>
goal in Maven or execute (bind) the <code>pushStubsToScm</code> task in
Gradle. We don&#8217;t push stubs to <code>origin</code> of your git
repository out of the box.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;!-- Base class mappings etc. --&gt;
&lt;!-- We want to pick contracts from a Git repository --&gt;
&lt;contractsRepositoryUrl&gt;git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git&lt;/contractsRepositoryUrl&gt;
&lt;!-- We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts --&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;${project.groupId}&lt;/groupId&gt;
&lt;artifactId&gt;${project.artifactId}&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;/contractDependency&gt;
&lt;!-- The contracts mode can't be classpath --&gt;
&lt;contractsMode&gt;REMOTE&lt;/contractsMode&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;!-- By default we will not push the stubs back to SCM,
you have to explicitly add it as a goal --&gt;
&lt;goal&gt;pushStubsToScm&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-gradle hljs" data-lang="gradle">contracts {
// We want to pick contracts from a Git repository
contractDependency {
stringNotation = "${project.group}:${project.name}:${project.version}"
}
/*
We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts
*/
contractRepository {
repositoryUrl = "git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
}
// The mode can't be classpath
contractsMode = "REMOTE"
// Base class mappings etc.
}
/*
In this scenario we want to publish stubs to SCM whenever
the `publish` task is executed
*/
publish.dependsOn("publishStubsToScm")</code></pre>
</div>
</div>
<div class="paragraph">
<p>With such a setup:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Git project will be cloned to a temporary directory</p>
</li>
<li>
<p>The SCM stub downloader will go to <code>META-INF/groupId/artifactId/version/contracts</code> folder
to find contracts. E.g. for <code>com.example:foo:1.0.0</code> the path would be
<code>META-INF/com.example/foo/1.0.0/contracts</code></p>
</li>
<li>
<p>Tests will be generated from the contracts</p>
</li>
<li>
<p>Stubs will be created from the contracts</p>
</li>
<li>
<p>Once the tests pass, the stubs will be committed in the cloned repository</p>
</li>
<li>
<p>Finally, a push will be done to that repo&#8217;s <code>origin</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_producer_with_contracts_stored_locally"><a class="link" href="#_producer_with_contracts_stored_locally">Producer with contracts stored locally</a></h4>
<div class="paragraph">
<p>Another option to use the SCM as the destination for stubs and contracts is to store the contracts locally, with the producer, and only push the contracts and the stubs to SCM. Below, you can find the setup required to achieve this using Maven and Gradle.</p>
</div>
<div class="listingblock">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;!-- In the default configuration, we want to use the contracts stored locally --&gt;
&lt;configuration&gt;
&lt;baseClassMappings&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*messaging.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.BeerMessagingBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*rest.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.BeerRestBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;/baseClassMappings&gt;
&lt;basePackageForTests&gt;com.example&lt;/basePackageForTests&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;!-- By default we will not push the stubs back to SCM,
you have to explicitly add it as a goal --&gt;
&lt;goal&gt;pushStubsToScm&lt;/goal&gt;
&lt;/goals&gt;
&lt;configuration&gt;
&lt;!-- We want to pick contracts from a Git repository --&gt;
&lt;contractsRepositoryUrl&gt;git://file://${env.ROOT}/target/contract_empty_git/
&lt;/contractsRepositoryUrl&gt;
&lt;!-- Example of URL via git protocol --&gt;
&lt;!--&lt;contractsRepositoryUrl&gt;git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git&lt;/contractsRepositoryUrl&gt;--&gt;
&lt;!-- Example of URL via http protocol --&gt;
&lt;!--&lt;contractsRepositoryUrl&gt;git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git&lt;/contractsRepositoryUrl&gt;--&gt;
&lt;!-- We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts --&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;${project.groupId}&lt;/groupId&gt;
&lt;artifactId&gt;${project.artifactId}&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;/contractDependency&gt;
&lt;!-- The mode can't be classpath --&gt;
&lt;contractsMode&gt;LOCAL&lt;/contractsMode&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">contracts {
// Base package for generated tests
basePackageForTests = "com.example"
baseClassMappings {
baseClassMapping(".*messaging.*", "com.example.BeerMessagingBase")
baseClassMapping(".*rest.*", "com.example.BeerRestBase")
}
}
/*
In this scenario we want to publish stubs to SCM whenever
the `publish` task is executed
*/
publishStubsToScm {
// We want to modify the default set up of the plugin when publish stubs to scm is called
customize {
// We want to pick contracts from a Git repository
contractDependency {
stringNotation = "${project.group}:${project.name}:${project.version}"
}
/*
We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts
*/
contractRepository {
repositoryUrl = "git://file://${System.getenv("ROOT")}/target/contract_empty_git/"
}
// The mode can't be classpath
contractsMode = "LOCAL"
}
}
publish.dependsOn("publishStubsToScm")
publishToMavenLocal.dependsOn("publishStubsToScm")</code></pre>
</div>
</div>
<div class="paragraph">
<p>With such a setup:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Contracts from the default <code>src/test/resources/contracts</code> directory will be picked</p>
</li>
<li>
<p>Tests will be generated from the contracts</p>
</li>
<li>
<p>Stubs will be created from the contracts</p>
</li>
<li>
<p>Once the tests pass</p>
<div class="ulist">
<ul>
<li>
<p>Git project will be cloned to a temporary directory</p>
</li>
<li>
<p>The stubs and contracts will be committed in the cloned repository</p>
</li>
</ul>
</div>
</li>
<li>
<p>Finally, a push will be done to that repo&#8217;s <code>origin</code></p>
</li>
</ul>
</div>
<div class="sect4">
<h5 id="_keeping_contracts_with_the_producer_and_stubs_in_an_external_repository"><a class="link" href="#_keeping_contracts_with_the_producer_and_stubs_in_an_external_repository">Keeping contracts with the producer and stubs in an external repository</a></h5>
<div class="paragraph">
<p>It is also possible to keep the contracts in the producer repository, but keep the stubs in an external git repo.
This is most useful when you want to use the base consumer-producer collaboration flow, but do not have a possibility to
use an artifact repository for storing the stubs.</p>
</div>
<div class="paragraph">
<p>In order to do that, use the usual producer setup, and then add the <code>pushStubsToScm</code> goal and set
<code>contractsRepositoryUrl</code> to the repository where you want to keep the stubs.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_consumer_2"><a class="link" href="#_consumer_2">Consumer</a></h4>
<div class="paragraph">
<p>On the consumer side when passing the <code>repositoryRoot</code> parameter,
either from the <code>@AutoConfigureStubRunner</code> annotation, the
JUnit rule, JUnit 5 extension or properties, it&#8217;s enough to pass the URL of the
SCM repository, prefixed with the protocol. For example</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
stubsMode="REMOTE",
repositoryRoot="git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
ids="com.example:bookstore:0.0.1.RELEASE"
)</code></pre>
</div>
</div>
<div class="paragraph">
<p>With such a setup:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Git project will be cloned to a temporary directory</p>
</li>
<li>
<p>The SCM stub downloader will go to <code>META-INF/groupId/artifactId/version/</code> folder
to find stub definitions and contracts. E.g. for <code>com.example:foo:1.0.0</code> the path would be
<code>META-INF/com.example/foo/1.0.0/</code></p>
</li>
<li>
<p>Stub servers will be started and fed with mappings</p>
</li>
<li>
<p>Messaging definitions will be read and used in the messaging tests</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_can_i_use_the_pact_broker"><a class="link" href="#_can_i_use_the_pact_broker">Can I use the Pact Broker?</a></h3>
<div class="paragraph">
<p>When using <a href="https://pact.io/">Pact</a> you can use the <a href="https://github.com/pact-foundation/pact_broker">Pact Broker</a>
to store and share Pact definitions. Starting from Spring Cloud Contract
2.0.0 one can fetch Pact files from the Pact Broker to generate
tests and stubs.</p>
</div>
<div class="paragraph">
<p>As a prerequisite the Pact Converter and Pact Stub Downloader
are required. You have to add them via the <code>spring-cloud-contract-pact</code> dependency.
You can read more about it in the <a href="#pact-converter">Pact Converter</a> section.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Pact follows the Consumer Contract convention. That means
that the Consumer creates the Pact definitions first, then
shares the files with the Producer. Those expectations are generated
from the Consumer&#8217;s code and can break the Producer if the expectations
are not met.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_pact_consumer"><a class="link" href="#_pact_consumer">Pact Consumer</a></h4>
<div class="paragraph">
<p>The consumer uses Pact framework to generate Pact files. The
Pact files are sent to the Pact Broker. An example of such
setup can be found <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/consumer_pact">here</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_producer_3"><a class="link" href="#_producer_3">Producer</a></h4>
<div class="paragraph">
<p>For the producer, to use the Pact files from the Pact Broker, we can reuse the
same mechanism we use for external contracts. We route Spring Cloud Contract
to use the Pact implementation via the URL that contains
the <code>pact://</code> protocol. It&#8217;s enough to pass the URL to the
Pact Broker. An example of such setup can be found <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/producer_pact">here</a>.</p>
</div>
<div class="listingblock">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;!-- Base class mappings etc. --&gt;
&lt;!-- We want to pick contracts from a Git repository --&gt;
&lt;contractsRepositoryUrl&gt;pact://http://localhost:8085&lt;/contractsRepositoryUrl&gt;
&lt;!-- We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts --&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;${project.groupId}&lt;/groupId&gt;
&lt;artifactId&gt;${project.artifactId}&lt;/artifactId&gt;
&lt;!-- When + is passed, a latest tag will be applied when fetching pacts --&gt;
&lt;version&gt;+&lt;/version&gt;
&lt;/contractDependency&gt;
&lt;!-- The contracts mode can't be classpath --&gt;
&lt;contractsMode&gt;REMOTE&lt;/contractsMode&gt;
&lt;/configuration&gt;
&lt;!-- Don't forget to add spring-cloud-contract-pact to the classpath! --&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-pact&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-gradle hljs" data-lang="gradle">buildscript {
repositories {
//...
}
dependencies {
// ...
// Don't forget to add spring-cloud-contract-pact to the classpath!
classpath "org.springframework.cloud:spring-cloud-contract-pact:${contractVersion}"
}
}
contracts {
// When + is passed, a latest tag will be applied when fetching pacts
contractDependency {
stringNotation = "${project.group}:${project.name}:+"
}
contractRepository {
repositoryUrl = "pact://http://localhost:8085"
}
// The mode can't be classpath
contractsMode = "REMOTE"
// Base class mappings etc.
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With such a setup:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Pact files will be downloaded from the Pact Broker</p>
</li>
<li>
<p>Spring Cloud Contract will convert the Pact files into tests and stubs</p>
</li>
<li>
<p>The JAR with the stubs gets automatically created as usual</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_pact_consumer_producer_contract_approach"><a class="link" href="#_pact_consumer_producer_contract_approach">Pact Consumer (Producer Contract approach)</a></h4>
<div class="paragraph">
<p>In the scenario where you don&#8217;t want to do Consumer Contract approach
(for every single consumer define the expectations) but you&#8217;d prefer
to do Producer Contracts (the producer provides the contracts and
publishes stubs), it&#8217;s enough to use Spring Cloud Contract with
Stub Runner option. An example of such setup can be found <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/consumer_pact_stubrunner">here</a>.</p>
</div>
<div class="paragraph">
<p>First, remember to add Stub Runner and Spring Cloud Contract Pact module
as test dependencies.</p>
</div>
<div class="listingblock">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud.version}&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;
&lt;!-- Don't forget to add spring-cloud-contract-pact to the classpath! --&gt;
&lt;dependencies&gt;
&lt;!-- ... --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-pact&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-gradle hljs" data-lang="gradle">dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
dependencies {
//...
testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
// Don't forget to add spring-cloud-contract-pact to the classpath!
testCompile("org.springframework.cloud:spring-cloud-contract-pact")
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next, just pass the URL of the Pact Broker to <code>repositoryRoot</code>, prefixed
with <code>pact://</code> protocol. E.g. <code>pact://http://localhost:8085</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
ids = "com.example:beer-api-producer-pact",
repositoryRoot = "pact://http://localhost:8085")
public class BeerControllerTest {
//Inject the port of the running stub
@StubRunnerPort("beer-api-producer-pact") int producerPort;
//...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>With such a setup:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Pact files will be downloaded from the Pact Broker</p>
</li>
<li>
<p>Spring Cloud Contract will convert the Pact files into stub definitions</p>
</li>
<li>
<p>The stub servers will be started and fed with stubs</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For more information about Pact support you can go to
the <a href="#pact-stub-downloader">Using the Pact Stub Downloader</a> section.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_how_can_i_debug_the_requestresponse_being_sent_by_the_generated_tests_client"><a class="link" href="#_how_can_i_debug_the_requestresponse_being_sent_by_the_generated_tests_client">How can I debug the request/response being sent by the generated tests client?</a></h3>
<div class="paragraph">
<p>The generated tests all boil down to RestAssured in some form or fashion which relies on <a href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>. HttpClient has a facility called <a href="https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging">wire logging</a> which logs the entire request and response to HttpClient. Spring Boot has a logging <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html">common application property</a> for doing this sort of thing, just add this to your application properties</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-properties hljs" data-lang="properties">logging.level.org.apache.http.wire=DEBUG</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_how_can_i_debug_the_mappingrequestresponse_being_sent_by_wiremock"><a class="link" href="#_how_can_i_debug_the_mappingrequestresponse_being_sent_by_wiremock">How can I debug the mapping/request/response being sent by WireMock?</a></h4>
<div class="paragraph">
<p>Starting from version <code>1.2.0</code> 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.</p>
</div>
<div class="paragraph">
<p>To turn off this feature just bump WireMock logging to <code>ERROR</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-properties hljs" data-lang="properties">logging.level.com.github.tomakehurst.wiremock=ERROR</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_how_can_i_see_what_got_registered_in_the_http_server_stub"><a class="link" href="#_how_can_i_see_what_got_registered_in_the_http_server_stub">How can I see what got registered in the HTTP server stub?</a></h4>
<div class="paragraph">
<p>You can use the <code>mappingsOutputFolder</code> property on <code>@AutoConfigureStubRunner</code>, <code>StubRunnerRule</code> or
`StubRunnerExtension`to dump all mappings per artifact id. Also the port at which the given stub server
was started will be attached.</p>
</div>
</div>
<div class="sect3">
<h4 id="_can_i_reference_text_from_file"><a class="link" href="#_can_i_reference_text_from_file">Can I reference text from file?</a></h4>
<div class="paragraph">
<p>Yes! With version 1.2.0 we&#8217;ve added such a possibility. It&#8217;s enough to call <code>file(&#8230;&#8203;)</code> method in the
DSL and provide a path relative to where the contract lays.
If you&#8217;re using YAML just use the <code>bodyFromFile</code> property.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier_setup"><a class="link" href="#_spring_cloud_contract_verifier_setup">Spring Cloud Contract Verifier Setup</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can set up Spring Cloud Contract Verifier in the following ways:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#gradle-project">As a Gradle project</a></p>
</li>
<li>
<p><a href="#maven-project">As a Maven project</a></p>
</li>
<li>
<p><a href="#docker-project">As a Docker project</a></p>
</li>
</ul>
</div>
<div class="sect2">
<h3 id="gradle-project"><a class="link" href="#gradle-project">Gradle Project</a></h3>
<div class="paragraph">
<p>To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the
following sections:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#gradle-prerequisites">Prerequisites</a></p>
</li>
<li>
<p><a href="#gradle-add-gradle-plugin">Add Gradle Plugin with Dependencies</a></p>
</li>
<li>
<p><a href="#gradle-and-rest-assured">Gradle and Rest Assured 2.0</a></p>
</li>
<li>
<p><a href="#gradle-snapshot-versions">Snapshot Versions for Gradle</a></p>
</li>
<li>
<p><a href="#gradle-add-stubs">Add stubs</a></p>
</li>
<li>
<p><a href="#gradle-default-setup">Default Setup</a></p>
</li>
<li>
<p><a href="#gradle-configure-plugin">Configure Plugin</a></p>
</li>
<li>
<p><a href="#gradle-configuration-options">Configuration Options</a></p>
</li>
<li>
<p><a href="#gradle-single-base-class">Single Base Class for All Tests</a></p>
</li>
<li>
<p><a href="#gradle-different-base-classes">Different Base Classes for Contracts</a></p>
</li>
<li>
<p><a href="#gradle-invoking-generated-tests">Invoking Generated Tests</a></p>
</li>
<li>
<p><a href="#gradle-pushing-stubs-to-scm">Pushing stubs to SCM</a></p>
</li>
<li>
<p><a href="#gradle-consumer">Spring Cloud Contract Verifier on the Consumer Side</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="gradle-prerequisites"><a class="link" href="#gradle-prerequisites">Prerequisites</a></h4>
<div class="paragraph">
<p>In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a
Gradle or a Maven plugin.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
If you want to use Spock in your projects, you must add separately the
<code>spock-core</code> and <code>spock-spring</code> modules. Check <a href="https://spockframework.github.io/">Spock
docs for more information</a>
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="gradle-add-gradle-plugin"><a class="link" href="#gradle-add-gradle-plugin">Add Gradle Plugin with Dependencies</a></h4>
<div class="paragraph">
<p>To add a Gradle plugin with dependencies, use code similar to this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
}
}
apply plugin: 'groovy'
apply plugin: 'spring-cloud-contract'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}"
}
}
dependencies {
testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
// example with adding Spock core and Spock Spring
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4'
testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="gradle-and-rest-assured"><a class="link" href="#gradle-and-rest-assured">Gradle and Rest Assured 2.0</a></h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
classpath "com.jayway.restassured:rest-assured:2.5.0"
classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
}
}
depenendencies {
// all dependencies
// you can exclude rest-assured from spring-cloud-contract-verifier
testCompile "com.jayway.restassured:rest-assured:2.5.0"
testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath
and modifies the imports accordingly.</p>
</div>
</div>
<div class="sect3">
<h4 id="gradle-snapshot-versions"><a class="link" href="#gradle-snapshot-versions">Snapshot Versions for Gradle</a></h4>
<div class="paragraph">
<p>Add the additional snapshot repository to your build.gradle to use snapshot versions,
which are automatically uploaded after every successful build, as shown here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
repositories {
mavenCentral()
mavenLocal()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/release" }
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="gradle-add-stubs"><a class="link" href="#gradle-add-stubs">Add stubs</a></h4>
<div class="paragraph">
<p>By default, Spring Cloud Contract Verifier is looking for stubs in the
<code>src/test/resources/contracts</code> directory.</p>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier creates a test class named <code>defaultBasePackage.MyService</code>
with two methods:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>shouldCreateUser()</code></p>
</li>
<li>
<p><code>shouldReturnUser()</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="gradle-run-plugin"><a class="link" href="#gradle-run-plugin">Run the Plugin</a></h4>
<div class="paragraph">
<p>The plugin registers itself to be invoked before a <code>check</code> 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 <code>generateContractTests</code> task.</p>
</div>
</div>
<div class="sect3">
<h4 id="gradle-default-setup"><a class="link" href="#gradle-default-setup">Default Setup</a></h4>
<div class="paragraph">
<p>The default Gradle Plugin setup creates the following Gradle part of the build (in
pseudocode):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
testFramework ='JUNIT'
testMode = 'MockMvc'
generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
basePackageForTests = 'org.springframework.cloud.verifier.tests'
stubsOutputDir = project.file("${project.buildDir}/stubs")
// the following properties are used when you want to provide where the JAR with contract lays
contractDependency {
stringNotation = ''
}
contractsPath = ''
contractsWorkOffline = false
contractRepository {
cacheDownloadedContracts(true)
}
}
tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
baseName = project.name
classifier = contracts.stubsSuffix
from contractVerifier.stubsOutputDir
}
project.artifacts {
archives task
}
tasks.create(type: Copy, name: 'copyContracts') {
from contracts.contractsDslDir
into contracts.stubsOutputDir
}
verifierStubsJar.dependsOn 'copyContracts'
publishing {
publications {
stubs(MavenPublication) {
artifactId project.name
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="gradle-configure-plugin"><a class="link" href="#gradle-configure-plugin">Configure Plugin</a></h4>
<div class="paragraph">
<p>To change the default configuration, add a <code>contracts</code> snippet to your Gradle config, as
shown here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
testMode = 'MockMvc'
baseClassForTests = 'org.mycompany.tests'
generatedTestSourcesDir = project.file('src/generatedContract')
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="gradle-configuration-options"><a class="link" href="#gradle-configuration-options">Configuration Options</a></h4>
<div class="ulist">
<ul>
<li>
<p><strong>testMode</strong>: Defines the mode for acceptance tests. By default, the mode is MockMvc,
which is based on Spring&#8217;s MockMvc. It can also be changed to <strong>WebTestClient</strong>, <strong>JaxRsClient</strong> or to
<strong>Explicit</strong> for real HTTP calls.</p>
</li>
<li>
<p><strong>imports</strong>: Creates an array with imports that should be included in generated tests
(for example ['org.myorg.Matchers']). By default, it creates an empty array.</p>
</li>
<li>
<p><strong>staticImports</strong>: Creates an array with static imports that should be included in
generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty
array.</p>
</li>
<li>
<p><strong>basePackageForTests</strong>: Specifies the base package for all generated tests. If not set,
the value is picked from <code>baseClassForTests&#8217;s package and from `packageWithBaseClasses</code>.
If neither of these values are set, then the value is set to
<code>org.springframework.cloud.contract.verifier.tests</code>.</p>
</li>
<li>
<p><strong>baseClassForTests</strong>: Creates a base class for all generated tests. By default, if you
use Spock classes, the class is <code>spock.lang.Specification</code>.</p>
</li>
<li>
<p><strong>packageWithBaseClasses</strong>: Defines a package where all the base classes reside. This
setting takes precedence over <strong>baseClassForTests</strong>.</p>
</li>
<li>
<p><strong>baseClassMappings</strong>: Explicitly maps a contract package to a FQN of a base class. This
setting takes precedence over <strong>packageWithBaseClasses</strong> and <strong>baseClassForTests</strong>.</p>
</li>
<li>
<p><strong>ruleClassForTests</strong>: Specifies a rule that should be added to the generated test
classes.</p>
</li>
<li>
<p><strong>ignoredFiles</strong>: Uses an <code>Antmatcher</code> to allow defining stub files for which processing
should be skipped. By default, it is an empty array.</p>
</li>
<li>
<p><strong>contractsDslDir</strong>: Specifies the directory containing contracts written using the
GroovyDSL. By default, its value is <code>$rootDir/src/test/resources/contracts</code>.</p>
</li>
<li>
<p><strong>generatedTestSourcesDir</strong>: Specifies the test source directory where tests generated
from the Groovy DSL should be placed. By default its value is
<code>$buildDir/generated-test-sources/contracts</code>.</p>
</li>
<li>
<p><strong>generatedTestResourcesDir</strong>: Specifies the test resource directory where resources used by the tests generated
from the Groovy DSL should be placed. By default its value is
<code>$buildDir/generated-test-resources/contracts</code>.</p>
</li>
<li>
<p><strong>stubsOutputDir</strong>: Specifies the directory where the generated WireMock stubs from
the Groovy DSL should be placed.</p>
</li>
<li>
<p><strong>testFramework</strong>: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (<code>TestFramework.JUNIT</code>), TestNG and
JUnit 5 are supported with JUnit 4 being the default framework.</p>
</li>
<li>
<p><strong>contractsProperties</strong>: a map containing properties to be passed to Spring Cloud Contract
components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The following properties are used when you want to specify the location of the JAR
containing the contracts:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><strong>contractDependency</strong>: Specifies the Dependency that provides
<code>groupid:artifactid:version:classifier</code> coordinates. You can use the <code>contractDependency</code>
closure to set it up.</p>
</li>
<li>
<p><strong>contractsPath</strong>: Specifies the path to the jar. If contract dependencies are
downloaded, the path defaults to <code>groupid/artifactid</code> where <code>groupid</code> is slash
separated. Otherwise, it scans contracts under the provided directory.</p>
</li>
<li>
<p><strong>contractsMode</strong>: Specifies the mode of downloading contracts (whether the
JAR is available offline, remotely etc.)</p>
</li>
<li>
<p><strong>deleteStubsAfterTest</strong>: If set to <code>false</code> will not remove any downloaded
contracts from temporary directories</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Below you can find a list of experimental features you can turn on via the plugin:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><strong>convertToYaml</strong>: converts all DSLs to the declarative, YAML format. This can be extremely useful when you&#8217;re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to <code>true</code>) you will not need to add the library dependency on the consumer side.</p>
</li>
<li>
<p><strong>assertJsonSize</strong>: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="gradle-single-base-class"><a class="link" href="#gradle-single-base-class">Single Base Class for All Tests</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">abstract class BaseMockMvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
}
void isProperCorrelationId(Integer correlationId) {
assert correlationId == 123456
}
void isEmpty(String value) {
assert value == null
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use <code>Explicit</code> 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 <code>JAXRSCLIENT</code> mode, this
base class should also contain a <code>protected WebTarget webTarget</code> field. Right now, the
only option to test the JAX-RS API is to start a web server.</p>
</div>
</div>
<div class="sect3">
<h4 id="gradle-different-base-classes"><a class="link" href="#gradle-different-base-classes">Different Base Classes for Contracts</a></h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Follow a convention by providing the <code>packageWithBaseClasses</code></p>
</li>
<li>
<p>Provide explicit mapping via <code>baseClassMappings</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>By Convention</strong></p>
</div>
<div class="paragraph">
<p>The convention is such that if you have a contract under (for example)
<code>src/test/resources/contract/foo/bar/baz/</code> and set the value of the
<code>packageWithBaseClasses</code> property to <code>com.example.base</code>, then Spring Cloud Contract
Verifier assumes that there is a <code>BarBazBase</code> class under the <code>com.example.base</code> package.
In other words, the system takes the last two parts of the package, if they exist, and
forms a class with a <code>Base</code> suffix. This rule takes precedence over <strong>baseClassForTests</strong>.
Here is an example of how it works in the <code>contracts</code> closure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">packageWithBaseClasses = 'com.example.base'</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>By Mapping</strong></p>
</div>
<div class="paragraph">
<p>You can manually map a regular expression of the contract&#8217;s package to fully qualified
name of the base class for the matched contract. You have to provide a list called
<code>baseClassMappings</code> that consists <code>baseClassMapping</code> objects that takes a
<code>contractPackageRegex</code> to <code>baseClassFQN</code> mapping. Consider the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">baseClassForTests = "com.example.FooBase"
baseClassMappings {
baseClassMapping('.*/com/.*', 'com.example.ComBase')
baseClassMapping('.*/bar/.*': 'com.example.BarBase')
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s assume that you have contracts under
- <code>src/test/resources/contract/com/</code>
- <code>src/test/resources/contract/foo/</code></p>
</div>
<div class="paragraph">
<p>By providing the <code>baseClassForTests</code>, we have a fallback in case mapping did not succeed.
(You could also provide the <code>packageWithBaseClasses</code> as a fallback.) That way, the tests
generated from <code>src/test/resources/contract/com/</code> contracts extend the
<code>com.example.ComBase</code>, whereas the rest of the tests extend <code>com.example.FooBase</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="gradle-invoking-generated-tests"><a class="link" href="#gradle-invoking-generated-tests">Invoking Generated Tests</a></h4>
<div class="paragraph">
<p>To ensure that the provider side is compliant with defined contracts, you need to invoke:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">./gradlew generateContractTests test</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="gradle-pushing-stubs-to-scm"><a class="link" href="#gradle-pushing-stubs-to-scm">Pushing stubs to SCM</a></h4>
<div class="paragraph">
<p>If you&#8217;re using the SCM repository to keep the contracts and
stubs, you might want to automate the step of pushing stubs to
the repository. To do that, it&#8217;s enough to call the <code>pushStubsToScm</code>
task. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ ./gradlew pushStubsToScm</code></pre>
</div>
</div>
<div class="paragraph">
<p>Under <a href="#scm-stub-downloader">Using the SCM Stub Downloader</a> you can find all possible
configuration options that you can pass either via
the <code>contractsProperties</code> field e.g. <code>contracts { contractsProperties = [foo:"bar"] }</code>,
via <code>contractsProperties</code> method e.g. <code>contracts { contractsProperties([foo:"bar"]) }</code>,
a system property or an environment variable.</p>
</div>
</div>
<div class="sect3">
<h4 id="gradle-consumer"><a class="link" href="#gradle-consumer">Spring Cloud Contract Verifier on the Consumer Side</a></h4>
<div class="paragraph">
<p>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 <code>src/test/resources/contracts</code> and generate
WireMock JSON stubs using:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">./gradlew generateClientStubs</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>stubsOutputDir</code> option has to be set for stub generation to work.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>When present, JSON stubs can be used in automated tests of consuming a service.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
class LoanApplicationServiceSpec extends Specification {
@ClassRule
@Shared
WireMockClassRule wireMockRule == new WireMockClassRule()
@Autowired
LoanApplicationService sut
def 'should successfully apply for loan'() {
given:
LoanApplication application =
new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
when:
LoanApplicationResult loanApplication == sut.loanApplication(application)
then:
loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED
loanApplication.rejectionReason == null
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>LoanApplication</code> makes a call to <code>FraudDetection</code> service. This request is handled by a
WireMock server configured with stubs generated by Spring Cloud Contract Verifier.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="maven-project"><a class="link" href="#maven-project">Maven Project</a></h3>
<div class="paragraph">
<p>To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the
following sections:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#maven-add-plugin">Add maven plugin</a></p>
</li>
<li>
<p><a href="#maven-rest-assured">Maven and Rest Assured 2.0</a></p>
</li>
<li>
<p><a href="#maven-snapshot-versions">Snapshot versions for Maven</a></p>
</li>
<li>
<p><a href="#maven-add-stubs">Add stubs</a></p>
</li>
<li>
<p><a href="#maven-run-plugin">Run plugin</a></p>
</li>
<li>
<p><a href="#maven-configure-plugin">Configure plugin</a></p>
</li>
<li>
<p><a href="#maven-configuration-options">Configuration Options</a></p>
</li>
<li>
<p><a href="#maven-single-base">Single Base Class for All Tests</a></p>
</li>
<li>
<p><a href="#maven-different-base">Different base classes for contracts</a></p>
</li>
<li>
<p><a href="#maven-invoking-generated-tests">Invoking generated tests</a></p>
</li>
<li>
<p><a href="#maven-pushing-stubs-to-scm">Pushing stubs to SCM</a></p>
</li>
<li>
<p><a href="#maven-sts">Maven Plugin and STS</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="maven-add-plugin"><a class="link" href="#maven-add-plugin">Add maven plugin</a></h4>
<div class="paragraph">
<p>Add the Spring Cloud Contract BOM in a fashion similar to this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-release.version}&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next, add the <code>Spring Cloud Contract Verifier</code> Maven plugin:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example.fraud&lt;/packageWithBaseClasses&gt;
&lt;convertToYaml&gt;true&lt;/convertToYaml&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can read more in the
<a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-contract/2.0.0.RELEASE/spring-cloud-contract-maven-plugin/">Spring
Cloud Contract Maven Plugin Documentation (example for <code>2.0.0.RELEASE</code> version)</a>.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-rest-assured"><a class="link" href="#maven-rest-assured">Maven and Rest Assured 2.0</a></h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example&lt;/packageWithBaseClasses&gt;
&lt;/configuration&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-verifier&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
&lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
&lt;version&gt;2.5.0&lt;/version&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
&lt;artifactId&gt;spring-mock-mvc&lt;/artifactId&gt;
&lt;version&gt;2.5.0&lt;/version&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/plugin&gt;
&lt;dependencies&gt;
&lt;!-- all dependencies --&gt;
&lt;!-- you can exclude rest-assured from spring-cloud-contract-verifier --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
&lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
&lt;version&gt;2.5.0&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.jayway.restassured&lt;/groupId&gt;
&lt;artifactId&gt;spring-mock-mvc&lt;/artifactId&gt;
&lt;version&gt;2.5.0&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath
and modifies the imports accordingly.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-snapshot-versions"><a class="link" href="#maven-snapshot-versions">Snapshot versions for Maven</a></h4>
<div class="paragraph">
<p>For Snapshot and Milestone versions, you have to add the following section to your
<code>pom.xml</code>, as shown here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="maven-add-stubs"><a class="link" href="#maven-add-stubs">Add stubs</a></h4>
<div class="paragraph">
<p>By default, Spring Cloud Contract Verifier is looking for stubs in the
<code>src/test/resources/contracts</code> 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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier creates a test class named <code>defaultBasePackage.MyService</code>
with two methods</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>shouldCreateUser()</code></p>
</li>
<li>
<p><code>shouldReturnUser()</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="maven-run-plugin"><a class="link" href="#maven-run-plugin">Run plugin</a></h4>
<div class="paragraph">
<p>The plugin goal <code>generateTests</code> is assigned to be invoked in the phase called
<code>generate-test-sources</code>. 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 <code>generateTests</code> goal.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-configure-plugin"><a class="link" href="#maven-configure-plugin">Configure plugin</a></h4>
<div class="paragraph">
<p>To change the default configuration, just add a <code>configuration</code> section to the plugin
definition or the <code>execution</code> definition, as shown here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;goal&gt;generateStubs&lt;/goal&gt;
&lt;goal&gt;generateTests&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;configuration&gt;
&lt;basePackageForTests&gt;org.springframework.cloud.verifier.twitter.place&lt;/basePackageForTests&gt;
&lt;baseClassForTests&gt;org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec&lt;/baseClassForTests&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="maven-configuration-options"><a class="link" href="#maven-configuration-options">Configuration Options</a></h4>
<div class="ulist">
<ul>
<li>
<p><strong>testMode</strong>: Defines the mode for acceptance tests. By default, the mode is MockMvc,
which is based on Spring&#8217;s MockMvc. It can also be changed to <strong>WebTestClient</strong>, <strong>JaxRsClient</strong> or to
<strong>Explicit</strong> for real HTTP calls.</p>
</li>
<li>
<p><strong>basePackageForTests</strong>: Specifies the base package for all generated tests. If not set,
the value is picked from <code>baseClassForTests&#8217;s package and from `packageWithBaseClasses</code>.
If neither of these values are set, then the value is set to
<code>org.springframework.cloud.contract.verifier.tests</code>.</p>
</li>
<li>
<p><strong>ruleClassForTests</strong>: Specifies a rule that should be added to the generated test
classes.</p>
</li>
<li>
<p><strong>baseClassForTests</strong>: Creates a base class for all generated tests. By default, if you
use Spock classes, the class is <code>spock.lang.Specification</code>.</p>
</li>
<li>
<p><strong>contractsDirectory</strong>: Specifies a directory containing contracts written with the
GroovyDSL. The default directory is <code>/src/test/resources/contracts</code>.</p>
</li>
<li>
<p><strong>generatedTestSourcesDir</strong>: Specifies the test source directory where tests generated
from the Groovy DSL should be placed. By default its value is
<code>$buildDir/generated-test-sources/contracts</code>.</p>
</li>
<li>
<p><strong>generatedTestResourcesDir</strong>: Specifies the test resource directory where resources used by the tests generated</p>
</li>
<li>
<p><strong>testFramework</strong>: Specifies the target test framework to be used. Currently, Spock, JUnit 4 (<code>TestFramework.JUNIT</code>) and
JUnit 5 are supported with JUnit 4 being the default framework.</p>
</li>
<li>
<p><strong>packageWithBaseClasses</strong>: Defines a package where all the base classes reside. This
setting takes precedence over <strong>baseClassForTests</strong>. The convention is such that, if you
have a contract under (for example) <code>src/test/resources/contract/foo/bar/baz/</code> and set
the value of the <code>packageWithBaseClasses</code> property to <code>com.example.base</code>, then Spring
Cloud Contract Verifier assumes that there is a <code>BarBazBase</code> class under the
<code>com.example.base</code> package. In other words, the system takes the last two parts of the
package, if they exist, and forms a class with a <code>Base</code> suffix.</p>
</li>
<li>
<p><strong>baseClassMappings</strong>: Specifies a list of base class mappings that provide
<code>contractPackageRegex</code>, which is checked against the package where the contract is
located, and <code>baseClassFQN</code>, which maps to the fully qualified name of the base class for
the matched contract. For example, if you have a contract under
<code>src/test/resources/contract/foo/bar/baz/</code> and map the property
<code>.* &#8594; com.example.base.BaseClass</code>, then the test class generated from these contracts
extends <code>com.example.base.BaseClass</code>. This setting takes precedence over
<strong>packageWithBaseClasses</strong> and <strong>baseClassForTests</strong>.</p>
</li>
<li>
<p><strong>contractsProperties</strong>: a map containing properties to be passed to Spring Cloud Contract
components. Those properties might be used by e.g. inbuilt or custom Stub Downloaders.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you want to download your contract definitions from a Maven repository, you can use
the following options:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><strong>contractDependency</strong>: The contract dependency that contains all the packaged contracts.</p>
</li>
<li>
<p><strong>contractsPath</strong>: The path to the concrete contracts in the JAR with packaged contracts.
Defaults to <code>groupid/artifactid</code> where <code>gropuid</code> is slash separated.</p>
</li>
<li>
<p><strong>contractsMode</strong>: Picks the mode in which stubs will be found and registered</p>
</li>
<li>
<p><strong>deleteStubsAfterTest</strong>: If set to <code>false</code> will not remove any downloaded
contracts from temporary directories</p>
</li>
<li>
<p><strong>contractsRepositoryUrl</strong>: URL to a repo with the artifacts that have contracts. If it is not provided,
use the current Maven ones.</p>
</li>
<li>
<p><strong>contractsRepositoryUsername</strong>: The user name to be used to connect to the repo with contracts.</p>
</li>
<li>
<p><strong>contractsRepositoryPassword</strong>: The password to be used to connect to the repo with contracts.</p>
</li>
<li>
<p><strong>contractsRepositoryProxyHost</strong>: The proxy host to be used to connect to the repo with contracts.</p>
</li>
<li>
<p><strong>contractsRepositoryProxyPort</strong>: The proxy port to be used to connect to the repo with contracts.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>We cache only non-snapshot, explicitly provided versions (for example
<code>+</code> or <code>1.0.0.BUILD-SNAPSHOT</code> won&#8217;t get cached). By default, this feature is turned on.</p>
</div>
<div class="paragraph">
<p>Below you can find a list of experimental features you can turn on via the plugin:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><strong>convertToYaml</strong>: converts all DSLs to the declarative, YAML format. This can be extremely useful when you&#8217;re using external libraries in your Groovy DSLs. By turning this feature on (by setting it to <code>true</code>) you will not need to add the library dependency on the consumer side.</p>
</li>
<li>
<p><strong>assertJsonSize</strong>: You can check the size of JSON arrays in the generated tests. This feature is disabled by default.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="maven-single-base"><a class="link" href="#maven-single-base">Single Base Class for All Tests</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.mycompany.tests
import org.mycompany.ExampleSpringController
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
import spock.lang.Specification
class MvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also setup the whole context if necessary.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {
@Autowired
WebApplicationContext context;
@Before
public void setup() {
RestAssuredMockMvc.webAppContextSetup(this.context);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use <code>EXPLICIT</code> mode, you can use a base class to initialize the whole tested app
similarly, as you might find in regular integration tests.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {
@LocalServerPort
int port;
@Before
public void setup() {
RestAssured.baseURI = "http://localhost:" + this.port;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you use the <code>JAXRSCLIENT</code> mode, this base class should also contain a <code>protected WebTarget webTarget</code> field. Right
now, the only option to test the JAX-RS API is to start a web server.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-different-base"><a class="link" href="#maven-different-base">Different base classes for contracts</a></h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Follow a convention by providing the <code>packageWithBaseClasses</code></p>
</li>
<li>
<p>provide explicit mapping via <code>baseClassMappings</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>By Convention</strong></p>
</div>
<div class="paragraph">
<p>The convention is such that if you have a contract under (for example)
<code>src/test/resources/contract/foo/bar/baz/</code> and set the value of the
<code>packageWithBaseClasses</code> property to <code>com.example.base</code>, then Spring Cloud Contract
Verifier assumes that there is a <code>BarBazBase</code> class under the <code>com.example.base</code> package.
In other words, the system takes the last two parts of the package, if they exist, and
forms a class with a <code>Base</code> suffix. This rule takes precedence over <strong>baseClassForTests</strong>.
Here is an example of how it works in the <code>contracts</code> closure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;hello&lt;/packageWithBaseClasses&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>By Mapping</strong></p>
</div>
<div class="paragraph">
<p>You can manually map a regular expression of the contract&#8217;s package to fully qualified
name of the base class for the matched contract. You have to provide a list called
<code>baseClassMappings</code> that consists <code>baseClassMapping</code> objects that takes a
<code>contractPackageRegex</code> to <code>baseClassFQN</code> mapping. Consider the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;baseClassForTests&gt;com.example.FooBase&lt;/baseClassForTests&gt;
&lt;baseClassMappings&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*com.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.TestBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;/baseClassMappings&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Assume that you have contracts under these two locations:
* <code>src/test/resources/contract/com/</code>
* <code>src/test/resources/contract/foo/</code></p>
</div>
<div class="paragraph">
<p>By providing the <code>baseClassForTests</code>, we have a fallback in case mapping did not succeed.
(You can also provide the <code>packageWithBaseClasses</code> as a fallback.) That way, the tests
generated from <code>src/test/resources/contract/com/</code> contracts extend the
<code>com.example.ComBase</code>, whereas the rest of the tests extend <code>com.example.FooBase</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-invoking-generated-tests"><a class="link" href="#maven-invoking-generated-tests">Invoking generated tests</a></h4>
<div class="paragraph">
<p>The Spring Cloud Contract Maven Plugin generates verification code in a directory called
<code>/generated-test-sources/contractVerifier</code> and attaches this directory to <code>testCompile</code>
goal.</p>
</div>
<div class="paragraph">
<p>For Groovy Spock code, use the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;
&lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;
&lt;version&gt;1.5&lt;/version&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;testCompile&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;configuration&gt;
&lt;testSources&gt;
&lt;testSource&gt;
&lt;directory&gt;${project.basedir}/src/test/groovy&lt;/directory&gt;
&lt;includes&gt;
&lt;include&gt;**/*.groovy&lt;/include&gt;
&lt;/includes&gt;
&lt;/testSource&gt;
&lt;testSource&gt;
&lt;directory&gt;${project.build.directory}/generated-test-sources/contractVerifier&lt;/directory&gt;
&lt;includes&gt;
&lt;include&gt;**/*.groovy&lt;/include&gt;
&lt;/includes&gt;
&lt;/testSource&gt;
&lt;/testSources&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>To ensure that provider side is compliant with defined contracts, you need to invoke
<code>mvn generateTest test</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-pushing-stubs-to-scm"><a class="link" href="#maven-pushing-stubs-to-scm">Pushing stubs to SCM</a></h4>
<div class="paragraph">
<p>If you&#8217;re using the SCM repository to keep the contracts and
stubs, you might want to automate the step of pushing stubs to
the repository. To do that, it&#8217;s enough to add the <code>pushStubsToScm</code>
goal. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;!-- Base class mappings etc. --&gt;
&lt;!-- We want to pick contracts from a Git repository --&gt;
&lt;contractsRepositoryUrl&gt;git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git&lt;/contractsRepositoryUrl&gt;
&lt;!-- We reuse the contract dependency section to set up the path
to the folder that contains the contract definitions. In our case the
path will be /groupId/artifactId/version/contracts --&gt;
&lt;contractDependency&gt;
&lt;groupId&gt;${project.groupId}&lt;/groupId&gt;
&lt;artifactId&gt;${project.artifactId}&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;/contractDependency&gt;
&lt;!-- The contracts mode can't be classpath --&gt;
&lt;contractsMode&gt;REMOTE&lt;/contractsMode&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;phase&gt;package&lt;/phase&gt;
&lt;goals&gt;
&lt;!-- By default we will not push the stubs back to SCM,
you have to explicitly add it as a goal --&gt;
&lt;goal&gt;pushStubsToScm&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Under <a href="#scm-stub-downloader">Using the SCM Stub Downloader</a> you can find all possible
configuration options that you can pass either via
the <code>&lt;configuration&gt;&lt;contractProperties&gt;</code> map, a system property
or an environment variable.</p>
</div>
</div>
<div class="sect3">
<h4 id="maven-sts"><a class="link" href="#maven-sts">Maven Plugin and STS</a></h4>
<div class="paragraph">
<p>If you see the following exception while using STS:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/docs/src/main/asciidoc/images/sts_exception.png" alt="STS Exception">
</div>
</div>
<div class="paragraph">
<p>When you click on the error marker you should see something like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash"> plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
...
org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at</code></pre>
</div>
</div>
<div class="paragraph">
<p>In order to fix this issue, provide the following section in your <code>pom.xml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;build&gt;
&lt;pluginManagement&gt;
&lt;plugins&gt;
&lt;!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. --&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.eclipse.m2e&lt;/groupId&gt;
&lt;artifactId&gt;lifecycle-mapping&lt;/artifactId&gt;
&lt;version&gt;1.0.0&lt;/version&gt;
&lt;configuration&gt;
&lt;lifecycleMappingMetadata&gt;
&lt;pluginExecutions&gt;
&lt;pluginExecution&gt;
&lt;pluginExecutionFilter&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;versionRange&gt;[1.0,)&lt;/versionRange&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;/goals&gt;
&lt;/pluginExecutionFilter&gt;
&lt;action&gt;
&lt;execute /&gt;
&lt;/action&gt;
&lt;/pluginExecution&gt;
&lt;/pluginExecutions&gt;
&lt;/lifecycleMappingMetadata&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/pluginManagement&gt;
&lt;/build&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_maven_plugin_with_spock_tests"><a class="link" href="#_maven_plugin_with_spock_tests">Maven Plugin with Spock Tests</a></h4>
<div class="paragraph">
<p>You can select the <a href="http://spockframework.org/">Spock Framework</a> for creating and executing the auto-generated contract
verification tests with both Maven and Gradle plugin. However, whereas with Gradle its really straightforward,
in Maven you will require some additional setup in order to make the tests compile and execute properly.</p>
</div>
<div class="paragraph">
<p>First of all, you will have to use a plugin, such as <a href="https://github.com/groovy/GMavenPlus">GMavenPlus</a> plugin,
to add Groovy to your project. In GMavenPlus plugin, you will need to explicitly set test sources, including both the
path where your base test classes are defined and the path were the generated contract tests are added.
Please refer to the example below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"></code></pre>
</div>
</div>
<div class="paragraph">
<p>If you uphold to the Spock convention of ending the test class names with <code>Spec</code>, you will also need to adjust your Maven
Surefire plugin setup, like in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stubs_and_transitive_dependencies"><a class="link" href="#_stubs_and_transitive_dependencies">Stubs and Transitive Dependencies</a></h3>
<div class="paragraph">
<p>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&#8217;s dependencies. When building a Maven artifact, even though you have a couple
of different jars, all of them share one pom:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
├── ...
└── ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>There are three possibilities of working with those dependencies so as not to have any
issues with transitive dependencies:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Mark all application dependencies as optional</p>
</li>
<li>
<p>Create a separate artifactid for the stubs</p>
</li>
<li>
<p>Exclude dependencies on the consumer side</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>Mark all application dependencies as optional</strong></p>
</div>
<div class="paragraph">
<p>If, in the <code>github-webhook</code> application, you mark all of your dependencies as optional,
when you include the <code>github-webhook</code> stubs in another application (or when that
dependency gets downloaded by Stub Runner) then, since all of the dependencies are
optional, they will not get downloaded.</p>
</div>
<div class="paragraph">
<p><strong>Create a separate <code>artifactid</code> for the stubs</strong></p>
</div>
<div class="paragraph">
<p>If you create a separate <code>artifactid</code>, then you can set it up in whatever way you wish.
For example, you might decide to have no dependencies at all.</p>
</div>
<div class="paragraph">
<p><strong>Exclude dependencies on the consumer side</strong></p>
</div>
<div class="paragraph">
<p>As a consumer, if you add the stub dependency to your classpath, you can explicitly
exclude the unwanted dependencies.</p>
</div>
</div>
<div class="sect2">
<h3 id="_scenarios"><a class="link" href="#_scenarios">Scenarios</a></h3>
<div class="paragraph">
<p>You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to
stick to the proper naming convention while creating your contracts. The convention
requires including an order number followed by an underscore. This will work regardles
of whether you&#8217;re working with YAML or Groovy. Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>my_contracts_dir\
scenario1\
1_login.groovy
2_showCart.groovy
3_logout.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Such a tree causes Spring Cloud Contract Verifier to generate WireMock&#8217;s scenario with a
name of <code>scenario1</code> and the three following steps:</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>login marked as <code>Started</code> pointing to&#8230;&#8203;</p>
</li>
<li>
<p>showCart marked as <code>Step1</code> pointing to&#8230;&#8203;</p>
</li>
<li>
<p>logout marked as <code>Step2</code> which will close the scenario.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>More details about WireMock scenarios can be found at
<a href="https://wiremock.org/docs/stateful-behaviour/">https://wiremock.org/docs/stateful-behaviour/</a></p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution.</p>
</div>
</div>
<div class="sect2">
<h3 id="docker-project"><a class="link" href="#docker-project">Docker Project</a></h3>
<div class="paragraph">
<p>We&#8217;re publishing a <code>springcloud/spring-cloud-contract</code> Docker image
that contains a project that will generate tests and execute them in <code>EXPLICIT</code> mode
against a running application.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
The <code>EXPLICIT</code> mode means that the tests generated from contracts will send
real requests and not the mocked ones.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_short_intro_to_maven_jars_and_binary_storage"><a class="link" href="#_short_intro_to_maven_jars_and_binary_storage">Short intro to Maven, JARs and Binary storage</a></h4>
<div class="paragraph">
<p>Since the Docker image can be used by non JVM projects, it&#8217;s good to
explain the basic terms behind Spring Cloud Contract packaging defaults.</p>
</div>
<div class="paragraph">
<p>Part of the following definitions were taken from the <a href="https://maven.apache.org/glossary.html">Maven Glossary</a></p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>Project</code>: Maven thinks in terms of projects. Everything that you
will build are projects. Those projects follow a well defined
“Project Object Model”. Projects can depend on other projects,
in which case the latter are called “dependencies”. A project may
consistent of several subprojects, however these subprojects are still
treated equally as projects.</p>
</li>
<li>
<p><code>Artifact</code>: An artifact is something that is either produced or used
by a project. Examples of artifacts produced by Maven for a project
include: JARs, source and binary distributions. Each artifact
is uniquely identified by a group id and an artifact ID which is
unique within a group.</p>
</li>
<li>
<p><code>JAR</code>: JAR stands for Java ARchive. It&#8217;s a format based on
the ZIP file format. Spring Cloud Contract packages the contracts and generated
stubs in a JAR file.</p>
</li>
<li>
<p><code>GroupId</code>: A group ID is a universally unique identifier for a project.
While this is often just the project name (eg. commons-collections),
it is helpful to use a fully-qualified package name to distinguish it
from other projects with a similar name (eg. org.apache.maven).
Typically, when published to the Artifact Manager, the <code>GroupId</code> will get
slash separated and form part of the URL. E.g. for group id <code>com.example</code>
and artifact id <code>application</code> would be <code>/com/example/application/</code>.</p>
</li>
<li>
<p><code>Classifier</code>: The Maven dependency notation looks as follows:
<code>groupId:artifactId:version:classifier</code>. The classifier is additional suffix
passed to the dependency. E.g. <code>stubs</code>, <code>sources</code>. The same dependency
e.g. <code>com.example:application</code> can produce multiple artifacts that
differ from each other with the classifier.</p>
</li>
<li>
<p><code>Artifact manager</code>: When you generate binaries / sources / packages, you would
like them to be available for others to download / reference or reuse. In case
of the JVM world those artifacts would be JARs, for Ruby these are gems
and for Docker those would be Docker images. You can store those artifacts
in a manager. Examples of such managers can be <a href="https://jfrog.com/artifactory/">Artifactory</a>
or <a href="https://www.sonatype.org/nexus/">Nexus</a>.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_how_it_works_2"><a class="link" href="#_how_it_works_2">How it works</a></h4>
<div class="paragraph">
<p>The image searches for contracts under the <code>/contracts</code> folder.
The output from running the tests will be available under
<code>/spring-cloud-contract/build</code> folder (it&#8217;s useful for debugging
purposes).</p>
</div>
<div class="paragraph">
<p>It&#8217;s enough for you to mount your contracts, pass the environment variables
and the image will:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>generate the contract tests</p>
</li>
<li>
<p>execute the tests against the provided URL</p>
</li>
<li>
<p>generate the <a href="https://github.com/tomakehurst/wiremock">WireMock</a> stubs</p>
</li>
<li>
<p>(optional - turned on by default) publish the stubs to a Artifact Manager</p>
</li>
</ul>
</div>
<div class="sect4">
<h5 id="_environment_variables"><a class="link" href="#_environment_variables">Environment Variables</a></h5>
<div class="paragraph">
<p>The Docker image requires some environment variables to point to
your running application, to the Artifact manager instance etc.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>PROJECT_GROUP</code> - your project&#8217;s group id. Defaults to <code>com.example</code></p>
</li>
<li>
<p><code>PROJECT_VERSION</code> - your project&#8217;s version. Defaults to <code>0.0.1-SNAPSHOT</code></p>
</li>
<li>
<p><code>PROJECT_NAME</code> - artifact id. Defaults to <code>example</code></p>
</li>
<li>
<p><code>PRODUCER_STUBS_CLASSIFIER</code> - archive classifier used for generated producer stubs, defaults to <code>stubs</code>.</p>
</li>
<li>
<p><code>REPO_WITH_BINARIES_URL</code> - URL of your Artifact Manager. Defaults to <code><a href="http://localhost:8081/artifactory/libs-release-local" class="bare">http://localhost:8081/artifactory/libs-release-local</a></code>
which is the default URL of <a href="https://jfrog.com/artifactory/">Artifactory</a> running locally</p>
</li>
<li>
<p><code>REPO_WITH_BINARIES_USERNAME</code> - (optional) username when the Artifact Manager is secured, defaults to <code>admin</code>.</p>
</li>
<li>
<p><code>REPO_WITH_BINARIES_PASSWORD</code> - (optional) password when the Artifact Manager is secured, defaults to <code>password</code>.</p>
</li>
<li>
<p><code>PUBLISH_ARTIFACTS</code> - if set to <code>true</code> then will publish artifact to binary storage. Defaults to <code>true</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>These environment variables are used when contracts lay in an external repository. To enable
this feature you must set the <code>EXTERNAL_CONTRACTS_ARTIFACT_ID</code> environment variable.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>EXTERNAL_CONTRACTS_GROUP_ID</code> - group id of the project with contracts. Defaults to <code>com.example</code></p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_ARTIFACT_ID</code>- artifact id of the project with contracts.</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_CLASSIFIER</code>- classifier of the project with contracts. Empty by default</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_VERSION</code> - version of the project with contracts. Defaults to <code>+</code>, equivalent to picking the latest</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL</code> - URL of your Artifact Manager. Defaults to value of <code>REPO_WITH_BINARIES_URL</code> env var.
If that&#8217;s not set, defaults to <code><a href="http://localhost:8081/artifactory/libs-release-local" class="bare">http://localhost:8081/artifactory/libs-release-local</a></code>
which is the default URL of <a href="https://jfrog.com/artifactory/">Artifactory</a> running locally</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_USERNAME</code> - (optional) username if the <code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL</code>
requires authentication, defaults to <code>REPO_WITH_BINARIES_USERNAME</code>. If that&#8217;s not set defaults to <code>admin</code>.</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_PASSWORD</code> - (optional) password if the <code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL</code>
requires authentication, defaults to <code>REPO_WITH_BINARIES_PASSWORD</code>. If that&#8217;s not set defaults to <code>password</code>.</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_PATH</code> - path to contracts for the given project, inside the project with contracts.
Defaults to slash separated <code>EXTERNAL_CONTRACTS_GROUP_ID</code> concatenated with <code>/</code> and <code>EXTERNAL_CONTRACTS_ARTIFACT_ID</code>. E.g.
for group id <code>foo.bar</code> and artifact id <code>baz</code>, would result in <code>foo/bar/baz</code> contracts path.</p>
</li>
<li>
<p><code>EXTERNAL_CONTRACTS_WORK_OFFLINE</code> - if set to <code>true</code> then will retrieve artifact with contracts
from the container&#8217;s <code>.m2</code>. Mount your local <code>.m2</code> as a volume available at the container&#8217;s <code>/root/.m2</code> path.
You must not set both <code>EXTERNAL_CONTRACTS_WORK_OFFLINE</code> and <code>EXTERNAL_CONTRACTS_REPO_WITH_BINARIES_URL</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>These environment variables are used when tests are executed:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>APPLICATION_BASE_URL</code> - url against which tests should be executed.
Remember that it has to be accessible from the Docker container (e.g. <code>localhost</code>
will not work)</p>
</li>
<li>
<p><code>APPLICATION_USERNAME</code> - (optional) username for basic authentication to your application</p>
</li>
<li>
<p><code>APPLICATION_PASSWORD</code> - (optional) password for basic authentication to your application</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_example_of_usage"><a class="link" href="#_example_of_usage">Example of usage</a></h4>
<div class="paragraph">
<p>Let&#8217;s take a look at a simple MVC application</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore</code></pre>
</div>
</div>
<div class="paragraph">
<p>The contracts are available under <code>/contracts</code> folder.</p>
</div>
</div>
<div class="sect3">
<h4 id="docker-server-side"><a class="link" href="#docker-server-side">Server side (nodejs)</a></h4>
<div class="paragraph">
<p>Since we want to run tests, we could just execute:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ npm test</code></pre>
</div>
</div>
<div class="paragraph">
<p>however, for learning purposes, let&#8217;s split it into pieces:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash"># Stop docker infra (nodejs, artifactory)
$ ./stop_infra.sh
# Start docker infra (nodejs, artifactory)
$ ./setup_infra.sh
# Kill &amp; Run app
$ pkill -f "node app"
$ nohup node app &amp;
# Prepare environment variables
$ SC_CONTRACT_DOCKER_VERSION="..."
$ APP_IP="192.168.0.100"
$ APP_PORT="3000"
$ ARTIFACTORY_PORT="8081"
$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
$ CURRENT_DIR="$( pwd )"
$ CURRENT_FOLDER_NAME=${PWD##*/}
$ PROJECT_VERSION="0.0.1.RELEASE"
# Execute contract tests
$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
# Kill app
$ pkill -f "node app"</code></pre>
</div>
</div>
<div class="paragraph">
<p>What will happen is that via bash scripts:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>infrastructure will be set up (MongoDb, Artifactory).
In real life scenario you would just run the NodeJS application
with mocked database. In this example we want to show how we can
benefit from Spring Cloud Contract in no time.</p>
</li>
<li>
<p>due to those constraints the contracts also represent the
stateful situation</p>
<div class="ulist">
<ul>
<li>
<p>first request is a <code>POST</code> that causes data to get inserted to the database</p>
</li>
<li>
<p>second request is a <code>GET</code> that returns a list of data with 1 previously inserted element</p>
</li>
</ul>
</div>
</li>
<li>
<p>the NodeJS application will be started (on port <code>3000</code>)</p>
</li>
<li>
<p>contract tests will be generated via Docker and tests
will be executed against the running application</p>
<div class="ulist">
<ul>
<li>
<p>the contracts will be taken from <code>/contracts</code> folder.</p>
</li>
<li>
<p>the output of the test execution is available under
<code>node_modules/spring-cloud-contract/output</code>.</p>
</li>
</ul>
</div>
</li>
<li>
<p>the stubs will be uploaded to Artifactory. You can check them out
under <a href="http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/" class="bare">http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/</a> .
The stubs will be here <a href="http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar" class="bare">http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar</a>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To see how the client side looks like check out the <a href="#stubrunner-docker">Stub Runner Docker</a> section.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier_messaging"><a class="link" href="#_spring_cloud_contract_verifier_messaging">Spring Cloud Contract Verifier Messaging</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Contract Verifier lets you verify applications that use messaging as a
means of communication. All of the integrations shown in this document work with Spring,
but you can also create one of your own and use that.</p>
</div>
<div class="sect2">
<h3 id="_integrations"><a class="link" href="#_integrations">Integrations</a></h3>
<div class="paragraph">
<p>You can use one of the following four integration configurations:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Apache Camel</p>
</li>
<li>
<p>Spring Integration</p>
</li>
<li>
<p>Spring Cloud Stream</p>
</li>
<li>
<p>Spring AMQP</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Since we use Spring Boot, if you have added one of these libraries to the classpath, all
the messaging configuration is automatically set up.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Remember to put <code>@AutoConfigureMessageVerifier</code> on the base class of your
generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not
work.
</td>
</tr>
</table>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you want to use Spring Cloud Stream, remember to add a dependency on
<code>org.springframework.cloud:spring-cloud-stream-test-support</code>, as shown here:
</td>
</tr>
</table>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-stream-test-support&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile "org.springframework.cloud:spring-cloud-stream-test-support"</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_manual_integration_testing"><a class="link" href="#_manual_integration_testing">Manual Integration Testing</a></h3>
<div class="paragraph">
<p>The main interface used by the tests is
<code>org.springframework.cloud.contract.verifier.messaging.MessageVerifier</code>.
It defines how to send and receive messages. You can create your own implementation to
achieve the same goal.</p>
</div>
<div class="paragraph">
<p>In a test, you can inject a <code>ContractVerifierMessageExchange</code> to send and receive
messages that follow the contract. Then add <code>@AutoConfigureMessageVerifier</code> to your test.
Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringTestRunner.class)
@SpringBootTest
@AutoConfigureMessageVerifier
public static class MessagingContractTests {
@Autowired
private MessageVerifier verifier;
...
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
If your tests require stubs as well, then <code>@AutoConfigureStubRunner</code> includes the
messaging configuration, so you only need the one annotation.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_publisher_side_test_generation"><a class="link" href="#_publisher_side_test_generation">Publisher-Side Test Generation</a></h3>
<div class="paragraph">
<p>Having the <code>input</code> or <code>outputMessage</code> sections in your DSL results in creation of tests
on the publisher&#8217;s side. By default, JUnit 4 tests are created. However, there is also a
possibility to create JUnit 5, TestNG or Spock tests.</p>
</div>
<div class="paragraph">
<p>There are 3 main scenarios that we should take into consideration:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>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).</p>
</li>
<li>
<p>Scenario 2: The input message triggers an output message.</p>
</li>
<li>
<p>Scenario 3: The input message is consumed and there is no output message.</p>
</li>
</ul>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The destination passed to <code>messageFrom</code> or <code>sentTo</code> can have different
meanings for different messaging implementations. For <strong>Stream</strong> and <strong>Integration</strong> it is
first resolved as a <code>destination</code> of a channel. Then, if there is no such <code>destination</code>
it is resolved as a channel name. For <strong>Camel</strong>, that&#8217;s a certain component (for example,
<code>jms</code>).
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_scenario_1_no_input_message"><a class="link" href="#_scenario_1_no_input_message">Scenario 1: No Input Message</a></h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> def contractDsl = Contract.make {
name "foo"
label 'some_label'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('activemq:output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
messagingContentType(applicationJson())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">label: some_label
input:
triggeredBy: bookReturnedTriggered
outputMessage:
sentTo: activemq:output
body:
bookName: foo
headers:
BOOK-NAME: foo
contentType: application/json</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following JUnit test is created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> '''\
package com.example;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import javax.inject.Inject;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
@SuppressWarnings("rawtypes")
public class FooTest {
\t@Inject ContractVerifierMessaging contractVerifierMessaging;
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
\t@Test
\tpublic void validate_foo() throws Exception {
\t\t// when:
\t\t\tbookReturnedTriggered();
\t\t// then:
\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
\t\t\tassertThat(response).isNotNull();
\t\t// and:
\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
\t\t\tassertThat(response.getHeader("contentType")).isNotNull();
\t\t\tassertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");
\t\t// and:
\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
\t}
}
'''</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> '''\
package com.example
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import javax.inject.Inject
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
@SuppressWarnings("rawtypes")
class FooSpec extends Specification {
\t@Inject ContractVerifierMessaging contractVerifierMessaging
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
\tdef validate_foo() throws Exception {
\t\twhen:
\t\t\tbookReturnedTriggered()
\t\tthen:
\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output")
\t\t\tresponse != null
\t\tand:
\t\t\tresponse.getHeader("BOOK-NAME") != null
\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
\t\t\tresponse.getHeader("contentType") != null
\t\t\tresponse.getHeader("contentType").toString() == 'application/json'
\t\tand:
\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
\t}
}
'''</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_scenario_2_output_triggered_by_input"><a class="link" href="#_scenario_2_output_triggered_by_input">Scenario 2: Output Triggered by Input</a></h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> def contractDsl = Contract.make {
name "foo"
label 'some_label'
input {
messageFrom('jms:input')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('jms:output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">label: some_label
input:
messageFrom: jms:input
messageBody:
bookName: 'foo'
messageHeaders:
sample: header
outputMessage:
sentTo: jms:output
body:
bookName: foo
headers:
BOOK-NAME: foo</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following JUnit test is created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> '''\
package com.example;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import javax.inject.Inject;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
@SuppressWarnings("rawtypes")
public class FooTest {
\t@Inject ContractVerifierMessaging contractVerifierMessaging;
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
\t@Test
\tpublic void validate_foo() throws Exception {
\t\t// given:
\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
\t\t\t\t\t\t, headers()
\t\t\t\t\t\t\t.header("sample", "header")
\t\t\t);
\t\t// when:
\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input");
\t\t// then:
\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
\t\t\tassertThat(response).isNotNull();
\t\t// and:
\t\t\tassertThat(response.getHeader("BOOK-NAME")).isNotNull();
\t\t\tassertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
\t\t// and:
\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
\t}
}
'''</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> """\
package com.example
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import javax.inject.Inject
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
@SuppressWarnings("rawtypes")
class FooSpec extends Specification {
\t@Inject ContractVerifierMessaging contractVerifierMessaging
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
\tdef validate_foo() throws Exception {
\t\tgiven:
\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
\t\t\t\t\t'''{"bookName":"foo"}'''
\t\t\t\t\t\t, headers()
\t\t\t\t\t\t\t.header("sample", "header")
\t\t\t)
\t\twhen:
\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:input")
\t\tthen:
\t\t\tContractVerifierMessage response = contractVerifierMessaging.receive("jms:output")
\t\t\tresponse != null
\t\tand:
\t\t\tresponse.getHeader("BOOK-NAME") != null
\t\t\tresponse.getHeader("BOOK-NAME").toString() == 'foo'
\t\tand:
\t\t\tDocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
\t\t\tassertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
\t}
}
"""</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_scenario_3_no_output_message"><a class="link" href="#_scenario_3_no_output_message">Scenario 3: No Output Message</a></h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> def contractDsl = Contract.make {
name "foo"
label 'some_label'
input {
messageFrom('jms:delete')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
assertThat('bookWasDeleted()')
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">label: some_label
input:
messageFrom: jms:delete
messageBody:
bookName: 'foo'
messageHeaders:
sample: header
assertThat: bookWasDeleted()</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following JUnit test is created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> """\
package com.example;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import javax.inject.Inject;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;
@SuppressWarnings("rawtypes")
public class FooTest {
\t@Inject ContractVerifierMessaging contractVerifierMessaging;
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper;
\t@Test
\tpublic void validate_foo() throws Exception {
\t\t// given:
\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
\t\t\t\t\t"{\\"bookName\\":\\"foo\\"}"
\t\t\t\t\t\t, headers()
\t\t\t\t\t\t\t.header("sample", "header")
\t\t\t);
\t\t// when:
\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete");
\t\t\tbookWasDeleted();
\t}
}
"""</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> """\
package com.example
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import javax.inject.Inject
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes
@SuppressWarnings("rawtypes")
class FooSpec extends Specification {
\t@Inject ContractVerifierMessaging contractVerifierMessaging
\t@Inject ContractVerifierObjectMapper contractVerifierObjectMapper
\tdef validate_foo() throws Exception {
\t\tgiven:
\t\t\tContractVerifierMessage inputMessage = contractVerifierMessaging.create(
\t\t\t\t\t'''{"bookName":"foo"}'''
\t\t\t\t\t\t, headers()
\t\t\t\t\t\t\t.header("sample", "header")
\t\t\t)
\t\twhen:
\t\t\tcontractVerifierMessaging.send(inputMessage, "jms:delete")
\t\t\tbookWasDeleted()
\t\tthen:
\t\t\tnoExceptionThrown()
\t}
}
"""</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_consumer_stub_generation"><a class="link" href="#_consumer_stub_generation">Consumer Stub Generation</a></h3>
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>For more information, see <a href="#stub-runner-for-messaging">Stub Runner for Messaging</a> section.</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-stream-rabbit&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-stub-runner&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-stream-test-support&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;dependencyManagement&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;
&lt;version&gt;Hoxton.BUILD-SNAPSHOT&lt;/version&gt;
&lt;type&gt;pom&lt;/type&gt;
&lt;scope&gt;import&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/dependencyManagement&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
// Automatically added by plugin:
// copyContracts - copies contracts to the output folder from which JAR will be created
// verifierStubsJar - JAR with a provided stub suffix
// the presented publication is also added by the plugin but you can modify it as you wish
publishing {
publications {
stubs(MavenPublication) {
artifactId "${project.name}-stubs"
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_stub_runner"><a class="link" href="#_spring_cloud_contract_stub_runner">Spring Cloud Contract Stub Runner</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<div class="sect2">
<h3 id="_snapshot_versions"><a class="link" href="#_snapshot_versions">Snapshot versions</a></h3>
<div class="paragraph">
<p>Add the additional snapshot repository to your <code>build.gradle</code> file to use snapshot
versions, which are automatically uploaded after every successful build:</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;repositories&gt;
&lt;repository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;repository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/repository&gt;
&lt;/repositories&gt;
&lt;pluginRepositories&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-snapshots&lt;/id&gt;
&lt;name&gt;Spring Snapshots&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/snapshot&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;true&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-milestones&lt;/id&gt;
&lt;name&gt;Spring Milestones&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;pluginRepository&gt;
&lt;id&gt;spring-releases&lt;/id&gt;
&lt;name&gt;Spring Releases&lt;/name&gt;
&lt;url&gt;https://repo.spring.io/release&lt;/url&gt;
&lt;snapshots&gt;
&lt;enabled&gt;false&lt;/enabled&gt;
&lt;/snapshots&gt;
&lt;/pluginRepository&gt;
&lt;/pluginRepositories&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
repositories {
mavenCentral()
mavenLocal()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/release" }
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="publishing-stubs-as-jars"><a class="link" href="#publishing-stubs-as-jars">Publishing Stubs as JARs</a></h3>
<div class="paragraph">
<p>The easiest approach would be to centralize the way stubs are kept. For example, you can
keep them as jars in a Maven repository.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
For both Maven and Gradle, the setup comes ready to work. However, you can customize
it if you want to.
</td>
</tr>
</table>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;!-- First disable the default jar setup in the properties section --&gt;
&lt;!-- we don't want the verifier to do a jar for us --&gt;
&lt;spring.cloud.contract.verifier.skip&gt;true&lt;/spring.cloud.contract.verifier.skip&gt;
&lt;!-- Next add the assembly plugin to your build --&gt;
&lt;!-- we want the assembly plugin to generate the JAR --&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;id&gt;stub&lt;/id&gt;
&lt;phase&gt;prepare-package&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;single&lt;/goal&gt;
&lt;/goals&gt;
&lt;inherited&gt;false&lt;/inherited&gt;
&lt;configuration&gt;
&lt;attach&gt;true&lt;/attach&gt;
&lt;descriptors&gt;
${basedir}/src/assembly/stub.xml
&lt;/descriptors&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
&lt;!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml --&gt;
&lt;assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd"&gt;
&lt;id&gt;stubs&lt;/id&gt;
&lt;formats&gt;
&lt;format&gt;jar&lt;/format&gt;
&lt;/formats&gt;
&lt;includeBaseDirectory&gt;false&lt;/includeBaseDirectory&gt;
&lt;fileSets&gt;
&lt;fileSet&gt;
&lt;directory&gt;src/main/java&lt;/directory&gt;
&lt;outputDirectory&gt;/&lt;/outputDirectory&gt;
&lt;includes&gt;
&lt;include&gt;**com/example/model/*.*&lt;/include&gt;
&lt;/includes&gt;
&lt;/fileSet&gt;
&lt;fileSet&gt;
&lt;directory&gt;${project.build.directory}/classes&lt;/directory&gt;
&lt;outputDirectory&gt;/&lt;/outputDirectory&gt;
&lt;includes&gt;
&lt;include&gt;**com/example/model/*.*&lt;/include&gt;
&lt;/includes&gt;
&lt;/fileSet&gt;
&lt;fileSet&gt;
&lt;directory&gt;${project.build.directory}/snippets/stubs&lt;/directory&gt;
&lt;outputDirectory&gt;META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings&lt;/outputDirectory&gt;
&lt;includes&gt;
&lt;include&gt;**/*&lt;/include&gt;
&lt;/includes&gt;
&lt;/fileSet&gt;
&lt;fileSet&gt;
&lt;directory&gt;${basedir}/src/test/resources/contracts&lt;/directory&gt;
&lt;outputDirectory&gt;META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts&lt;/outputDirectory&gt;
&lt;includes&gt;
&lt;include&gt;**/*.groovy&lt;/include&gt;
&lt;/includes&gt;
&lt;/fileSet&gt;
&lt;/fileSets&gt;
&lt;/assembly&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
// Automatically added by plugin:
// copyContracts - copies contracts to the output folder from which JAR will be created
// verifierStubsJar - JAR with a provided stub suffix
// the presented publication is also added by the plugin but you can modify it as you wish
publishing {
publications {
stubs(MavenPublication) {
artifactId "${project.name}-stubs"
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_core"><a class="link" href="#_stub_runner_core">Stub Runner Core</a></h3>
<div class="paragraph">
<p>Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of
<a href="https://martinfowler.com/articles/consumerDrivenContracts.html">Consumer Driven Contracts</a>.</p>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<div class="sect3">
<h4 id="_retrieving_stubs"><a class="link" href="#_retrieving_stubs">Retrieving stubs</a></h4>
<div class="paragraph">
<p>You can pick the following options of acquiring stubs</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Aether based solution that downloads JARs with stubs from Artifactory / Nexus</p>
</li>
<li>
<p>Classpath scanning solution that searches classpath via pattern to retrieve stubs</p>
</li>
<li>
<p>Write your own implementation of the <code>org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder</code> for full customization</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The latter example is described in the <a href="#custom_stub_runner">Custom Stub Runner</a> section.</p>
</div>
<div class="sect4">
<h5 id="_stub_downloading"><a class="link" href="#_stub_downloading">Stub downloading</a></h5>
<div class="paragraph">
<p>You can control the stub downloading via the <code>stubsMode</code> switch. It picks value from the
<code>StubRunnerProperties.StubsMode</code> enum. You can use the following options</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>StubRunnerProperties.StubsMode.CLASSPATH</code> (default value) - will pick stubs from the classpath</p>
</li>
<li>
<p><code>StubRunnerProperties.StubsMode.LOCAL</code> - will pick stubs from a local storage (e.g. <code>.m2</code>)</p>
</li>
<li>
<p><code>StubRunnerProperties.StubsMode.REMOTE</code> - will pick stubs from a remote location</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(repositoryRoot="https://foo.bar", ids = "com.example:beer-api-producer:+:stubs:8095", stubsMode = StubRunnerProperties.StubsMode.LOCAL)</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_classpath_scanning"><a class="link" href="#_classpath_scanning">Classpath scanning</a></h5>
<div class="paragraph">
<p>If you set the <code>stubsMode</code> property to <code>StubRunnerProperties.StubsMode.CLASSPATH</code>
(or set nothing since <code>CLASSPATH</code> is the default value) then classpath will get scanned.
Let&#8217;s look at the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids = {
"com.example:beer-api-producer:+:stubs:8095",
"com.example.foo:bar:1.0.0:superstubs:8096"
})</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you&#8217;ve added the dependencies to your classpath</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;com.example&lt;/groupId&gt;
&lt;artifactId&gt;beer-api-producer-restdocs&lt;/artifactId&gt;
&lt;classifier&gt;stubs&lt;/classifier&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;*&lt;/groupId&gt;
&lt;artifactId&gt;*&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.example.foo&lt;/groupId&gt;
&lt;artifactId&gt;bar&lt;/artifactId&gt;
&lt;classifier&gt;superstubs&lt;/classifier&gt;
&lt;version&gt;1.0.0&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;*&lt;/groupId&gt;
&lt;artifactId&gt;*&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
transitive = false
}
testCompile("com.example.foo:bar:1.0.0:superstubs") {
transitive = false
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then the following locations on your classpath will get scanned. For <code>com.example:beer-api-producer-restdocs</code></p>
</div>
<div class="ulist">
<ul>
<li>
<p>/META-INF/com.example/beer-api-producer-restdocs/<strong>*/</strong>.*</p>
</li>
<li>
<p>/contracts/com.example/beer-api-producer-restdocs/<strong>*/</strong>.*</p>
</li>
<li>
<p>/mappings/com.example/beer-api-producer-restdocs/<strong>*/</strong>.*</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>and <code>com.example.foo:bar</code></p>
</div>
<div class="ulist">
<ul>
<li>
<p>/META-INF/com.example.foo/bar/<strong>*/</strong>.*</p>
</li>
<li>
<p>/contracts/com.example.foo/bar/<strong>*/</strong>.*</p>
</li>
<li>
<p>/mappings/com.example.foo/bar/<strong>*/</strong>.*</p>
</li>
</ul>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
As you can see you have to explicitly provide the group and artifact ids when packaging the
producer stubs.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The producer would setup the contracts like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── src
└── test
└── resources
└── contracts
   └── com.example
      └── beer-api-producer-restdocs
      └── nested
      └── contract3.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>To achieve proper stub packaging.</p>
</div>
<div class="paragraph">
<p>Or using the <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/2.2.x/producer_with_restdocs/pom.xml">Maven <code>assembly</code> plugin</a> or
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/2.2.x/producer_with_restdocs/build.gradle">Gradle Jar</a> task you have to create the following
structure in your stubs jar.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── META-INF
└── com.example
└── beer-api-producer-restdocs
└── 2.0.0
├── contracts
│   └── nested
   │ └── contract2.groovy
   └── mappings
   └── mapping.json</code></pre>
</div>
</div>
<div class="paragraph">
<p>By maintaining this structure classpath gets scanned and you can profit from the messaging /
HTTP stubs without the need to download artifacts.</p>
</div>
</div>
<div class="sect4">
<h5 id="_configuring_http_server_stubs"><a class="link" href="#_configuring_http_server_stubs">Configuring HTTP Server Stubs</a></h5>
<div class="paragraph">
<p>Stub Runner has a notion of a <code>HttpServerStub</code> that abstracts the underlaying
concrete implementation of the HTTP server (e.g. WireMock is one of the implementations).
Sometimes, you need to perform some additional tuning of the stub servers,
that is concrete for the given implementation. To do that, Stub Runner gives you
the <code>httpServerStubConfigurer</code> property that is available in the annotation,
JUnit rule, and is accessible via system properties, where you can provide
your implementation of the <code>org.springframework.cloud.contract.stubrunner.HttpServerStubConfigurer</code> interface. The implementations can alter
the configuration files for the given HTTP server stub.</p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Stub Runner comes with an implementation that you
can extend, for WireMock - <code>org.springframework.cloud.contract.stubrunner.provider.wiremock.WireMockHttpServerStubConfigurer</code>. In the <code>configure</code> method
you can provide your own, custom configuration for the given stub. The use
case might be starting WireMock for the given artifact id, on an HTTPs port. Example:</p>
</div>
<div class="listingblock">
<div class="title">WireMockHttpServerStubConfigurer implementation</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@CompileStatic
static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
@Override
WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
int httpsPort = SocketUtils.findAvailableTcpPort()
log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
return httpStubConfiguration
.httpsPort(httpsPort)
}
return httpStubConfiguration
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can then reuse it via the annotation</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
httpServerStubConfigurer = HttpsForFraudDetection)</code></pre>
</div>
</div>
<div class="paragraph">
<p>Whenever an https port is found, it will take precedence over the http one.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_running_stubs"><a class="link" href="#_running_stubs">Running stubs</a></h4>
<div class="sect4">
<h5 id="_running_using_main_app"><a class="link" href="#_running_using_main_app">Running using main app</a></h5>
<div class="paragraph">
<p>You can set the following options to the main class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">-c, --classifier Suffix for the jar containing stubs (e.
g. 'stubs' if the stub jar would
have a 'stubs' classifier for stubs:
foobar-stubs ). Defaults to 'stubs'
(default: stubs)
--maxPort, --maxp &lt;Integer&gt; Maximum port value to be assigned to
the WireMock instance. Defaults to
15000 (default: 15000)
--minPort, --minp &lt;Integer&gt; Minimum port value to be assigned to
the WireMock instance. Defaults to
10000 (default: 10000)
-p, --password Password to user when connecting to
repository
--phost, --proxyHost Proxy host to use for repository
requests
--pport, --proxyPort [Integer] Proxy port to use for repository
requests
-r, --root Location of a Jar containing server
where you keep your stubs (e.g. http:
//nexus.
net/content/repositories/repository)
-s, --stubs Comma separated list of Ivy
representation of jars with stubs.
Eg. groupid:artifactid1,groupid2:
artifactid2:classifier
--sm, --stubsMode Stubs mode to be used. Acceptable values
[CLASSPATH, LOCAL, REMOTE]
-u, --username Username to user when connecting to
repository</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_http_stubs"><a class="link" href="#_http_stubs">HTTP Stubs</a></h5>
<div class="paragraph">
<p>Stubs are defined in JSON documents, whose syntax is defined in <a href="http://wiremock.org/stubbing.html">WireMock documentation</a></p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-javascript hljs" data-lang="javascript">{
"request": {
"method": "GET",
"url": "/ping"
},
"response": {
"status": 200,
"body": "pong",
"headers": {
"Content-Type": "text/plain"
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_viewing_registered_mappings"><a class="link" href="#_viewing_registered_mappings">Viewing registered mappings</a></h5>
<div class="paragraph">
<p>Every stubbed collaborator exposes list of defined mappings under <code>__/admin/</code> endpoint.</p>
</div>
<div class="paragraph">
<p>You can also use the <code>mappingsOutputFolder</code> property to dump the mappings to files.
For annotation based approach it would look like this</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
mappingsOutputFolder = "target/outputmappings/")</code></pre>
</div>
</div>
<div class="paragraph">
<p>and for the JUnit approach like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
.repoRoot("https://some_url")
.downloadStub("a.b.c", "loanIssuance")
.downloadStub("a.b.c:fraudDetectionServer")
.withMappingsOutputFolder("target/outputmappings")</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then if you check out the folder <code>target/outputmappings</code> you would see the following structure</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">.
├── fraudDetectionServer_13705
└── loanIssuance_12255</code></pre>
</div>
</div>
<div class="paragraph">
<p>That means that there were two stubs registered. <code>fraudDetectionServer</code> was registered at port <code>13705</code>
and <code>loanIssuance</code> at port <code>12255</code>. If we take a look at one of the files we would see (for WireMock)
mappings available for the given server:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">[{
"id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
"request" : {
"url" : "/name",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "fraudDetectionServer"
},
"uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
},
...
]</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_messaging_stubs"><a class="link" href="#_messaging_stubs">Messaging Stubs</a></h5>
<div class="paragraph">
<p>Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.</p>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_junit_rule_and_stub_runner_junit5_extension"><a class="link" href="#_stub_runner_junit_rule_and_stub_runner_junit5_extension">Stub Runner JUnit Rule and Stub Runner JUnit5 Extension</a></h3>
<div class="paragraph">
<p>Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")
.downloadStub(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");
@BeforeClass
@AfterClass
public static void setupProps() {
System.clearProperty("stubrunner.repository.root");
System.clearProperty("stubrunner.classifier");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>There&#8217;s also a <code>StubRunnerExtension</code> available for JUnit 5. <code>StubRunnerRule</code> and <code>StubRunnerExtension</code> work in a very
similar fashion. After the rule/ extension is executed, Stub Runner connects to your Maven repository and for the given list of dependencies tries to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>download them</p>
</li>
<li>
<p>cache them locally</p>
</li>
<li>
<p>unzip them to a temporary folder</p>
</li>
<li>
<p>start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port</p>
</li>
<li>
<p>feed the WireMock server with all JSON files that are valid WireMock definitions</p>
</li>
<li>
<p>can also send messages (remember to pass an implementation of <code>MessageVerifier</code> interface)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Stub Runner uses <a href="https://wiki.eclipse.org/Aether">Eclipse Aether</a> mechanism to download the Maven dependencies.
Check their <a href="https://wiki.eclipse.org/Aether">docs</a> for more information.</p>
</div>
<div class="paragraph">
<p>Since the <code>StubRunnerRule</code> and <code>StubRunnerExtension</code> implement the <code>StubFinder</code> they allow you to find the started stubs:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.springframework.cloud.contract.stubrunner;
import java.net.URL;
import java.util.Collection;
import java.util.Map;
import org.springframework.cloud.contract.spec.Contract;
/**
* Contract for finding registered stubs.
*
* @author Marcin Grzejszczak
*/
public interface StubFinder extends StubTrigger {
/**
* For the given groupId and artifactId tries to find the matching URL of the running
* stub.
* @param groupId - might be null. In that case a search only via artifactId takes
* place
* @param artifactId - artifact id of the stub
* @return URL of a running stub or throws exception if not found
* @throws StubNotFoundException in case of not finding a stub
*/
URL findStubUrl(String groupId, String artifactId) throws StubNotFoundException;
/**
* For the given Ivy notation {@code [groupId]:artifactId:[version]:[classifier]}
* tries to find the matching URL of the running stub. You can also pass only
* {@code artifactId}.
* @param ivyNotation - Ivy representation of the Maven artifact
* @return URL of a running stub or throws exception if not found
* @throws StubNotFoundException in case of not finding a stub
*/
URL findStubUrl(String ivyNotation) throws StubNotFoundException;
/**
* @return all running stubs
*/
RunningStubs findAllRunningStubs();
/**
* @return the list of Contracts
*/
Map&lt;StubConfiguration, Collection&lt;Contract&gt;&gt; getContracts();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of usage in Spock tests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ClassRule
@Shared
StubRunnerRule rule = new StubRunnerRule()
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
.withMappingsOutputFolder("target/outputmappingsforrule")
def 'should start WireMock servers'() {
expect: 'WireMocks are running'
rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
rule.findStubUrl('loanIssuance') != null
rule.findStubUrl('loanIssuance') == rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
rule.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
and:
rule.findAllRunningStubs().isPresent('loanIssuance')
rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
rule.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
and: 'Stubs were registered'
"${rule.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
"${rule.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
}
def 'should output mappings to output folder'() {
when:
def url = rule.findStubUrl('fraudDetectionServer')
then:
new File("target/outputmappingsforrule", "fraudDetectionServer_${url.port}").exists()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of usage in JUnit tests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> @Test
public void should_start_wiremock_servers() throws Exception {
// expect: 'WireMocks are running'
then(rule.findStubUrl("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isNotNull();
then(rule.findStubUrl("loanIssuance")).isEqualTo(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs", "loanIssuance"));
then(rule.findStubUrl(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isNotNull();
// and:
then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs",
"fraudDetectionServer")).isTrue();
then(rule.findAllRunningStubs().isPresent(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer"))
.isTrue();
// and: 'Stubs were registered'
then(httpGet(rule.findStubUrl("loanIssuance").toString() + "/name"))
.isEqualTo("loanIssuance");
then(httpGet(rule.findStubUrl("fraudDetectionServer").toString() + "/name"))
.isEqualTo("fraudDetectionServer");
}
private String httpGet(String url) throws Exception {
try (InputStream stream = URI.create(url).toURL().openStream()) {
return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>JUnit 5 Extension example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// Visible for Junit
@RegisterExtension
static StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.repoRoot(repoRoot()).stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")
.downloadStub(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
.withMappingsOutputFolder("target/outputmappingsforrule");
@BeforeAll
@AfterAll
static void setupProps() {
System.clearProperty("stubrunner.repository.root");
System.clearProperty("stubrunner.classifier");
}
private static String repoRoot() {
try {
return StubRunnerRuleJUnitTest.class.getResource("/m2repo/repository/")
.toURI().toString();
}
catch (Exception e) {
return "";
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Check the <strong>Common properties for JUnit and Spring</strong> for more information on how to apply global configuration of Stub Runner.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
To use the JUnit rule or JUnit 5 extension together with messaging, you have to provide an implementation of the
<code>MessageVerifier</code> interface to the rule builder (e.g. <code>rule.messageVerifier(new MyMessageVerifier())</code>).
If you don&#8217;t do this, then whenever you try to send a message an exception will be thrown.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_maven_settings"><a class="link" href="#_maven_settings">Maven settings</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
</div>
<div class="sect3">
<h4 id="_providing_fixed_ports"><a class="link" href="#_providing_fixed_ports">Providing fixed ports</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
</div>
<div class="sect3">
<h4 id="_fluent_api"><a class="link" href="#_fluent_api">Fluent API</a></h4>
<div class="paragraph">
<p>When using the <code>StubRunnerRule</code> or <code>StubRunnerExtension</code> you can add a stub to download and then pass the port for the last downloaded stub.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@ClassRule
public static StubRunnerRule rule = new StubRunnerRule().repoRoot(repoRoot())
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.downloadStub("org.springframework.cloud.contract.verifier.stubs",
"loanIssuance")
.withPort(12345).downloadStub(
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");
@BeforeClass
@AfterClass
public static void setupProps() {
System.clearProperty("stubrunner.repository.root");
System.clearProperty("stubrunner.classifier");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can see that for this example the following test is valid:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">then(rule.findStubUrl("loanIssuance"))
.isEqualTo(URI.create("http://localhost:12345").toURL());
then(rule.findStubUrl("fraudDetectionServer"))
.isEqualTo(URI.create("http://localhost:12346").toURL());</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_stub_runner_with_spring"><a class="link" href="#_stub_runner_with_spring">Stub Runner with Spring</a></h4>
<div class="paragraph">
<p>Sets up Spring configuration of the Stub Runner project.</p>
</div>
<div class="paragraph">
<p>By providing a list of stubs inside your configuration file the Stub Runner automatically downloads
and registers in WireMock the selected stubs.</p>
</div>
<div class="paragraph">
<p>If you want to find the URL of your stubbed dependency you can autowire the <code>StubFinder</code> interface and use
its methods as presented below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
@SpringBootTest(properties = [" stubrunner.cloud.enabled=false",
'foo=${stubrunner.runningstubs.fraudDetectionServer.port}',
'fooWithGroup=${stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port}'])
@AutoConfigureStubRunner(mappingsOutputFolder = "target/outputmappings/",
httpServerStubConfigurer = HttpsForFraudDetection)
@ActiveProfiles("test")
class StubRunnerConfigurationSpec extends Specification {
@Autowired
StubFinder stubFinder
@Autowired
Environment environment
@StubRunnerPort("fraudDetectionServer")
int fraudDetectionServerPort
@StubRunnerPort("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
int fraudDetectionServerPortWithGroupId
@Value('${foo}')
Integer foo
@BeforeClass
@AfterClass
void setupProps() {
System.clearProperty("stubrunner.repository.root")
System.clearProperty("stubrunner.classifier")
}
def 'should start WireMock servers'() {
expect: 'WireMocks are running'
stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance') != null
stubFinder.findStubUrl('loanIssuance') != null
stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs', 'loanIssuance')
stubFinder.findStubUrl('loanIssuance') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance')
stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT') == stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs')
stubFinder.findStubUrl('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer') != null
and:
stubFinder.findAllRunningStubs().isPresent('loanIssuance')
stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs', 'fraudDetectionServer')
stubFinder.findAllRunningStubs().isPresent('org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer')
and: 'Stubs were registered'
"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
and: 'Fraud Detection is an HTTPS endpoint'
stubFinder.findStubUrl('fraudDetectionServer').toString().startsWith("https")
}
def 'should throw an exception when stub is not found'() {
when:
stubFinder.findStubUrl('nonExistingService')
then:
thrown(StubNotFoundException)
when:
stubFinder.findStubUrl('nonExistingGroupId', 'nonExistingArtifactId')
then:
thrown(StubNotFoundException)
}
def 'should register started servers as environment variables'() {
expect:
environment.getProperty("stubrunner.runningstubs.loanIssuance.port") != null
stubFinder.findAllRunningStubs().getPort("loanIssuance") == (environment.getProperty("stubrunner.runningstubs.loanIssuance.port") as Integer)
and:
environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") as Integer)
and:
environment.getProperty("stubrunner.runningstubs.fraudDetectionServer.port") != null
stubFinder.findAllRunningStubs().getPort("fraudDetectionServer") == (environment.getProperty("stubrunner.runningstubs.org.springframework.cloud.contract.verifier.stubs.fraudDetectionServer.port") as Integer)
}
def 'should be able to interpolate a running stub in the passed test property'() {
given:
int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
expect:
fraudPort &gt; 0
environment.getProperty("foo", Integer) == fraudPort
environment.getProperty("fooWithGroup", Integer) == fraudPort
foo == fraudPort
}
@Issue("#573")
def 'should be able to retrieve the port of a running stub via an annotation'() {
given:
int fraudPort = stubFinder.findAllRunningStubs().getPort("fraudDetectionServer")
expect:
fraudPort &gt; 0
fraudDetectionServerPort == fraudPort
fraudDetectionServerPortWithGroupId == fraudPort
}
def 'should dump all mappings to a file'() {
when:
def url = stubFinder.findStubUrl("fraudDetectionServer")
then:
new File("target/outputmappings/", "fraudDetectionServer_${url.port}").exists()
}
@Configuration
@EnableAutoConfiguration
static class Config {}
@CompileStatic
static class HttpsForFraudDetection extends WireMockHttpServerStubConfigurer {
private static final Log log = LogFactory.getLog(HttpsForFraudDetection)
@Override
WireMockConfiguration configure(WireMockConfiguration httpStubConfiguration, HttpServerStubConfiguration httpServerStubConfiguration) {
if (httpServerStubConfiguration.stubConfiguration.artifactId == "fraudDetectionServer") {
int httpsPort = SocketUtils.findAvailableTcpPort()
log.info("Will set HTTPs port [" + httpsPort + "] for fraud detection server")
return httpStubConfiguration
.httpsPort(httpsPort)
}
return httpStubConfiguration
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>for the following configuration file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">stubrunner:
repositoryRoot: classpath:m2repo/repository/
ids:
- org.springframework.cloud.contract.verifier.stubs:loanIssuance
- org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer
- org.springframework.cloud.contract.verifier.stubs:bootService
stubs-mode: remote</code></pre>
</div>
</div>
<div class="paragraph">
<p>Instead of using the properties you can also use the properties inside the <code>@AutoConfigureStubRunner</code>.
Below you can find an example of achieving the same result by setting values on the annotation.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@AutoConfigureStubRunner(
ids = ["org.springframework.cloud.contract.verifier.stubs:loanIssuance",
"org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer",
"org.springframework.cloud.contract.verifier.stubs:bootService"],
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "classpath:m2repo/repository/")</code></pre>
</div>
</div>
<div class="paragraph">
<p>Stub Runner Spring registers environment variables in the following manner
for every registered WireMock server. Example for Stub Runner ids
<code>com.example:foo</code>, <code>com.example:bar</code>.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>stubrunner.runningstubs.foo.port</code></p>
</li>
<li>
<p><code>stubrunner.runningstubs.com.example.foo.port</code></p>
</li>
<li>
<p><code>stubrunner.runningstubs.bar.port</code></p>
</li>
<li>
<p><code>stubrunner.runningstubs.com.example.bar.port</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Which you can reference in your code.</p>
</div>
<div class="paragraph">
<p>You can also use the <code>@StubRunnerPort</code> annotation to inject the port of a running stub.
Value of the annotation can be the <code>groupid:artifactid</code> or just the <code>artifactid</code>. Example for Stub Runner ids
<code>com.example:foo</code>, <code>com.example:bar</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StubRunnerPort("foo")
int fooPort;
@StubRunnerPort("com.example:bar")
int barPort;</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_spring_cloud"><a class="link" href="#_stub_runner_spring_cloud">Stub Runner Spring Cloud</a></h3>
<div class="paragraph">
<p>Stub Runner can integrate with Spring Cloud.</p>
</div>
<div class="paragraph">
<p>For real life examples you can check the</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/producer">producer app sample</a></p>
</li>
<li>
<p><a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/consumer_with_discovery">consumer app sample</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_stubbing_service_discovery"><a class="link" href="#_stubbing_service_discovery">Stubbing Service Discovery</a></h4>
<div class="paragraph">
<p>The most important feature of <code>Stub Runner Spring Cloud</code> is the fact that it&#8217;s stubbing</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>DiscoveryClient</code></p>
</li>
<li>
<p><code>Ribbon</code> <code>ServerList</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>that means that regardless of the fact whether you&#8217;re using Zookeeper, Consul, Eureka or anything else, you don&#8217;t need that in your tests.
We&#8217;re starting WireMock instances of your dependencies and we&#8217;re telling your application whenever you&#8217;re using <code>Feign</code>, load balanced <code>RestTemplate</code>
or <code>DiscoveryClient</code> directly, to call those stubbed servers instead of calling the real Service Discovery tool.</p>
</div>
<div class="paragraph">
<p>For example this test will pass</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">def 'should make service discovery work'() {
expect: 'WireMocks are running'
"${stubFinder.findStubUrl('loanIssuance').toString()}/name".toURL().text == 'loanIssuance'
"${stubFinder.findStubUrl('fraudDetectionServer').toString()}/name".toURL().text == 'fraudDetectionServer'
and: 'Stubs can be reached via load service discovery'
restTemplate.getForObject('http://loanIssuance/name', String) == 'loanIssuance'
restTemplate.getForObject('http://someNameThatShouldMapFraudDetectionServer/name', String) == 'fraudDetectionServer'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>for the following configuration file</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">stubrunner:
idsToServiceIds:
ivyNotation: someValueInsideYourCode
fraudDetectionServer: someNameThatShouldMapFraudDetectionServer</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_test_profiles_and_service_discovery"><a class="link" href="#_test_profiles_and_service_discovery">Test profiles and service discovery</a></h5>
<div class="paragraph">
<p>In your integration tests you typically don&#8217;t want to call neither a discovery service (e.g. Eureka)
or Config Server. That&#8217;s why you create an additional test configuration in which you want to disable
these features.</p>
</div>
<div class="paragraph">
<p>Due to certain limitations of <a href="https://github.com/spring-cloud/spring-cloud-commons/issues/156"><code>spring-cloud-commons</code></a> to achieve this you have disable these properties
via a static block like presented below (example for Eureka)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> //Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
static {
System.setProperty("eureka.client.enabled", "false");
System.setProperty("spring.cloud.config.failFast", "false");
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_additional_configuration"><a class="link" href="#_additional_configuration">Additional Configuration</a></h4>
<div class="paragraph">
<p>You can match the artifactId of the stub with the name of your app by using the <code>stubrunner.idsToServiceIds:</code> map.
You can disable Stub Runner Ribbon support by providing: <code>stubrunner.cloud.ribbon.enabled</code> equal to <code>false</code>
You can disable Stub Runner support by providing: <code>stubrunner.cloud.enabled</code> equal to <code>false</code></p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
By default all service discovery will be stubbed. That means that regardless of the fact if you have
an existing <code>DiscoveryClient</code> its results will be ignored. However, if you want to reuse it, just set
<code>stubrunner.cloud.delegate.enabled</code> to <code>true</code> and then your existing <code>DiscoveryClient</code> results will be
merged with the stubbed ones.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The default Maven configuration used by Stub Runner can be tweaked either
via the following system properties or environment variables</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>maven.repo.local</code> - path to the custom maven local repository location</p>
</li>
<li>
<p><code>org.apache.maven.user-settings</code> - path to custom maven user settings location</p>
</li>
<li>
<p><code>org.apache.maven.global-settings</code> - path to maven global settings location</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_boot_application"><a class="link" href="#_stub_runner_boot_application">Stub Runner Boot Application</a></h3>
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>One of the use-cases is to run some smoke (end to end) tests on a deployed application.
You can check out the <a href="https://github.com/spring-cloud/spring-cloud-pipelines">Spring Cloud Pipelines</a>
project for more information.</p>
</div>
<div class="sect3">
<h4 id="_how_to_use_it"><a class="link" href="#_how_to_use_it">How to use it?</a></h4>
<div class="sect4">
<h5 id="_stub_runner_server"><a class="link" href="#_stub_runner_server">Stub Runner Server</a></h5>
<div class="paragraph">
<p>Just add the</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">compile "org.springframework.cloud:spring-cloud-starter-stub-runner"</code></pre>
</div>
</div>
<div class="paragraph">
<p>Annotate a class with <code>@EnableStubRunnerServer</code>, build a fat-jar and you&#8217;re ready to go!</p>
</div>
<div class="paragraph">
<p>For the properties check the <strong>Stub Runner Spring</strong> section.</p>
</div>
</div>
<div class="sect4">
<h5 id="_stub_runner_server_fat_jar"><a class="link" href="#_stub_runner_server_fat_jar">Stub Runner Server Fat Jar</a></h5>
<div class="paragraph">
<p>You can download a standalone JAR from Maven (e.g. for version 2.0.1.RELEASE), as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
$ java -jar stub-runner.jar --stubrunner.ids=... --stubrunner.repositoryRoot=...</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_spring_cloud_cli"><a class="link" href="#_spring_cloud_cli">Spring Cloud CLI</a></h5>
<div class="paragraph">
<p>Starting from <code>1.4.0.RELEASE</code> version of the <a href="https://cloud.spring.io/spring-cloud-cli">Spring Cloud CLI</a>
project you can start Stub Runner Boot by executing <code>spring cloud stubrunner</code>.</p>
</div>
<div class="paragraph">
<p>In order to pass the configuration just create a <code>stubrunner.yml</code> file in the current working directory
or a subdirectory called <code>config</code> or in <code>~/.spring-cloud</code>. The file could look like this
(example for running stubs installed locally)</p>
</div>
<div class="listingblock">
<div class="title">stubrunner.yml</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">stubrunner:
stubsMode: LOCAL
ids:
- com.example:beer-api-producer:+:9876</code></pre>
</div>
</div>
<div class="paragraph">
<p>and then just call <code>spring cloud stubrunner</code> from your terminal window to start
the Stub Runner server. It will be available at port <code>8750</code>.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_endpoints"><a class="link" href="#_endpoints">Endpoints</a></h4>
<div class="sect4">
<h5 id="_http"><a class="link" href="#_http">HTTP</a></h5>
<div class="ulist">
<ul>
<li>
<p>GET <code>/stubs</code> - returns a list of all running stubs in <code>ivy:integer</code> notation</p>
</li>
<li>
<p>GET <code>/stubs/{ivy}</code> - returns a port for the given <code>ivy</code> notation (when calling the endpoint <code>ivy</code> can also be <code>artifactId</code> only)</p>
</li>
</ul>
</div>
</div>
<div class="sect4">
<h5 id="_messaging"><a class="link" href="#_messaging">Messaging</a></h5>
<div class="paragraph">
<p>For Messaging</p>
</div>
<div class="ulist">
<ul>
<li>
<p>GET <code>/triggers</code> - returns a list of all running labels in <code>ivy : [ label1, label2 &#8230;&#8203;]</code> notation</p>
</li>
<li>
<p>POST <code>/triggers/{label}</code> - executes a trigger with <code>label</code></p>
</li>
<li>
<p>POST <code>/triggers/{ivy}/{label}</code> - executes a trigger with <code>label</code> for the given <code>ivy</code> notation (when calling the endpoint <code>ivy</code> can also be <code>artifactId</code> only)</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_example"><a class="link" href="#_example">Example</a></h4>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
@SpringBootTest(properties = "spring.cloud.zookeeper.enabled=false")
@ActiveProfiles("test")
class StubRunnerBootSpec extends Specification {
@Autowired
StubRunning stubRunning
def setup() {
RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning),
new TriggerController(stubRunning))
}
def 'should return a list of running stub servers in "full ivy:port" notation'() {
when:
String response = RestAssuredMockMvc.get('/stubs').body.asString()
then:
def root = new JsonSlurper().parseText(response)
root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs' instanceof Integer
}
def 'should return a port on which a [#stubId] stub is running'() {
when:
def response = RestAssuredMockMvc.get("/stubs/${stubId}")
then:
response.statusCode == 200
Integer.valueOf(response.body.asString()) &gt; 0
where:
stubId &lt;&lt; ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
'org.springframework.cloud.contract.verifier.stubs:bootService:+',
'org.springframework.cloud.contract.verifier.stubs:bootService',
'bootService']
}
def 'should return 404 when missing stub was called'() {
when:
def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
then:
response.statusCode == 404
}
def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
when:
String response = RestAssuredMockMvc.get('/triggers').body.asString()
then:
def root = new JsonSlurper().parseText(response)
root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book", "return_book_1", "return_book_2"])
}
def 'should trigger a messaging label'() {
given:
StubRunning stubRunning = Mock()
RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
when:
def response = RestAssuredMockMvc.post("/triggers/delete_book")
then:
response.statusCode == 200
and:
1 * stubRunning.trigger('delete_book')
}
def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
given:
StubRunning stubRunning = Mock()
RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
when:
def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
then:
response.statusCode == 200
and:
1 * stubRunning.trigger(stubId, 'delete_book')
where:
stubId &lt;&lt; ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
}
def 'should throw exception when trigger is missing'() {
when:
RestAssuredMockMvc.post("/triggers/missing_label")
then:
Exception e = thrown(Exception)
e.message.contains("Exception occurred while trying to return [missing_label] label.")
e.message.contains("Available labels are")
e.message.contains("org.springframework.cloud.contract.verifier.stubs:loanIssuance:0.0.1-SNAPSHOT:stubs=[]")
e.message.contains("org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs=")
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_stub_runner_boot_with_service_discovery"><a class="link" href="#_stub_runner_boot_with_service_discovery">Stub Runner Boot with Service Discovery</a></h4>
<div class="paragraph">
<p>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&#8217;s assume that you don&#8217;t want to deploy 50 microservice to a test environment in order
to check if your application is working fine. You&#8217;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
is to deploy your application to an environment, start it and run a couple of tests on it to see if
it&#8217;s working fine. We can call those tests smoke-tests since their idea is to check only a handful
of testing scenarios.</p>
</div>
<div class="paragraph">
<p>The problem with this approach is such that if you&#8217;re doing microservices most likely you&#8217;re
using a service discovery tool. Stub Runner Boot allows you to solve this issue by starting the
required stubs and register them in a service discovery tool. Let&#8217;s take a look at an example of
such a setup with Eureka. Let&#8217;s assume that Eureka was already running.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
@EnableStubRunnerServer
@EnableEurekaClient
@AutoConfigureStubRunner
public class StubRunnerBootEurekaExample {
public static void main(String[] args) {
SpringApplication.run(StubRunnerBootEurekaExample.class, args);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see we want to start a Stub Runner Boot server <code>@EnableStubRunnerServer</code>, enable Eureka client <code>@EnableEurekaClient</code>
and we want to have the stub runner feature turned on <code>@AutoConfigureStubRunner</code>.</p>
</div>
<div class="paragraph">
<p>Now let&#8217;s assume that we want to start this application so that the stubs get automatically registered.
We can do it by running the app <code>java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar</code> where
<code>${SYSTEM_PROPS}</code> would contain the following list of properties</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">* -Dstubrunner.repositoryRoot=https://repo.spring.io/snapshot (1)
* -Dstubrunner.cloud.stubbed.discovery.enabled=false (2)
* -Dstubrunner.ids=org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.
* springframework.cloud.contract.verifier.stubs:fraudDetectionServer,org.springframework.
* cloud.contract.verifier.stubs:bootService (3)
* -Dstubrunner.idsToServiceIds.fraudDetectionServer=
* someNameThatShouldMapFraudDetectionServer (4)
*
* (1) - we tell Stub Runner where all the stubs reside (2) - we don't want the default
* behaviour where the discovery service is stubbed. That's why the stub registration will
* be picked (3) - we provide a list of stubs to download (4) - we provide a list of</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 <code>application.yml</code> 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.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stubs_per_consumer"><a class="link" href="#_stubs_per_consumer">Stubs Per Consumer</a></h3>
<div class="paragraph">
<p>There are cases in which 2 consumers of the same endpoint want to have 2 different responses.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Let&#8217;s look at the following example for contract defined for the producer called <code>producer</code>.
There are 2 consumers: <code>foo-consumer</code> and <code>bar-consumer</code>.</p>
</div>
<div class="paragraph">
<p><strong>Consumer <code>foo-service</code></strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">request {
url '/foo'
method GET()
}
response {
status OK()
body(
foo: "foo"
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Consumer <code>bar-service</code></strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">request {
url '/foo'
method GET()
}
response {
status OK()
body(
bar: "bar"
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can&#8217;t produce for the same request 2 different responses. That&#8217;s why you can properly package the
contracts and then profit from the <code>stubsPerConsumer</code> feature.</p>
</div>
<div class="paragraph">
<p>On the producer side the consumers can have a folder that contains contracts related only to them.
By setting the <code>stubrunner.stubs-per-consumer</code> flag to <code>true</code> we no longer register all stubs but only those that
correspond to the consumer application&#8217;s name. In other words we&#8217;ll scan the path of every stub and
if it contains the subfolder with name of the consumer in the path only then will it get registered.</p>
</div>
<div class="paragraph">
<p>On the <code>foo</code> producer side the contracts would look like this</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">.
└── contracts
├── bar-consumer
│   ├── bookReturnedForBar.groovy
│   └── shouldCallBar.groovy
└── foo-consumer
├── bookReturnedForFoo.groovy
└── shouldCallFoo.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Being the <code>bar-consumer</code> consumer you can either set the <code>spring.application.name</code> or the <code>stubrunner.consumer-name</code> to <code>bar-consumer</code>
Or set the test as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
@SpringBootTest(properties = ["spring.application.name=bar-consumer"])
@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
repositoryRoot = "classpath:m2repo/repository/",
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
stubsPerConsumer = true)
class StubRunnerStubsPerConsumerSpec extends Specification {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then only the stubs registered under a path that contains the <code>bar-consumer</code> in its name (i.e. those from the
<code>src/test/resources/contracts/bar-consumer/some/contracts/&#8230;&#8203;</code> folder) will be allowed to be referenced.</p>
</div>
<div class="paragraph">
<p>Or set the consumer name explicitly</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
@SpringBootTest
@AutoConfigureStubRunner(ids = "org.springframework.cloud.contract.verifier.stubs:producerWithMultipleConsumers",
repositoryRoot = "classpath:m2repo/repository/",
consumerName = "foo-consumer",
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
stubsPerConsumer = true)
class StubRunnerStubsPerConsumerWithConsumerNameSpec extends Specification {
...
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then only the stubs registered under a path that contains the <code>foo-consumer</code> in its name (i.e. those from the
<code>src/test/resources/contracts/foo-consumer/some/contracts/&#8230;&#8203;</code> folder) will be allowed to be referenced.</p>
</div>
<div class="paragraph">
<p>You can check out <a href="https://github.com/spring-cloud/spring-cloud-contract/issues/224">issue 224</a> for more
information about the reasons behind this change.</p>
</div>
</div>
<div class="sect2">
<h3 id="_common"><a class="link" href="#_common">Common</a></h3>
<div class="paragraph">
<p>This section briefly describes common properties, including:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#common-properties-junit-spring">Common Properties for JUnit and Spring</a></p>
</li>
<li>
<p><a href="#stub-runner-stub-ids">Stub Runner Stubs IDs</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="common-properties-junit-spring"><a class="link" href="#common-properties-junit-spring">Common Properties for JUnit and Spring</a></h4>
<div class="paragraph">
<p>You can set repetitive properties by using system properties or Spring configuration
properties. Here are their names with their default values:</p>
</div>
<table class="tableblock frame-topbot grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Property name</th>
<th class="tableblock halign-left valign-top">Default value</th>
<th class="tableblock halign-left valign-top">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.minPort</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">10000</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Minimum value of a port for a started WireMock with stubs.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.maxPort</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">15000</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Maximum value of a port for a started WireMock with stubs.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.repositoryRoot</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Maven repo URL. If blank, then call the local maven repo.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.classifier</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubs</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Default classifier for the stub artifacts.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.stubsMode</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">CLASSPATH</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The way you want to fetch and register the stubs</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.ids</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Array of Ivy notation stubs to download.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.username</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Optional username to access the tool that stores the JARs with
stubs.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.password</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Optional password to access the tool that stores the JARs with
stubs.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.stubsPerConsumer</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">false</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Set to <code>true</code> if you want to use different stubs for
each consumer instead of registering all stubs for every consumer.</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.consumerName</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">If you want to use a stub for each consumer and want to
override the consumer name just change this value.</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="stub-runner-stub-ids"><a class="link" href="#stub-runner-stub-ids">Stub Runner Stubs IDs</a></h4>
<div class="paragraph">
<p>You can provide the stubs to download via the <code>stubrunner.ids</code> system property. They
follow this pattern:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">groupId:artifactId:version:classifier:port</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that <code>version</code>, <code>classifier</code> and <code>port</code> are optional.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If you do not provide the <code>port</code>, a random one will be picked.</p>
</li>
<li>
<p>If you do not provide the <code>classifier</code>, the default is used. (Note that you can
pass an empty classifier this way: <code>groupId:artifactId:version:</code>).</p>
</li>
<li>
<p>If you do not provide the <code>version</code>, then the <code>+</code> will be passed and the latest one is
downloaded.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><code>port</code> means the port of the WireMock server.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
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
<a href="https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges">Aether versioning
ranges here</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="stubrunner-docker"><a class="link" href="#stubrunner-docker">Stub Runner Docker</a></h3>
<div class="paragraph">
<p>We&#8217;re publishing a <code>spring-cloud/spring-cloud-contract-stub-runner</code> Docker image
that will start the standalone version of Stub Runner.</p>
</div>
<div class="paragraph">
<p>If you want to learn more about the basics of Maven, artifact ids,
group ids, classifiers and Artifact Managers, just click here <a href="#docker-project">Docker Project</a>.</p>
</div>
<div class="sect3">
<h4 id="_how_to_use_it_2"><a class="link" href="#_how_to_use_it_2">How to use it</a></h4>
<div class="paragraph">
<p>Just execute the docker image. You can pass any of the <a href="#common-properties-junit-spring">Common Properties for JUnit and Spring</a>
as environment variables. The convention is that all the
letters should be upper case. The camel case notation should
and the dot (<code>.</code>) should be separated via underscore (<code>_</code>). E.g.
the <code>stubrunner.repositoryRoot</code> property should be represented
as a <code>STUBRUNNER_REPOSITORY_ROOT</code> environment variable.</p>
</div>
</div>
<div class="sect3">
<h4 id="_example_of_client_side_usage_in_a_non_jvm_project"><a class="link" href="#_example_of_client_side_usage_in_a_non_jvm_project">Example of client side usage in a non JVM project</a></h4>
<div class="paragraph">
<p>We&#8217;d like to use the stubs created in this <a href="#docker-server-side">Server side (nodejs)</a> step.
Let&#8217;s assume that we want to run the stubs on port <code>9876</code>. The NodeJS code
is available here:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s run the Stub Runner Boot application with the stubs.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash"># Provide the Spring Cloud Contract Docker version
$ SC_CONTRACT_DOCKER_VERSION="..."
# The IP at which the app is running and Docker container can reach it
$ APP_IP="192.168.0.100"
# Spring Cloud Contract Stub Runner properties
$ STUBRUNNER_PORT="8083"
# Stub coordinates 'groupId:artifactId:version:classifier:port'
$ STUBRUNNER_IDS="com.example:bookstore:0.0.1.RELEASE:stubs:9876"
$ STUBRUNNER_REPOSITORY_ROOT="http://${APP_IP}:8081/artifactory/libs-release-local"
# Run the docker with Stub Runner Boot
$ docker run --rm -e "STUBRUNNER_IDS=${STUBRUNNER_IDS}" -e "STUBRUNNER_REPOSITORY_ROOT=${STUBRUNNER_REPOSITORY_ROOT}" -e "STUBRUNNER_STUBS_MODE=REMOTE" -p "${STUBRUNNER_PORT}:${STUBRUNNER_PORT}" -p "9876:9876" springcloud/spring-cloud-contract-stub-runner:"${SC_CONTRACT_DOCKER_VERSION}"</code></pre>
</div>
</div>
<div class="paragraph">
<p>What&#8217;s happening is that</p>
</div>
<div class="ulist">
<ul>
<li>
<p>a standalone Stub Runner application got started</p>
</li>
<li>
<p>it downloaded the stub with coordinates <code>com.example:bookstore:0.0.1.RELEASE:stubs</code> on port <code>9876</code></p>
</li>
<li>
<p>it got downloaded from Artifactory running at <code><a href="http://192.168.0.100:8081/artifactory/libs-release-local" class="bare">http://192.168.0.100:8081/artifactory/libs-release-local</a></code></p>
</li>
<li>
<p>after a while Stub Runner will be running on port <code>8083</code></p>
</li>
<li>
<p>and the stubs will be running at port <code>9876</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>On the server side we built a stateful stub. Let&#8217;s use curl to assert
that the stubs are setup properly.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash"># let's execute the first request (no response is returned)
$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
# Now time for the second request
$ curl -X GET http://localhost:9876/api/books
# You will receive contents of the JSON</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you want use the stubs that you have built locally, on your host,
then you should pass the environment variable <code>-e STUBRUNNER_STUBS_MODE=LOCAL</code> and mount
the volume of your local m2 <code>-v "${HOME}/.m2/:/root/.m2:ro"</code>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="stub-runner-for-messaging"><a class="link" href="#stub-runner-for-messaging">Stub Runner for Messaging</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Stub Runner can run the published stubs in memory. It can integrate with the following
frameworks:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Spring Integration</p>
</li>
<li>
<p>Spring Cloud Stream</p>
</li>
<li>
<p>Apache Camel</p>
</li>
<li>
<p>Spring AMQP</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>It also provides entry points to integrate with any other solution on the market.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you have multiple frameworks on the classpath Stub Runner will need to
define which one should be used. Let&#8217;s assume that you have both AMQP, Spring Cloud Stream and Spring Integration
on the classpath. Then you need to set <code>stubrunner.stream.enabled=false</code> and <code>stubrunner.integration.enabled=false</code>.
That way the only remaining framework is Spring AMQP.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_stub_triggering"><a class="link" href="#_stub_triggering">Stub triggering</a></h3>
<div class="paragraph">
<p>To trigger a message, use the <code>StubTrigger</code> interface:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.springframework.cloud.contract.stubrunner;
import java.util.Collection;
import java.util.Map;
/**
* Contract for triggering stub messages.
*
* @author Marcin Grzejszczak
*/
public interface StubTrigger {
/**
* Triggers an event by a given label for a given {@code groupid:artifactid} notation.
* You can use only {@code artifactId} too.
*
* Feature related to messaging.
* @param ivyNotation ivy notation of a stub
* @param labelName name of the label to trigger
* @return true - if managed to run a trigger
*/
boolean trigger(String ivyNotation, String labelName);
/**
* Triggers an event by a given label.
*
* Feature related to messaging.
* @param labelName name of the label to trigger
* @return true - if managed to run a trigger
*/
boolean trigger(String labelName);
/**
* Triggers all possible events.
*
* Feature related to messaging.
* @return true - if managed to run a trigger
*/
boolean trigger();
/**
* Feature related to messaging.
* @return a mapping of ivy notation of a dependency to all the labels it has.
*/
Map&lt;String, Collection&lt;String&gt;&gt; labels();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For convenience, the <code>StubFinder</code> interface extends <code>StubTrigger</code>, so you only need one
or the other in your tests.</p>
</div>
<div class="paragraph">
<p><code>StubTrigger</code> gives you the following options to trigger a message:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#trigger-label">Trigger by Label</a></p>
</li>
<li>
<p><a href="#trigger-group-artifact-ids">Trigger by Group and Artifact Ids</a></p>
</li>
<li>
<p><a href="#trigger-artifact-ids">Trigger by Artifact Ids</a></p>
</li>
<li>
<p><a href="#trigger-all-messages">Trigger All Messages</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="trigger-label"><a class="link" href="#trigger-label">Trigger by Label</a></h4>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="trigger-group-artifact-ids"><a class="link" href="#trigger-group-artifact-ids">Trigger by Group and Artifact Ids</a></h4>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="trigger-artifact-ids"><a class="link" href="#trigger-artifact-ids">Trigger by Artifact Ids</a></h4>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('streamService', 'return_book_1')</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="trigger-all-messages"><a class="link" href="#trigger-all-messages">Trigger All Messages</a></h4>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger()</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_camel"><a class="link" href="#_stub_runner_camel">Stub Runner Camel</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;s messaging module gives you an easy way to integrate with Apache Camel.
For the provided artifacts it will automatically download the stubs and register the required
routes.</p>
</div>
<div class="sect3">
<h4 id="_adding_it_to_the_project"><a class="link" href="#_adding_it_to_the_project">Adding it to the project</a></h4>
<div class="paragraph">
<p>It&#8217;s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath.
Remember to annotate your test class with <code>@AutoConfigureStubRunner</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_disabling_the_functionality"><a class="link" href="#_disabling_the_functionality">Disabling the functionality</a></h4>
<div class="paragraph">
<p>If you need to disable this functionality just pass <code>stubrunner.camel.enabled=false</code> property.</p>
</div>
</div>
<div class="sect3">
<h4 id="_examples"><a class="link" href="#_examples">Examples</a></h4>
<div class="sect4">
<h5 id="_stubs_structure"><a class="link" href="#_stubs_structure">Stubs structure</a></h5>
<div class="paragraph">
<p>Let us assume that we have the following Maven repository with a deployed stubs for the
<code>camelService</code> application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── camelService
├── 0.0.1-SNAPSHOT
│   ├── camelService-0.0.1-SNAPSHOT.pom
│   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s consider the following contracts (let' number it with <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_1'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('jms:output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and number <strong>2</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('jms:input')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('jms:output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_1_no_input_message_2"><a class="link" href="#_scenario_1_no_input_message_2">Scenario 1 (no input message)</a></h5>
<div class="paragraph">
<p>So as to trigger a message via the <code>return_book_1</code> label we&#8217;ll use the <code>StubTigger</code> interface as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>jms:output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
receivedMessage.in.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_2_output_triggered_by_input_2"><a class="link" href="#_scenario_2_output_triggered_by_input_2">Scenario 2 (output triggered by input)</a></h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>jms:output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">producerTemplate.
sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>jms:output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Exchange receivedMessage = consumerTemplate.receive('jms:output', 5000)</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
receivedMessage.in.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_3_input_with_no_output"><a class="link" href="#_scenario_3_input_with_no_output">Scenario 3 (input with no output)</a></h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>jms:output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">producerTemplate.
sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_integration"><a class="link" href="#_stub_runner_integration">Stub Runner Integration</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;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.</p>
</div>
<div class="sect3">
<h4 id="_adding_the_runner_to_the_project"><a class="link" href="#_adding_the_runner_to_the_project">Adding the Runner to the Project</a></h4>
<div class="paragraph">
<p>You can have both Spring Integration and Spring Cloud Contract Stub Runner on the
classpath. Remember to annotate your test class with <code>@AutoConfigureStubRunner</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_disabling_the_functionality_2"><a class="link" href="#_disabling_the_functionality_2">Disabling the functionality</a></h4>
<div class="paragraph">
<p>If you need to disable this functionality, set the
<code>stubrunner.integration.enabled=false</code> property.</p>
</div>
<div class="paragraph">
<p>Assume that you have the following Maven repository with deployed stubs for the
<code>integrationService</code> application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── integrationService
├── 0.0.1-SNAPSHOT
│   ├── integrationService-0.0.1-SNAPSHOT.pom
│   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>Further assume the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Consider the following contracts (numbered <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_1'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now consider <strong>2</strong>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('input')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and the following Spring Integration Route:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd"&gt;
&lt;!-- REQUIRED FOR TESTING --&gt;
&lt;bridge input-channel="output"
output-channel="outputTest"/&gt;
&lt;channel id="outputTest"&gt;
&lt;queue/&gt;
&lt;/channel&gt;
&lt;/beans:beans&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>These examples lend themselves to three scenarios:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#integration-scenario-1">Scenario 1 (no input message)</a></p>
</li>
<li>
<p><a href="#integration-scenario-2">Scenario 2 (output triggered by input)</a></p>
</li>
<li>
<p><a href="#integration-scenario-3">Scenario 3 (input with no output)</a></p>
</li>
</ul>
</div>
<div class="sect4">
<h5 id="integration-scenario-1"><a class="link" href="#integration-scenario-1">Scenario 1 (no input message)</a></h5>
<div class="paragraph">
<p>To trigger a message via the <code>return_book_1</code> label, use the <code>StubTigger</code> interface, as
follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>To listen to the output of the message sent to <code>output</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message&lt;?&gt; receivedMessage = messaging.receive('outputTest')</code></pre>
</div>
</div>
<div class="paragraph">
<p>The received message would pass the following assertions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="integration-scenario-2"><a class="link" href="#integration-scenario-2">Scenario 2 (output triggered by input)</a></h5>
<div class="paragraph">
<p>Since the route is set for you, you can send a message to the <code>output</code>
destination:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')</code></pre>
</div>
</div>
<div class="paragraph">
<p>To listen to the output of the message sent to <code>output</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message&lt;?&gt; receivedMessage = messaging.receive('outputTest')</code></pre>
</div>
</div>
<div class="paragraph">
<p>The received message passes the following assertions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="integration-scenario-3"><a class="link" href="#integration-scenario-3">Scenario 3 (input with no output)</a></h5>
<div class="paragraph">
<p>Since the route is set for you, you can send a message to the <code>input</code> destination:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_stream"><a class="link" href="#_stub_runner_stream">Stub Runner Stream</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;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.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
If Stub Runner&#8217;s integration with Stream the <code>messageFrom</code> or <code>sentTo</code> Strings
are resolved first as a <code>destination</code> of a channel and no such <code>destination</code> exists, the
destination is resolved as a channel name.
</td>
</tr>
</table>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you want to use Spring Cloud Stream remember, to add a dependency on
<code>org.springframework.cloud:spring-cloud-stream-test-support</code>.
</td>
</tr>
</table>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-stream-test-support&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile "org.springframework.cloud:spring-cloud-stream-test-support"</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_adding_the_runner_to_the_project_2"><a class="link" href="#_adding_the_runner_to_the_project_2">Adding the Runner to the Project</a></h4>
<div class="paragraph">
<p>You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the
classpath. Remember to annotate your test class with <code>@AutoConfigureStubRunner</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_disabling_the_functionality_3"><a class="link" href="#_disabling_the_functionality_3">Disabling the functionality</a></h4>
<div class="paragraph">
<p>If you need to disable this functionality, set the <code>stubrunner.stream.enabled=false</code>
property.</p>
</div>
<div class="paragraph">
<p>Assume that you have the following Maven repository with a deployed stubs for the
<code>streamService</code> application:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── streamService
├── 0.0.1-SNAPSHOT
│   ├── streamService-0.0.1-SNAPSHOT.pom
│   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>Further assume the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Consider the following contracts (numbered <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_1'
input { triggeredBy('bookReturnedTriggered()') }
outputMessage {
sentTo('returnBook')
body('''{ "bookName" : "foo" }''')
headers { header('BOOK-NAME', 'foo') }
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now consider <strong>2</strong>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('bookStorage')
messageBody([
bookName: 'foo'
])
messageHeaders { header('sample', 'header') }
}
outputMessage {
sentTo('returnBook')
body([
bookName: 'foo'
])
headers { header('BOOK-NAME', 'foo') }
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now consider the following Spring configuration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner.repositoryRoot: classpath:m2repo/repository/
stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
stubrunner.stubs-mode: remote
spring:
cloud:
stream:
bindings:
output:
destination: returnBook
input:
destination: bookStorage
server:
port: 0
debug: true</code></pre>
</div>
</div>
<div class="paragraph">
<p>These examples lend themselves to three scenarios:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#stream-scenario-1">Scenario 1 (no input message)</a></p>
</li>
<li>
<p><a href="#stream-scenario-2">Scenario 2 (output triggered by input)</a></p>
</li>
<li>
<p><a href="#stream-scenario-3">Scenario 3 (input with no output)</a></p>
</li>
</ul>
</div>
<div class="sect4">
<h5 id="stream-scenario-1"><a class="link" href="#stream-scenario-1">Scenario 1 (no input message)</a></h5>
<div class="paragraph">
<p>To trigger a message via the <code>return_book_1</code> label, use the <code>StubTrigger</code> interface as
follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>To listen to the output of the message sent to a channel whose <code>destination</code> is
<code>returnBook</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message&lt;?&gt; receivedMessage = messaging.receive('returnBook')</code></pre>
</div>
</div>
<div class="paragraph">
<p>The received message passes the following assertions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="stream-scenario-2"><a class="link" href="#stream-scenario-2">Scenario 2 (output triggered by input)</a></h5>
<div class="paragraph">
<p>Since the route is set for you, you can send a message to the <code>bookStorage</code>
<code>destination</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')</code></pre>
</div>
</div>
<div class="paragraph">
<p>To listen to the output of the message sent to <code>returnBook</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message&lt;?&gt; receivedMessage = messaging.receive('returnBook')</code></pre>
</div>
</div>
<div class="paragraph">
<p>The received message passes the following assertions:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="stream-scenario-3"><a class="link" href="#stream-scenario-3">Scenario 3 (input with no output)</a></h5>
<div class="paragraph">
<p>Since the route is set for you, you can send a message to the <code>output</code>
destination:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_spring_amqp"><a class="link" href="#_stub_runner_spring_amqp">Stub Runner Spring AMQP</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;s messaging module provides an easy way to
integrate with Spring AMQP&#8217;s Rabbit Template. For the provided artifacts, it
automatically downloads the stubs and registers the required routes.</p>
</div>
<div class="paragraph">
<p>The integration tries to work standalone (that is, without interaction with a running
RabbitMQ message broker). It expects a <code>RabbitTemplate</code> on the application context and
uses it as a spring boot test named <code>@SpyBean</code>. As a result, it can use the mockito spy
functionality to verify and inspect messages sent by the application.</p>
</div>
<div class="paragraph">
<p>On the message consumer side, the stub runner considers all <code>@RabbitListener</code> annotated
endpoints and all <code>SimpleMessageListenerContainer</code> objects on the application context.</p>
</div>
<div class="paragraph">
<p>As messages are usually sent to exchanges in AMQP, the message contract contains the
exchange name as the destination. Message listeners on the other side are bound to
queues. Bindings connect an exchange to a queue. If message contracts are triggered, the
Spring AMQP stub runner integration looks for bindings on the application context that
match this exchange. Then it collects the queues from the Spring exchanges and tries to
find message listeners bound to these queues. The message is triggered for all matching
message listeners.</p>
</div>
<div class="paragraph">
<p>If you need to work with routing keys, it&#8217;s enough to pass them via the <code>amqp_receivedRoutingKey</code>
messaging header.</p>
</div>
<div class="sect3">
<h4 id="_adding_the_runner_to_the_project_3"><a class="link" href="#_adding_the_runner_to_the_project_3">Adding the Runner to the Project</a></h4>
<div class="paragraph">
<p>You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and
set the property <code>stubrunner.amqp.enabled=true</code>. Remember to annotate your test class
with <code>@AutoConfigureStubRunner</code>.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you already have Stream and Integration on the classpath, you need
to disable them explicitly by setting the <code>stubrunner.stream.enabled=false</code> and
<code>stubrunner.integration.enabled=false</code> properties.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Assume that you have the following Maven repository with a deployed stubs for the
<code>spring-cloud-contract-amqp-test</code> application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── .m2
└── repository
└── com
└── example
└── spring-cloud-contract-amqp-test
├── 0.4.0-SNAPSHOT
│   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom
│   ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>Further assume that the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── contracts
└── shouldProduceValidPersonData.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Consider the following contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
// Human readable description
description 'Should produce valid person data'
// Label by means of which the output message can be triggered
label 'contract-test.person.created.event'
// input to the contract
input {
// the contract will be triggered by a method
triggeredBy('createPerson()')
}
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo 'contract-test.exchange'
headers {
header('contentType': 'application/json')
header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person')
}
// the body of the output message
body([
id : $(consumer(9), producer(regex("[0-9]+"))),
name: "me"
])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now consider the following Spring configuration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner:
repositoryRoot: classpath:m2repo/repository/
ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs
stubs-mode: remote
amqp:
enabled: true
server:
port: 0</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_triggering_the_message"><a class="link" href="#_triggering_the_message">Triggering the message</a></h5>
<div class="paragraph">
<p>To trigger a message using the contract above, use the <code>StubTrigger</code> interface as
follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">stubTrigger.trigger("contract-test.person.created.event")</code></pre>
</div>
</div>
<div class="paragraph">
<p>The message has a destination of <code>contract-test.exchange</code>, so the Spring AMQP stub runner
integration looks for bindings related to this exchange.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public Binding binding() {
return BindingBuilder.bind(new Queue("test.queue"))
.to(new DirectExchange("contract-test.exchange")).with("#");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The binding definition binds the queue <code>test.queue</code>. As a result, the following listener
definition is matched and invoked with the contract message.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public SimpleMessageListenerContainer simpleMessageListenerContainer(
ConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames("test.queue");
container.setMessageListener(listenerAdapter);
return container;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Also, the following annotated listener matches and is invoked:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"),
exchange = @Exchange(value = "contract-test.exchange",
ignoreDeclarationExceptions = "true")))
public void handlePerson(Person person) {
this.person = person;
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The message is directly handed over to the <code>onMessage</code> method of the
<code>MessageListener</code> associated with the matching <code>SimpleMessageListenerContainer</code>.
</td>
</tr>
</table>
</div>
</div>
<div class="sect4">
<h5 id="_spring_amqp_test_configuration"><a class="link" href="#_spring_amqp_test_configuration">Spring AMQP Test Configuration</a></h5>
<div class="paragraph">
<p>In order to avoid Spring AMQP trying to connect to a running broker during our tests
configure a mock <code>ConnectionFactory</code>.</p>
</div>
<div class="paragraph">
<p>To disable the mocked ConnectionFactory, set the following property:
<code>stubrunner.amqp.mockConnection=false</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner:
amqp:
mockConnection: false</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="contract-dsl"><a class="link" href="#contract-dsl">Contract DSL</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Contract supports out of the box 2 types of DSL. One written in
<code>Groovy</code> and one written in <code>YAML</code>.</p>
</div>
<div class="paragraph">
<p>If you decide to write the contract in Groovy, do not be alarmed if you have not used Groovy
before. Knowledge of the language is not really needed, as the Contract DSL uses only a
tiny subset of it (only literals, method calls and closures). Also, the DSL is statically
typed, to make it programmer-readable without any knowledge of the DSL itself.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Remember that, inside the Groovy contract file, you have to provide the fully
qualified name to the <code>Contract</code> class and <code>make</code> static imports, such as
<code>org.springframework.cloud.spec.Contract.make { &#8230;&#8203; }</code>. You can also provide an import to
the <code>Contract</code> class: <code>import org.springframework.cloud.spec.Contract</code> and then call
<code>Contract.make { &#8230;&#8203; }</code>.
</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Spring Cloud Contract supports defining multiple contracts in a single file.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following is a complete example of a Groovy contract definition:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"></code></pre>
</div>
</div>
<div class="paragraph">
<p>The following is a complete example of a YAML contract definition:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">description: Some description
name: some name
priority: 8
ignored: true
request:
url: /foo
queryParameters:
a: b
b: c
method: PUT
headers:
foo: bar
fooReq: baz
body:
foo: bar
matchers:
body:
- path: $.foo
type: by_regex
value: bar
headers:
- key: foo
regex: bar
response:
status: 200
headers:
foo2: bar
foo3: foo33
fooRes: baz
body:
foo2: bar
foo3: baz
nullValue: null
matchers:
body:
- path: $.foo2
type: by_regex
value: bar
- path: $.foo3
type: by_command
value: executeMe($it)
- path: $.nullValue
type: by_null
value: null
headers:
- key: foo2
regex: bar
- key: foo3
command: andMeToo($it)</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You can compile contracts to stubs mapping using standalone maven command:
<code>mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert</code>
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="_limitations"><a class="link" href="#_limitations">Limitations</a></h3>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Spring Cloud Contract Verifier does not properly support XML. Please use JSON or
help us implement this feature.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
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 <code>true</code>:
<code>spring.cloud.contract.verifier.assert.size</code>. By default, this feature is set to <code>false</code>.
You can also provide the <code>assertJsonSize</code> property in the plugin configuration.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Because JSON structure can have any form, it can be impossible to parse it
properly when using the Groovy DSL and the <code>value(consumer(&#8230;&#8203;), producer(&#8230;&#8203;))</code> notation in <code>GString</code>. That
is why you should use the Groovy Map notation.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_common_top_level_elements"><a class="link" href="#_common_top_level_elements">Common Top-Level elements</a></h3>
<div class="paragraph">
<p>The following sections describe the most common top-level elements:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#contract-dsl-description">Description</a></p>
</li>
<li>
<p><a href="#contract-dsl-name">Name</a></p>
</li>
<li>
<p><a href="#contract-dsl-ignoring-contracts">Ignoring Contracts</a></p>
</li>
<li>
<p><a href="#contract-dsl-passing-values-from-files">Passing Values from Files</a></p>
</li>
<li>
<p><a href="#contract-dsl-http-top-level-elements">HTTP Top-Level Elements</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="contract-dsl-description"><a class="link" href="#contract-dsl-description">Description</a></h4>
<div class="paragraph">
<p>You can add a <code>description</code> to your contract. The description is arbitrary text. The
following code shows an example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> org.springframework.cloud.contract.spec.Contract.make {
description('''
given:
An input
when:
Sth happens
then:
Output
''')
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">description: Some description
name: some name
priority: 8
ignored: true
request:
url: /foo
queryParameters:
a: b
b: c
method: PUT
headers:
foo: bar
fooReq: baz
body:
foo: bar
matchers:
body:
- path: $.foo
type: by_regex
value: bar
headers:
- key: foo
regex: bar
response:
status: 200
headers:
foo2: bar
foo3: foo33
fooRes: baz
body:
foo2: bar
foo3: baz
nullValue: null
matchers:
body:
- path: $.foo2
type: by_regex
value: bar
- path: $.foo3
type: by_command
value: executeMe($it)
- path: $.nullValue
type: by_null
value: null
headers:
- key: foo2
regex: bar
- key: foo3
command: andMeToo($it)</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-name"><a class="link" href="#contract-dsl-name">Name</a></h4>
<div class="paragraph">
<p>You can provide a name for your contract. Assume that you provided the following name:
<code>should register a user</code>. If you do so, the name of the autogenerated test is
<code>validate_should_register_a_user</code>. Also, the name of the stub in a WireMock stub is
<code>should_register_a_user.json</code>.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
name("some_special_name")
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">name: some name</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-ignoring-contracts"><a class="link" href="#contract-dsl-ignoring-contracts">Ignoring Contracts</a></h4>
<div class="paragraph">
<p>If you want to ignore a contract, you can either set a value of ignored contracts in the
plugin configuration or set the <code>ignored</code> property on the contract itself:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
ignored()
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">ignored: true</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-passing-values-from-files"><a class="link" href="#contract-dsl-passing-values-from-files">Passing Values from Files</a></h4>
<div class="paragraph">
<p>Starting with version <code>1.2.0</code>, you can pass values from files. Assume that you have the
following resources in our project.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">└── src
    └── test
       └── resources
          └── contracts
    ├── readFromFile.groovy
    ├── request.json
    └── response.json</code></pre>
</div>
</div>
<div class="paragraph">
<p>Further assume that your contract is as follows:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method('PUT')
headers {
contentType(applicationJson())
}
body(file("request.json"))
url("/1")
}
response {
status OK()
body(file("response.json"))
headers {
contentType(applicationJson())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
method: GET
url: /foo
bodyFromFile: request.json
response:
status: 200
bodyFromFile: response.json</code></pre>
</div>
</div>
<div class="paragraph">
<p>Further assume that the JSON files is as follows:</p>
</div>
<div class="paragraph">
<p><strong>request.json</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"status": "REQUEST"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>response.json</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"status": "RESPONSE"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>When test or stub generation takes place, the contents of the file is passed to the body
of a request or a response. The name of the file needs to be a file with location
relative to the folder in which the contract lays.</p>
</div>
<div class="paragraph">
<p>If you need to pass the contents of a file in a binary form
it&#8217;s enough for you to use the <code>fileAsBytes</code> method in Groovy DSL or <code>bodyFromFileAsBytes</code> field in YAML.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
url("/1")
method(PUT())
headers {
contentType(applicationOctetStream())
}
body(fileAsBytes("request.pdf"))
}
response {
status 200
body(fileAsBytes("response.pdf"))
headers {
contentType(applicationOctetStream())
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
url: /1
method: PUT
headers:
Content-Type: application/octet-stream
bodyFromFileAsBytes: request.pdf
response:
status: 200
bodyFromFileAsBytes: response.pdf
headers:
Content-Type: application/octet-stream</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
You should use this approach whenever you want to work with binary payloads both for HTTP and messaging.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-http-top-level-elements"><a class="link" href="#contract-dsl-http-top-level-elements">HTTP Top-Level Elements</a></h4>
<div class="paragraph">
<p>The following methods can be called in the top-level closure of a contract definition.
<code>request</code> and <code>response</code> are mandatory. <code>priority</code> is optional.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">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).
request {
method GET()
url "/foo"
//...
}
// Definition of HTTP response part of the contract
// (a service implementing this contract should respond
// with following response after receiving request
// specified in "request" part above).
response {
status 200
//...
}
// Contract priority, which can be used for overriding
// contracts (1 is highest). Priority is optional.
priority 1
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">priority: 8
request:
...
response:
...</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you want to make your contract have a <strong>higher</strong> value of priority
you need to pass a <strong>lower</strong> number to the <code>priority</code> tag / method. E.g. <code>priority</code> with
value <code>5</code> has <strong>higher</strong> priority than <code>priority</code> with value <code>10</code>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_request"><a class="link" href="#_request">Request</a></h3>
<div class="paragraph">
<p>The HTTP protocol requires only <strong>method and url</strong> to be specified in a request. The
same information is mandatory in request definition of the Contract.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
// HTTP request method (GET/POST/PUT/DELETE).
method 'GET'
// Path component of request URL is specified as follows.
urlPath('/users')
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">method: PUT
url: /foo</code></pre>
</div>
</div>
<div class="paragraph">
<p>It is possible to specify an absolute rather than relative <code>url</code>, but using <code>urlPath</code> is
the recommended way, as doing so makes the tests <strong>host-independent</strong>.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
// Specifying `url` and `urlPath` in one contract is illegal.
url('http://localhost:8888/users')
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
method: PUT
urlPath: /foo</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>request</code> may contain <strong>query parameters</strong>.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
method GET()
urlPath('/users') {
// Each parameter is specified in form
// `'paramName' : paramValue` where parameter value
// may be a simple literal or one of matcher functions,
// all of which are used in this example.
queryParameters {
// If a simple literal is used as value
// default matcher function is used (equalTo)
parameter 'limit': 100
// `equalTo` function simply compares passed value
// using identity operator (==).
parameter 'filter': equalTo("email")
// `containing` function matches strings
// that contains passed substring.
parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))
// `matching` function tests parameter
// against passed regular expression.
parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))
// `notMatching` functions tests if parameter
// does not match passed regular expression.
parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
}
}
//...
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
...
queryParameters:
a: b
b: c
headers:
foo: bar
fooReq: baz
cookies:
foo: bar
fooReq: baz
body:
foo: bar
matchers:
body:
- path: $.foo
type: by_regex
value: bar
headers:
- key: foo
regex: bar
response:
status: 200
fixedDelayMilliseconds: 1000
headers:
foo2: bar
foo3: foo33
fooRes: baz
body:
foo2: bar
foo3: baz
nullValue: null
matchers:
body:
- path: $.foo2
type: by_regex
value: bar
- path: $.foo3
type: by_command
value: executeMe($it)
- path: $.nullValue
type: by_null
value: null
headers:
- key: foo2
regex: bar
- key: foo3
command: andMeToo($it)
cookies:
- key: foo2
regex: bar
- key: foo3
predefined:</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>request</code> may contain additional <strong>request headers</strong>, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
method GET()
url "/foo"
// Each header is added in form `'Header-Name' : 'Header-Value'`.
// there are also some helper methods
headers {
header 'key': 'value'
contentType(applicationJson())
}
//...
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
...
headers:
foo: bar
fooReq: baz</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>request</code> may contain additional <strong>request cookies</strong>, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
method GET()
url "/foo"
// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
// there are also some helper methods
cookies {
cookie 'key': 'value'
cookie('another_key', 'another_value')
}
//...
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
...
cookies:
foo: bar
fooReq: baz</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>request</code> may contain a <strong>request body</strong>:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
method GET()
url "/foo"
// Currently only JSON format of request body is supported.
// Format will be determined from a header or body's content.
body '''{ "login" : "john", "name": "John The Contract" }'''
}
response {
//...
status 200
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
...
body:
foo: bar</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>request</code> may contain <strong>multipart</strong> elements. To include multipart elements, use the
<code>multipart</code> method/section, as shown in the following examples</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"></code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
method: PUT
url: /multipart
headers:
Content-Type: multipart/form-data;boundary=AaB03x
multipart:
params:
# key (parameter name), value (parameter value) pair
formParameter: '"formParameterValue"'
someBooleanParameter: true
named:
- paramName: file
fileName: filename.csv
fileContent: file content
matchers:
multipart:
params:
- key: formParameter
regex: ".+"
- key: someBooleanParameter
predefined: any_boolean
named:
- paramName: file
fileName:
predefined: non_empty
fileContent:
predefined: non_empty
response:
status: 200</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the preceding example, we define parameters in either of two ways:</p>
</div>
<div class="ulist">
<div class="title">Groovy DSL</div>
<ul>
<li>
<p>Directly, by using the map notation, where the value can be a dynamic property (such as
<code>formParameter: $(consumer(&#8230;&#8203;), producer(&#8230;&#8203;))</code>).</p>
</li>
<li>
<p>By using the <code>named(&#8230;&#8203;)</code> method that lets you set a named parameter. A named parameter
can set a <code>name</code> and <code>content</code>. You can call it either via a method with two arguments,
such as <code>named("fileName", "fileContent")</code>, or via a map notation, such as
<code>named(name: "fileName", content: "fileContent")</code>.</p>
</li>
</ul>
</div>
<div class="ulist">
<div class="title">YAML</div>
<ul>
<li>
<p>The multipart parameters are set via <code>multipart.params</code> section</p>
</li>
<li>
<p>The named parameters (the <code>fileName</code> and <code>fileContent</code> for a given parameter name)
can be set via the <code>multipart.named</code> section. That section contains
the <code>paramName</code> (name of the parameter), <code>fileName</code> (name of the file),
<code>fileContent</code> (content of the file) fields</p>
</li>
<li>
<p>The dynamic bits can be set via the <code>matchers.multipart</code> section</p>
<div class="ulist">
<ul>
<li>
<p>for parameters use the <code>params</code> section that can accept
<code>regex</code> or a <code>predefined</code> regular expression</p>
</li>
<li>
<p>for named params use the <code>named</code> section where first you
define the parameter name via <code>paramName</code> and then you can pass the
parametrization of either <code>fileName</code> or <code>fileContent</code> via
<code>regex</code> or a <code>predefined</code> regular expression</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>From this contract, the generated test is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "multipart/form-data;boundary=AaB03x")
.param("formParameter", "\"formParameterValue\"")
.param("someBooleanParameter", "true")
.multiPart("file", "filename.csv", "file content".getBytes());
// when:
ResponseOptions response = given().spec(request)
.put("/multipart");
// then:
assertThat(response.statusCode()).isEqualTo(200);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The WireMock stub is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json"> '''
{
"request" : {
"url" : "/multipart",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"matches" : "multipart/form-data;boundary=AaB03x.*"
}
},
"bodyPatterns" : [ {
"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
}, {
"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
}, {
"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
} ]
},
"response" : {
"status" : 200,
"transformers" : [ "response-template", "foo-transformer" ]
}
}
'''</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_response"><a class="link" href="#_response">Response</a></h3>
<div class="paragraph">
<p>The response must contain an <strong>HTTP status code</strong> and may contain other information. The
following code shows an example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
method GET()
url "/foo"
}
response {
// Status code sent by the server
// in response to request specified above.
status OK()
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">response:
...
status: 200</code></pre>
</div>
</div>
<div class="paragraph">
<p>Besides status, the response may contain <strong>headers</strong>, <strong>cookies</strong> and a <strong>body</strong>, both of which are
specified the same way as in the request (see the previous paragraph).</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
Via the Groovy DSL you can reference the <code>org.springframework.cloud.contract.spec.internal.HttpStatus</code>
methods to provide a meaningful status instead of a digit. E.g. you can call
<code>OK()</code> for a status <code>200</code> or <code>BAD_REQUEST()</code> for <code>400</code>.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_dynamic_properties"><a class="link" href="#_dynamic_properties">Dynamic properties</a></h3>
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>For Groovy DSL you can provide the dynamic parts in your contracts
in two ways: pass them directly in the body or set them in a separate section called
<code>bodyMatchers</code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Before 2.0.0 these were set using <code>testMatchers</code> and <code>stubMatchers</code>,
check out the <a href="https://github.com/spring-cloud/spring-cloud-contract/wiki/Spring-Cloud-Contract-2.0-Migration-Guide">migration guide</a> for more information.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>For YAML you can only use the <code>matchers</code> section.</p>
</div>
<div class="sect3">
<h4 id="_dynamic_properties_inside_the_body"><a class="link" href="#_dynamic_properties_inside_the_body">Dynamic properties inside the body</a></h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL. Check out the
<a href="#contract-matchers">Dynamic Properties in the Matchers Sections</a> section for YAML examples of a similar feature.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>You can set the properties inside the body either with the <code>value</code> method or, if you use
the Groovy map notation, with <code>$()</code>. The following example shows how to set dynamic
properties with the value method:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">value(consumer(...), producer(...))
value(c(...), p(...))
value(stub(...), test(...))
value(client(...), server(...))</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to set dynamic properties with <code>$()</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">$(consumer(...), producer(...))
$(c(...), p(...))
$(stub(...), test(...))
$(client(...), server(...))</code></pre>
</div>
</div>
<div class="paragraph">
<p>Both approaches work equally well. <code>stub</code> and <code>client</code> methods are aliases over the <code>consumer</code>
method. Subsequent sections take a closer look at what you can do with those values.</p>
</div>
</div>
<div class="sect3">
<h4 id="_regular_expressions"><a class="link" href="#_regular_expressions">Regular expressions</a></h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL. Check out the
<a href="#contract-matchers">Dynamic Properties in the Matchers Sections</a> section for YAML examples of a similar feature.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>Make sure that regex matches a whole region of a sequence as internally a call to
<a href="https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#matches--">Pattern.matches()</a>
is called. For instance, <code>abc</code> pattern doesn&#8217;t match <code>aabc</code> string but <code>.abc</code> does.
There are several additional <a href="#regex-limitations">known limitations</a> as well.</p>
</div>
<div class="paragraph">
<p>The following example shows how to use regular expressions to write a request:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method('GET')
url $(consumer(~/\/[0-9]{2}/), producer('/12'))
}
response {
status OK()
body(
id: $(anyNumber()),
surname: $(
consumer('Kowalsky'),
producer(regex('[a-zA-Z]+'))
),
name: 'Jan',
created: $(consumer('2014-02-02 12:23:43'), producer(execute('currentDate(it)'))),
correlationId: value(consumer('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
producer(regex('[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}'))
)
)
headers {
header 'Content-Type': 'text/plain'
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url value(consumer(regex('/foo/[0-9]{5}')))
body([
requestElement: $(consumer(regex('[0-9]{5}')))
])
headers {
header('header', $(consumer(regex('application\\/vnd\\.fraud\\.v1\\+json;.*'))))
}
}
response {
status OK()
body([
responseElement: $(producer(regex('[0-9]{7}')))
])
headers {
contentType("application/vnd.fraud.v1+json")
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the preceding example, the opposite side of the communication has the respective data
generated for request and response.</p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract comes with a series of predefined regular expressions that you can
use in your contracts, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">protected static final Pattern TRUE_OR_FALSE = Pattern.compile("(true|false)");
protected static final Pattern ALPHA_NUMERIC = Pattern.compile("[a-zA-Z0-9]+");
protected static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile("[\\p{L}]*");
protected static final Pattern NUMBER = Pattern.compile("-?(\\d*\\.\\d+|\\d+)");
protected static final Pattern INTEGER = Pattern.compile("-?(\\d+)");
protected static final Pattern POSITIVE_INT = Pattern.compile("([1-9]\\d*)");
protected static final Pattern DOUBLE = Pattern.compile("-?(\\d*\\.\\d+)");
protected static final Pattern HEX = Pattern.compile("[a-fA-F0-9]+");
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])");
protected static final Pattern HOSTNAME_PATTERN = Pattern
.compile("((http[s]?|ftp):/)/?([^:/\\s]+)(:[0-9]{1,5})?");
protected static final Pattern EMAIL = Pattern
.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
protected static final Pattern URL = UrlHelper.URL;
protected static final Pattern HTTPS_URL = UrlHelper.HTTPS_URL;
protected static final Pattern UUID = Pattern
.compile("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
protected static final Pattern ANY_DATE = Pattern
.compile("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
protected static final Pattern ANY_DATE_TIME = Pattern.compile(
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
protected static final Pattern ANY_TIME = Pattern
.compile("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
protected static final Pattern NON_EMPTY = Pattern.compile("[\\S\\s]+");
protected static final Pattern NON_BLANK = Pattern.compile("^\\s*\\S[\\S\\s]*");
protected static final Pattern ISO8601_WITH_OFFSET = Pattern.compile(
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d{3})?(Z|[+-][01]\\d:[0-5]\\d)");
protected static Pattern anyOf(String... values) {
return Pattern.compile(Arrays.stream(values).map(it -&gt; '^' + it + '$')
.collect(Collectors.joining("|")));
}
public static String multipartParam(Object name, Object value) {
return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+ "\"\r\n(Content-Type: .*\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+ value + "\r\n--\\1.*";
}
public static String multipartFile(Object name, Object filename, Object content,
Object contentType) {
return ".*--(.*)\r\nContent-Disposition: form-data; name=\"" + name
+ "\"; filename=\"" + filename + "\"\r\n(Content-Type: "
+ toContentType(contentType)
+ "\r\n)?(Content-Transfer-Encoding: .*\r\n)?(Content-Length: \\d+\r\n)?\r\n"
+ content + "\r\n--\\1.*";
}
private static String toContentType(Object contentType) {
if (contentType == null) {
return ".*";
}
if (contentType instanceof RegexProperty) {
return ((RegexProperty) contentType).pattern();
}
return contentType.toString();
}
public RegexProperty onlyAlphaUnicode() {
return new RegexProperty(ONLY_ALPHA_UNICODE).asString();
}
public RegexProperty alphaNumeric() {
return new RegexProperty(ALPHA_NUMERIC).asString();
}
public RegexProperty number() {
return new RegexProperty(NUMBER).asDouble();
}
public RegexProperty positiveInt() {
return new RegexProperty(POSITIVE_INT).asInteger();
}
public RegexProperty anyBoolean() {
return new RegexProperty(TRUE_OR_FALSE).asBooleanType();
}
public RegexProperty anInteger() {
return new RegexProperty(INTEGER).asInteger();
}
public RegexProperty aDouble() {
return new RegexProperty(DOUBLE).asDouble();
}
public RegexProperty ipAddress() {
return new RegexProperty(IP_ADDRESS).asString();
}
public RegexProperty hostname() {
return new RegexProperty(HOSTNAME_PATTERN).asString();
}
public RegexProperty email() {
return new RegexProperty(EMAIL).asString();
}
public RegexProperty url() {
return new RegexProperty(URL).asString();
}
public RegexProperty httpsUrl() {
return new RegexProperty(HTTPS_URL).asString();
}
public RegexProperty uuid() {
return new RegexProperty(UUID).asString();
}
public RegexProperty isoDate() {
return new RegexProperty(ANY_DATE).asString();
}
public RegexProperty isoDateTime() {
return new RegexProperty(ANY_DATE_TIME).asString();
}
public RegexProperty isoTime() {
return new RegexProperty(ANY_TIME).asString();
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In your contract, you can use it as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract dslWithOptionalsInString = Contract.make {
priority 1
request {
method POST()
url '/users/password'
headers {
contentType(applicationJson())
}
body(
email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
callback_url: $(consumer(regex(hostname())), producer('http://partners.com'))
)
}
response {
status 404
headers {
contentType(applicationJson())
}
body(
code: value(consumer("123123"), producer(optional("123123"))),
message: "User not found by email = [${value(producer(regex(email())), consumer('not.existing@user.com'))}]"
)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>To make matters even simpler you can use a set of predefined objects that will automatically assume that you want a regular expression to be passed.
All of those methods start with <code>any</code> prefix:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"></code></pre>
</div>
</div>
<div class="paragraph">
<p>and this is an example of how you can reference those methods:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract contractDsl = Contract.make {
name "foo"
label 'trigger_event'
input {
triggeredBy('toString()')
}
outputMessage {
sentTo 'topic.rateablequote'
body([
alpha : $(anyAlphaUnicode()),
number : $(anyNumber()),
anInteger : $(anyInteger()),
positiveInt : $(anyPositiveInt()),
aDouble : $(anyDouble()),
aBoolean : $(aBoolean()),
ip : $(anyIpAddress()),
hostname : $(anyHostname()),
email : $(anyEmail()),
url : $(anyUrl()),
httpsUrl : $(anyHttpsUrl()),
uuid : $(anyUuid()),
date : $(anyDate()),
dateTime : $(anyDateTime()),
time : $(anyTime()),
iso8601WithOffset: $(anyIso8601WithOffset()),
nonBlankString : $(anyNonBlankString()),
nonEmptyString : $(anyNonEmptyString()),
anyOf : $(anyOf('foo', 'bar'))
])
}
}</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="regex-limitations"><a class="link" href="#regex-limitations">Limitations</a></h5>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Due to certain limitations of <code>Xeger</code> library that generates string out of
regex, do not use <code>$</code> and <code>^</code> signs in your regex if you rely on automatic
generation. <a href="https://github.com/spring-cloud/spring-cloud-contract/issues/899">Issue 899</a>
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="fa icon-warning" title="Warning"></i>
</td>
<td class="content">
Do not use <code>LocalDate</code> instance as a value for <code>$</code> like this <code>$(consumer(LocalDate.now()))</code>.
It causes <code>java.lang.StackOverflowError</code>. Use <code>$(consumer(LocalDate.now().toString()))</code> instead.
<a href="https://github.com/spring-cloud/spring-cloud-contract/issues/900">Issue 900</a>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_passing_optional_parameters"><a class="link" href="#_passing_optional_parameters">Passing Optional Parameters</a></h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL. Check out the
<a href="#contract-matchers">Dynamic Properties in the Matchers Sections</a> section for YAML examples of a similar feature.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>It is possible to provide optional parameters in your contract. However, you can provide
optional parameters only for the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><em>STUB</em> side of the Request</p>
</li>
<li>
<p><em>TEST</em> side of the Response</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The following example shows how to provide optional parameters:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
priority 1
name "optionals"
request {
method 'POST'
url '/users/password'
headers {
contentType(applicationJson())
}
body(
email: $(consumer(optional(regex(email()))), producer('abc@abc.com')),
callback_url: $(consumer(regex(hostname())), producer('https://partners.com'))
)
}
response {
status 404
headers {
header 'Content-Type': 'application/json'
}
body(
code: value(consumer("123123"), producer(optional("123123")))
)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By wrapping a part of the body with the <code>optional()</code> method, you create a regular
expression that must be present 0 or more times.</p>
</div>
<div class="paragraph">
<p>If you use Spock for, the following test would be generated from the previous example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> """\
package com.example
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification
import io.restassured.response.ResponseOptions
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*
@SuppressWarnings("rawtypes")
class FooSpec extends Specification {
\tdef validate_optionals() throws Exception {
\t\tgiven:
\t\t\tMockMvcRequestSpecification request = given()
\t\t\t\t\t.header("Content-Type", "application/json")
\t\t\t\t\t.body('''{"email":"abc@abc.com","callback_url":"https://partners.com"}''')
\t\twhen:
\t\t\tResponseOptions response = given().spec(request)
\t\t\t\t\t.post("/users/password")
\t\tthen:
\t\t\tresponse.statusCode() == 404
\t\t\tresponse.header("Content-Type") == 'application/json'
\t\tand:
\t\t\tDocumentContext parsedJson = JsonPath.parse(response.body.asString())
\t\t\tassertThatJson(parsedJson).field("['code']").matches("(123123)?")
\t}
}
"""</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following stub would also be generated:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> '''
{
"request" : {
"url" : "/users/password",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['email'] =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,6})?/)]"
}, {
"matchesJsonPath" : "$[?(@.['callback_url'] =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
}
},
"response" : {
"status" : 404,
"body" : "{\\"code\\":\\"123123\\",\\"message\\":\\"User not found by email == [not.existing@user.com]\\"}",
"headers" : {
"Content-Type" : "application/json"
}
},
"priority" : 1
}
'''</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_executing_custom_methods_on_the_server_side"><a class="link" href="#_executing_custom_methods_on_the_server_side">Executing Custom Methods on the Server Side</a></h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL. Check out the
<a href="#contract-matchers">Dynamic Properties in the Matchers Sections</a> section for YAML examples of a similar feature.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"></code></pre>
</div>
</div>
<div class="paragraph">
<p>The following code shows the base class portion of the test case:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">abstract class BaseMockMvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
}
void isProperCorrelationId(Integer correlationId) {
assert correlationId == 123456
}
void isEmpty(String value) {
assert value == null
}
}</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
You cannot use both a String and <code>execute</code> to perform concatenation. For
example, calling <code>header('Authorization', 'Bearer ' + execute('authToken()'))</code> leads to
improper results. Instead, call <code>header('Authorization', execute('authToken()'))</code> and
ensure that the <code>authToken()</code> method returns everything you need.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The type of the object read from the JSON can be one of the following, depending on the
JSON path:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>String</code>: If you point to a <code>String</code> value in the JSON.</p>
</li>
<li>
<p><code>JSONArray</code>: If you point to a <code>List</code> in the JSON.</p>
</li>
<li>
<p><code>Map</code>: If you point to a <code>Map</code> in the JSON.</p>
</li>
<li>
<p><code>Number</code>: If you point to <code>Integer</code>, <code>Double</code> etc. in the JSON.</p>
</li>
<li>
<p><code>Boolean</code>: If you point to a <code>Boolean</code> in the JSON.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In the request part of the contract, you can specify that the <code>body</code> should be taken from
a method.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
You must provide both the consumer and the producer side. The <code>execute</code> part
is applied for the whole body - not for parts of it.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following example shows how to read an object from JSON:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract contractDsl = Contract.make {
request {
method 'GET'
url '/something'
body(
$(c('foo'), p(execute('hashCode()')))
)
}
response {
status OK()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The preceding example results in calling the <code>hashCode()</code> method in the request body.
It should resemble the following code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// given:
MockMvcRequestSpecification request = given()
.body(hashCode());
// when:
ResponseOptions response = given().spec(request)
.get("/something");
// then:
assertThat(response.statusCode()).isEqualTo(200);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_referencing_the_request_from_the_response"><a class="link" href="#_referencing_the_request_from_the_response">Referencing the Request from the Response</a></h4>
<div class="paragraph">
<p>The best situation is to provide fixed values, but sometimes you need to reference a
request in your response.</p>
</div>
<div class="paragraph">
<p>If you&#8217;re writing contracts using Groovy DSL, you can use the <code>fromRequest()</code> method, which lets
you reference a bunch of elements from the HTTP request. You can use the following
options:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>fromRequest().url()</code>: Returns the request URL and query parameters.</p>
</li>
<li>
<p><code>fromRequest().query(String key)</code>: Returns the first query parameter with a given name.</p>
</li>
<li>
<p><code>fromRequest().query(String key, int index)</code>: Returns the nth query parameter with a
given name.</p>
</li>
<li>
<p><code>fromRequest().path()</code>: Returns the full path.</p>
</li>
<li>
<p><code>fromRequest().path(int index)</code>: Returns the nth path element.</p>
</li>
<li>
<p><code>fromRequest().header(String key)</code>: Returns the first header with a given name.</p>
</li>
<li>
<p><code>fromRequest().header(String key, int index)</code>: Returns the nth header with a given name.</p>
</li>
<li>
<p><code>fromRequest().body()</code>: Returns the full request body.</p>
</li>
<li>
<p><code>fromRequest().body(String jsonPath)</code>: Returns the element from the request that
matches the JSON Path.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>If you&#8217;re using the YAML contract definition you have to use the
<a href="https://handlebarsjs.com/">Handlebars</a> <code>{{{ }}}</code> notation with custom, Spring Cloud Contract
functions to achieve this.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>{{{ request.url }}}</code>: Returns the request URL and query parameters.</p>
</li>
<li>
<p><code>{{{ request.query.key.[index] }}}</code>: Returns the nth query parameter with a given name.
E.g. for key <code>foo</code>, first entry <code>{{{ request.query.foo.[0] }}}</code></p>
</li>
<li>
<p><code>{{{ request.path }}}</code>: Returns the full path.</p>
</li>
<li>
<p><code>{{{ request.path.[index] }}}</code>: Returns the nth path element. E.g.
for first entry <code>`</code>{{{ request.path.[0] }}}</p>
</li>
<li>
<p><code>{{{ request.headers.key }}}</code>: Returns the first header with a given name.</p>
</li>
<li>
<p><code>{{{ request.headers.key.[index] }}}</code>: Returns the nth header with a given name.</p>
</li>
<li>
<p><code>{{{ request.body }}}</code>: Returns the full request body.</p>
</li>
<li>
<p><code>{{{ jsonpath this 'your.json.path' }}}</code>: Returns the element from the request that
matches the JSON Path. E.g. for json path <code>$.foo</code> - <code>{{{ jsonpath this '$.foo' }}}</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Consider the following contract:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"></code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
method: GET
url: /api/v1/xxxx
queryParameters:
foo:
- bar
- bar2
headers:
Authorization:
- secret
- secret2
body:
foo: bar
baz: 5
response:
status: 200
headers:
Authorization: "foo {{{ request.headers.Authorization.0 }}} bar"
body:
url: "{{{ request.url }}}"
path: "{{{ request.path }}}"
pathIndex: "{{{ request.path.1 }}}"
param: "{{{ request.query.foo }}}"
paramIndex: "{{{ request.query.foo.1 }}}"
authorization: "{{{ request.headers.Authorization.0 }}}"
authorization2: "{{{ request.headers.Authorization.1 }}"
fullBody: "{{{ request.body }}}"
responseFoo: "{{{ jsonpath this '$.foo' }}}"
responseBaz: "{{{ jsonpath this '$.baz' }}}"
responseBaz2: "Bla bla {{{ jsonpath this '$.foo' }}} bla bla"</code></pre>
</div>
</div>
<div class="paragraph">
<p>Running a JUnit test generation leads to a test that resembles the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// given:
MockMvcRequestSpecification request = given()
.header("Authorization", "secret")
.header("Authorization", "secret2")
.body("{\"foo\":\"bar\",\"baz\":5}");
// when:
ResponseOptions response = given().spec(request)
.queryParam("foo","bar")
.queryParam("foo","bar2")
.get("/api/v1/xxxx");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Authorization")).isEqualTo("foo secret bar");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['fullBody']").isEqualTo("{\"foo\":\"bar\",\"baz\":5}");
assertThatJson(parsedJson).field("['authorization']").isEqualTo("secret");
assertThatJson(parsedJson).field("['authorization2']").isEqualTo("secret2");
assertThatJson(parsedJson).field("['path']").isEqualTo("/api/v1/xxxx");
assertThatJson(parsedJson).field("['param']").isEqualTo("bar");
assertThatJson(parsedJson).field("['paramIndex']").isEqualTo("bar2");
assertThatJson(parsedJson).field("['pathIndex']").isEqualTo("v1");
assertThatJson(parsedJson).field("['responseBaz']").isEqualTo(5);
assertThatJson(parsedJson).field("['responseFoo']").isEqualTo("bar");
assertThatJson(parsedJson).field("['url']").isEqualTo("/api/v1/xxxx?foo=bar&amp;foo=bar2");
assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla");</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, elements from the request have been properly referenced in the response.</p>
</div>
<div class="paragraph">
<p>The generated WireMock stub should resemble the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"request" : {
"urlPath" : "/api/v1/xxxx",
"method" : "POST",
"headers" : {
"Authorization" : {
"equalTo" : "secret2"
}
},
"queryParameters" : {
"foo" : {
"equalTo" : "bar2"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['baz'] == 5)]"
}, {
"matchesJsonPath" : "$[?(@.['foo'] == 'bar')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"authorization\":\"{{{request.headers.Authorization.[0]}}}\",\"path\":\"{{{request.path}}}\",\"responseBaz\":{{{jsonpath this '$.baz'}}} ,\"param\":\"{{{request.query.foo.[0]}}}\",\"pathIndex\":\"{{{request.path.[1]}}}\",\"responseBaz2\":\"Bla bla {{{jsonpath this '$.foo'}}} bla bla\",\"responseFoo\":\"{{{jsonpath this '$.foo'}}}\",\"authorization2\":\"{{{request.headers.Authorization.[1]}}}\",\"fullBody\":\"{{{escapejsonbody}}}\",\"url\":\"{{{request.url}}}\",\"paramIndex\":\"{{{request.query.foo.[1]}}}\"}",
"headers" : {
"Authorization" : "{{{request.headers.Authorization.[0]}}};foo"
},
"transformers" : [ "response-template" ]
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Sending a request such as the one presented in the <code>request</code> part of the contract results
in sending the following response body:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
"url" : "/api/v1/xxxx?foo=bar&amp;foo=bar2",
"path" : "/api/v1/xxxx",
"pathIndex" : "v1",
"param" : "bar",
"paramIndex" : "bar2",
"authorization" : "secret",
"authorization2" : "secret2",
"fullBody" : "{\"foo\":\"bar\",\"baz\":5}",
"responseFoo" : "bar",
"responseBaz" : 5,
"responseBaz2" : "Bla bla bar bla bla"
}</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This feature works only with WireMock having a version greater than or equal
to 2.5.1. The Spring Cloud Contract Verifier uses WireMock&#8217;s
<code>response-template</code> response transformer. It uses Handlebars to convert the Mustache <code>{{{ }}}</code> templates into
proper values. Additionally, it registers two helper functions:
</td>
</tr>
</table>
</div>
<div class="ulist">
<ul>
<li>
<p><code>escapejsonbody</code>: Escapes the request body in a format that can be embedded in a JSON.</p>
</li>
<li>
<p><code>jsonpath</code>: For a given parameter, find an object in the request body.</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_registering_your_own_wiremock_extension"><a class="link" href="#_registering_your_own_wiremock_extension">Registering Your Own WireMock Extension</a></h4>
<div class="paragraph">
<p>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
<code>org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions</code> interface.
Since we use the spring.factories extension approach, you can create an entry in
<code>META-INF/spring.factories</code> file similar to the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.verifier.dsl.wiremock.WireMockExtensions=\
org.springframework.cloud.contract.stubrunner.provider.wiremock.TestWireMockExtensions
org.springframework.cloud.contract.spec.ContractConverter=\
org.springframework.cloud.contract.stubrunner.TestCustomYamlContractConverter</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following is an example of a custom extension:</p>
</div>
<div class="listingblock">
<div class="title">TestWireMockExtensions.groovy</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.verifier.dsl.wiremock
import com.github.tomakehurst.wiremock.extension.Extension
/**
* Extension that registers the default transformer and the custom one
*/
class TestWireMockExtensions implements WireMockExtensions {
@Override
List&lt;Extension&gt; extensions() {
return [
new DefaultResponseTransformer(),
new CustomExtension()
]
}
}
class CustomExtension implements Extension {
@Override
String getName() {
return "foo-transformer"
}
}</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Remember to override the <code>applyGlobally()</code> method and set it to <code>false</code> if you
want the transformation to be applied only for a mapping that explicitly requires it.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="contract-matchers"><a class="link" href="#contract-matchers">Dynamic Properties in the Matchers Sections</a></h4>
<div class="paragraph">
<p>If you work with <a href="https://docs.pact.io/">Pact</a>, 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.</p>
</div>
<div class="paragraph">
<p>You can use the <code>bodyMatchers</code> section for two reasons:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Define the dynamic values that should end up in a stub.
You can set it in the <code>request</code> or <code>inputMessage</code> part of your contract.</p>
</li>
<li>
<p>Verify the result of your test.
This section is present in the <code>response</code> or <code>outputMessage</code> side of the
contract.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the
following matching possibilities:</p>
</div>
<div class="ulist">
<div class="title">Groovy DSL</div>
<ul>
<li>
<p>For the stubs(in tests on the Consumer&#8217;s side):</p>
<div class="ulist">
<ul>
<li>
<p><code>byEquality()</code>: The value taken from the consumer&#8217;s request via the provided JSON Path must be
equal to the value provided in the contract.</p>
</li>
<li>
<p><code>byRegex(&#8230;&#8203;)</code>: The value taken from the consumer&#8217;s request via the provided JSON Path must
match the regex. You can also pass the type of the expected matched value (e.g. <code>asString()</code>, <code>asLong()</code> etc.)</p>
</li>
<li>
<p><code>byDate()</code>: The value taken from the consumer&#8217;s request via the provided JSON Path must
match the regex for an ISO Date value.</p>
</li>
<li>
<p><code>byTimestamp()</code>: The value taken from the consumer&#8217;s request via the provided JSON Path must
match the regex for an ISO DateTime value.</p>
</li>
<li>
<p><code>byTime()</code>: The value taken from the consumer&#8217;s request via the provided JSON Path must
match the regex for an ISO Time value.</p>
</li>
</ul>
</div>
</li>
<li>
<p>For the verification(in generated tests on the Producer&#8217;s side):</p>
<div class="ulist">
<ul>
<li>
<p><code>byEquality()</code>: The value taken from the producer&#8217;s response via the provided JSON Path must be
equal to the provided value in the contract.</p>
</li>
<li>
<p><code>byRegex(&#8230;&#8203;)</code>: The value taken from the producer&#8217;s response via the provided JSON Path must
match the regex.</p>
</li>
<li>
<p><code>byDate()</code>: The value taken from the producer&#8217;s response via the provided JSON Path must match
the regex for an ISO Date value.</p>
</li>
<li>
<p><code>byTimestamp()</code>: The value taken from the producer&#8217;s response via the provided JSON Path must
match the regex for an ISO DateTime value.</p>
</li>
<li>
<p><code>byTime()</code>: The value taken from the producer&#8217;s response via the provided JSON Path must match
the regex for an ISO Time value.</p>
</li>
<li>
<p><code>byType()</code>: The value taken from the producer&#8217;s 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.
<code>byType</code> can take a closure, in which you can set <code>minOccurrence</code> and <code>maxOccurrence</code>. For the request side, you should use the closure to assert size of the collection.
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 <code>byCommand(&#8230;&#8203;)</code> testMatcher.</p>
</li>
<li>
<p><code>byCommand(&#8230;&#8203;)</code>: The value taken from the producer&#8217;s response via the provided JSON Path is
passed as an input to the custom method that you provide. For example,
<code>byCommand('foo($it)')</code> results in calling a <code>foo</code> 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:</p>
<div class="ulist">
<ul>
<li>
<p><code>String</code>: If you point to a <code>String</code> value.</p>
</li>
<li>
<p><code>JSONArray</code>: If you point to a <code>List</code>.</p>
</li>
<li>
<p><code>Map</code>: If you point to a <code>Map</code>.</p>
</li>
<li>
<p><code>Number</code>: If you point to <code>Integer</code>, <code>Double</code>, or other kind of number.</p>
</li>
<li>
<p><code>Boolean</code>: If you point to a <code>Boolean</code>.</p>
</li>
</ul>
</div>
</li>
<li>
<p><code>byNull()</code>: The value taken from the response via the provided JSON Path must be null</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<div class="title">YAML</div>
<p><em>Please read the Groovy section for detailed explanation of
what the types mean</em></p>
</div>
<div class="paragraph">
<p>For YAML the structure of a matcher looks like this</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">- path: $.foo
type: by_regex
value: bar
regexType: as_string</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or if you want to use one of the predefined regular expressions
<code>[only_alpha_unicode, number, any_boolean, ip_address, hostname,
email, url, uuid, iso_date, iso_date_time, iso_time, iso_8601_with_offset, non_empty, non_blank]</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">- path: $.foo
type: by_regex
predefined: only_alpha_unicode</code></pre>
</div>
</div>
<div class="paragraph">
<p>Below you can find the allowed list of `type`s.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>For <code>stubMatchers</code>:</p>
<div class="ulist">
<ul>
<li>
<p><code>by_equality</code></p>
</li>
<li>
<p><code>by_regex</code></p>
</li>
<li>
<p><code>by_date</code></p>
</li>
<li>
<p><code>by_timestamp</code></p>
</li>
<li>
<p><code>by_time</code></p>
</li>
<li>
<p><code>by_type</code></p>
<div class="ulist">
<ul>
<li>
<p>there are 2 additional fields accepted: <code>minOccurrence</code> and <code>maxOccurrence</code>.</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
<li>
<p>For <code>testMatchers</code>:</p>
<div class="ulist">
<ul>
<li>
<p><code>by_equality</code></p>
</li>
<li>
<p><code>by_regex</code></p>
</li>
<li>
<p><code>by_date</code></p>
</li>
<li>
<p><code>by_timestamp</code></p>
</li>
<li>
<p><code>by_time</code></p>
</li>
<li>
<p><code>by_type</code></p>
<div class="ulist">
<ul>
<li>
<p>there are 2 additional fields accepted: <code>minOccurrence</code> and <code>maxOccurrence</code>.</p>
</li>
</ul>
</div>
</li>
<li>
<p><code>by_command</code></p>
</li>
<li>
<p><code>by_null</code></p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can also define which type the regular expression corresponds to via the <code>regexType</code> field. Below you can find the allowed list of regular expression types:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>as_integer</p>
</li>
<li>
<p>as_double</p>
</li>
<li>
<p>as_float,</p>
</li>
<li>
<p>as_long</p>
</li>
<li>
<p>as_short</p>
</li>
<li>
<p>as_boolean</p>
</li>
<li>
<p>as_string</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Consider the following example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract contractDsl = Contract.make {
request {
method 'GET'
urlPath '/get'
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',
key : [
'complex.key': 'foo'
]
])
bodyMatchers {
jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
jsonPath('$.duck', byEquality())
jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
jsonPath('$.alpha', byEquality())
jsonPath('$.number', byRegex(number()).asInteger())
jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
jsonPath('$.date', byDate())
jsonPath('$.dateTime', byTimestamp())
jsonPath('$.time', byTime())
jsonPath("\$.['key'].['complex.key']", byEquality())
}
headers {
contentType(applicationJson())
}
}
response {
status OK()
body([
duck : 123,
alpha : 'abc',
number : 123,
positiveInteger : 1234567890,
negativeInteger : -1234567890,
positiveDecimalNumber: 123.4567890,
negativeDecimalNumber: -123.4567890,
aBoolean : true,
date : '2017-01-01',
dateTime : '2017-01-01T01:23:45',
time : "01:02:34",
valueWithoutAMatcher : 'foo',
valueWithTypeMatch : 'string',
valueWithMin : [
1, 2, 3
],
valueWithMax : [
1, 2, 3
],
valueWithMinMax : [
1, 2, 3
],
valueWithMinEmpty : [],
valueWithMaxEmpty : [],
key : [
'complex.key': 'foo'
],
nullValue : null
])
bodyMatchers {
// asserts the jsonpath value against manual regex
jsonPath('$.duck', byRegex("[0-9]{3}").asInteger())
// asserts the jsonpath value against the provided value
jsonPath('$.duck', byEquality())
// asserts the jsonpath value against some default regex
jsonPath('$.alpha', byRegex(onlyAlphaUnicode()).asString())
jsonPath('$.alpha', byEquality())
jsonPath('$.number', byRegex(number()).asInteger())
jsonPath('$.positiveInteger', byRegex(anInteger()).asInteger())
jsonPath('$.negativeInteger', byRegex(anInteger()).asInteger())
jsonPath('$.positiveDecimalNumber', byRegex(aDouble()).asDouble())
jsonPath('$.negativeDecimalNumber', byRegex(aDouble()).asDouble())
jsonPath('$.aBoolean', byRegex(anyBoolean()).asBooleanType())
// asserts vs inbuilt time related regex
jsonPath('$.date', byDate())
jsonPath('$.dateTime', byTimestamp())
jsonPath('$.time', byTime())
// asserts that the resulting type is the same as in response body
jsonPath('$.valueWithTypeMatch', byType())
jsonPath('$.valueWithMin', byType {
// results in verification of size of array (min 1)
minOccurrence(1)
})
jsonPath('$.valueWithMax', byType {
// results in verification of size of array (max 3)
maxOccurrence(3)
})
jsonPath('$.valueWithMinMax', byType {
// results in verification of size of array (min 1 &amp; max 3)
minOccurrence(1)
maxOccurrence(3)
})
jsonPath('$.valueWithMinEmpty', byType {
// results in verification of size of array (min 0)
minOccurrence(0)
})
jsonPath('$.valueWithMaxEmpty', byType {
// results in verification of size of array (max 0)
maxOccurrence(0)
})
// will execute a method `assertThatValueIsANumber`
jsonPath('$.duck', byCommand('assertThatValueIsANumber($it)'))
jsonPath("\$.['key'].['complex.key']", byEquality())
jsonPath('$.nullValue', byNull())
}
headers {
contentType(applicationJson())
header('Some-Header', $(c('someValue'), p(regex('[a-zA-Z]{9}'))))
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
method: GET
urlPath: /get/1
headers:
Content-Type: application/json
cookies:
foo: 2
bar: 3
queryParameters:
limit: 10
offset: 20
filter: 'email'
sort: name
search: 55
age: 99
name: John.Doe
email: 'bob@email.com'
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"
key:
"complex.key": 'foo'
nullValue: null
valueWithMin:
- 1
- 2
- 3
valueWithMax:
- 1
- 2
- 3
valueWithMinMax:
- 1
- 2
- 3
valueWithMinEmpty: []
valueWithMaxEmpty: []
matchers:
url:
regex: /get/[0-9]
# predefined:
# execute a method
#command: 'equals($it)'
queryParameters:
- key: limit
type: equal_to
value: 20
- key: offset
type: containing
value: 20
- key: sort
type: equal_to
value: name
- key: search
type: not_matching
value: '^[0-9]{2}$'
- key: age
type: not_matching
value: '^\\w*$'
- key: name
type: matching
value: 'John.*'
- key: hello
type: absent
cookies:
- key: foo
regex: '[0-9]'
- key: bar
command: 'equals($it)'
headers:
- key: Content-Type
regex: "application/json.*"
body:
- path: $.duck
type: by_regex
value: "[0-9]{3}"
- path: $.duck
type: by_equality
- path: $.alpha
type: by_regex
predefined: only_alpha_unicode
- path: $.alpha
type: by_equality
- path: $.number
type: by_regex
predefined: number
- path: $.aBoolean
type: by_regex
predefined: any_boolean
- path: $.date
type: by_date
- path: $.dateTime
type: by_timestamp
- path: $.time
type: by_time
- path: "$.['key'].['complex.key']"
type: by_equality
- path: $.nullvalue
type: by_null
- path: $.valueWithMin
type: by_type
minOccurrence: 1
- path: $.valueWithMax
type: by_type
maxOccurrence: 3
- path: $.valueWithMinMax
type: by_type
minOccurrence: 1
maxOccurrence: 3
response:
status: 200
cookies:
foo: 1
bar: 2
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"
valueWithMin:
- 1
- 2
- 3
valueWithMax:
- 1
- 2
- 3
valueWithMinMax:
- 1
- 2
- 3
valueWithMinEmpty: []
valueWithMaxEmpty: []
key:
'complex.key': 'foo'
nulValue: null
matchers:
headers:
- key: Content-Type
regex: "application/json.*"
cookies:
- key: foo
regex: '[0-9]'
- key: bar
command: 'equals($it)'
body:
- path: $.duck
type: by_regex
value: "[0-9]{3}"
- path: $.duck
type: by_equality
- path: $.alpha
type: by_regex
predefined: only_alpha_unicode
- path: $.alpha
type: by_equality
- path: $.number
type: by_regex
predefined: number
- path: $.aBoolean
type: by_regex
predefined: any_boolean
- path: $.date
type: by_date
- path: $.dateTime
type: by_timestamp
- path: $.time
type: by_time
- path: $.valueWithTypeMatch
type: by_type
- path: $.valueWithMin
type: by_type
minOccurrence: 1
- path: $.valueWithMax
type: by_type
maxOccurrence: 3
- path: $.valueWithMinMax
type: by_type
minOccurrence: 1
maxOccurrence: 3
- path: $.valueWithMinEmpty
type: by_type
minOccurrence: 0
- path: $.valueWithMaxEmpty
type: by_type
maxOccurrence: 0
- path: $.duck
type: by_command
value: assertThatValueIsANumber($it)
- path: $.nullValue
type: by_null
value: null
headers:
Content-Type: application/json</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the preceding example, you can see the dynamic portions of the contract in the
<code>matchers</code> sections. For the request part, you can see that, for all fields but
<code>valueWithoutAMatcher</code>, the values of the regular expressions that the stub should
contain are explicitly set. For the <code>valueWithoutAMatcher</code>, the verification takes place
in the same way as without the use of matchers. In that case, the test performs an
equality check.</p>
</div>
<div class="paragraph">
<p>For the response side in the <code>bodyMatchers</code> section, we define the dynamic parts in a
similar manner. The only difference is that the <code>byType</code> 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):</p>
</div>
<div class="ulist">
<ul>
<li>
<p>For <code>$.valueWithTypeMatch</code>, the engine checks whether the type is the same.</p>
</li>
<li>
<p>For <code>$.valueWithMin</code>, the engine check the type and asserts whether the size is greater
than or equal to the minimum occurrence.</p>
</li>
<li>
<p>For <code>$.valueWithMax</code>, the engine checks the type and asserts whether the size is
smaller than or equal to the maximum occurrence.</p>
</li>
<li>
<p>For <code>$.valueWithMinMax</code>, the engine checks the type and asserts whether the size is
between the min and maximum occurrence.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The resulting test would resemble the following example (note that an <code>and</code> section
separates the autogenerated assertions and the assertion from matchers):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">// 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\",\"key\":{\"complex.key\":\"foo\"}}");
// when:
ResponseOptions response = given().spec(request)
.get("/get");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['valueWithoutAMatcher']").isEqualTo("foo");
// and:
assertThat(parsedJson.read("$.duck", String.class)).matches("[0-9]{3}");
assertThat(parsedJson.read("$.duck", Integer.class)).isEqualTo(123);
assertThat(parsedJson.read("$.alpha", String.class)).matches("[\\p{L}]*");
assertThat(parsedJson.read("$.alpha", String.class)).isEqualTo("abc");
assertThat(parsedJson.read("$.number", String.class)).matches("-?(\\d*\\.\\d+|\\d+)");
assertThat(parsedJson.read("$.aBoolean", String.class)).matches("(true|false)");
assertThat(parsedJson.read("$.date", String.class)).matches("(\\d\\d\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])");
assertThat(parsedJson.read("$.dateTime", String.class)).matches("([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
assertThat(parsedJson.read("$.time", String.class)).matches("(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])");
assertThat((Object) parsedJson.read("$.valueWithTypeMatch")).isInstanceOf(java.lang.String.class);
assertThat((Object) parsedJson.read("$.valueWithMin")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMin", java.util.Collection.class)).as("$.valueWithMin").hasSizeGreaterThanOrEqualTo(1);
assertThat((Object) parsedJson.read("$.valueWithMax")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMax", java.util.Collection.class)).as("$.valueWithMax").hasSizeLessThanOrEqualTo(3);
assertThat((Object) parsedJson.read("$.valueWithMinMax")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinMax", java.util.Collection.class)).as("$.valueWithMinMax").hasSizeBetween(1, 3);
assertThat((Object) parsedJson.read("$.valueWithMinEmpty")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMinEmpty", java.util.Collection.class)).as("$.valueWithMinEmpty").hasSizeGreaterThanOrEqualTo(0);
assertThat((Object) parsedJson.read("$.valueWithMaxEmpty")).isInstanceOf(java.util.List.class);
assertThat((java.lang.Iterable) parsedJson.read("$.valueWithMaxEmpty", java.util.Collection.class)).as("$.valueWithMaxEmpty").hasSizeLessThanOrEqualTo(0);
assertThatValueIsANumber(parsedJson.read("$.duck"));
assertThat(parsedJson.read("$.['key'].['complex.key']", String.class)).isEqualTo("foo");</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Notice that, for the <code>byCommand</code> method, the example calls the
<code>assertThatValueIsANumber</code>. This method must be defined in the test base class or be
statically imported to your tests. Notice that the <code>byCommand</code> call was converted to
<code>assertThatValueIsANumber(parsedJson.read("$.duck"));</code>. That means that the engine took
the method name and passed the proper JSON path as a parameter to it.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The resulting WireMock stub is in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json"> '''
{
"request" : {
"urlPath" : "/get",
"method" : "POST",
"headers" : {
"Content-Type" : {
"matches" : "application/json.*"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$.['list'].['some'].['nested'][?(@.['anothervalue'] == 4)]"
}, {
"matchesJsonPath" : "$[?(@.['valueWithoutAMatcher'] == 'foo')]"
}, {
"matchesJsonPath" : "$[?(@.['valueWithTypeMatch'] == 'string')]"
}, {
"matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['json'] == 'with value')]"
}, {
"matchesJsonPath" : "$.['list'].['someother'].['nested'][?(@.['anothervalue'] == 4)]"
}, {
"matchesJsonPath" : "$[?(@.duck =~ /([0-9]{3})/)]"
}, {
"matchesJsonPath" : "$[?(@.duck == 123)]"
}, {
"matchesJsonPath" : "$[?(@.alpha =~ /([\\\\p{L}]*)/)]"
}, {
"matchesJsonPath" : "$[?(@.alpha == 'abc')]"
}, {
"matchesJsonPath" : "$[?(@.number =~ /(-?(\\\\d*\\\\.\\\\d+|\\\\d+))/)]"
}, {
"matchesJsonPath" : "$[?(@.aBoolean =~ /((true|false))/)]"
}, {
"matchesJsonPath" : "$[?(@.date =~ /((\\\\d\\\\d\\\\d\\\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]))/)]"
}, {
"matchesJsonPath" : "$[?(@.dateTime =~ /(([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
}, {
"matchesJsonPath" : "$[?(@.time =~ /((2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]))/)]"
}, {
"matchesJsonPath" : "$.list.some.nested[?(@.json =~ /(.*)/)]"
}, {
"matchesJsonPath" : "$[?(@.valueWithMin.size() &gt;= 1)]"
}, {
"matchesJsonPath" : "$[?(@.valueWithMax.size() &lt;= 3)]"
}, {
"matchesJsonPath" : "$[?(@.valueWithMinMax.size() &gt;= 1 &amp;&amp; @.valueWithMinMax.size() &lt;= 3)]"
}, {
"matchesJsonPath" : "$[?(@.valueWithOccurrence.size() &gt;= 4 &amp;&amp; @.valueWithOccurrence.size() &lt;= 4)]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\\"date\\":\\"2017-01-01\\",\\"dateTime\\":\\"2017-01-01T01:23:45\\",\\"aBoolean\\":true,\\"valueWithMax\\":[1,2,3],\\"valueWithOccurrence\\":[1,2,3,4],\\"number\\":123,\\"duck\\":123,\\"alpha\\":\\"abc\\",\\"valueWithMin\\":[1,2,3],\\"time\\":\\"01:02:34\\",\\"valueWithTypeMatch\\":\\"string\\",\\"valueWithMinMax\\":[1,2,3],\\"valueWithoutAMatcher\\":\\"foo\\"}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template" ]
}
}
'''</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you use a <code>matcher</code>, then the part of the request and response that the
<code>matcher</code> addresses with the JSON Path gets removed from the assertion. In the case of
verifying a collection, you must create matchers for <strong>all</strong> the elements of the
collection.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Consider the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract.make {
request {
method 'GET'
url("/foo")
}
response {
status OK()
body(events: [[
operation : 'EXPORT',
eventId : '16f1ed75-0bcc-4f0d-a04d-3121798faf99',
status : 'OK'
], [
operation : 'INPUT_PROCESSING',
eventId : '3bb4ac82-6652-462f-b6d1-75e424a0024a',
status : 'OK'
]
]
)
bodyMatchers {
jsonPath('$.events[0].operation', byRegex('.+'))
jsonPath('$.events[0].eventId', byRegex('^([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})$'))
jsonPath('$.events[0].status', byRegex('.+'))
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The preceding code leads to creating the following test (the code block shows only the assertion section):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">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")
assertThatJson(parsedJson).array("['events']").contains("['operation']").isEqualTo("INPUT_PROCESSING")
assertThatJson(parsedJson).array("['events']").contains("['eventId']").isEqualTo("3bb4ac82-6652-462f-b6d1-75e424a0024a")
assertThatJson(parsedJson).array("['events']").contains("['status']").isEqualTo("OK")
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(".+")</code></pre>
</div>
</div>
<div class="paragraph">
<p>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 <code>$.events</code>
collection and assert it with the <code>byCommand(&#8230;&#8203;)</code> method.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_jax_rs_support"><a class="link" href="#_jax_rs_support">JAX-RS Support</a></h3>
<div class="paragraph">
<p>The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs
to define <code>protected WebTarget webTarget</code> 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 <code>application/octet-stream</code> gets used.</p>
</div>
<div class="paragraph">
<p>In order to use JAX-RS mode, use the following settings:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testMode == 'JAXRSCLIENT'</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows a generated test API:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> """\
package com.example;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static javax.ws.rs.client.Entity.*;
@SuppressWarnings("rawtypes")
public class FooTest {
\tWebTarget webTarget;
\t@Test
\tpublic void validate_() throws Exception {
\t\t// when:
\t\t\tResponse response = webTarget
\t\t\t\t\t\t\t.path("/users")
\t\t\t\t\t\t\t.queryParam("limit", "10")
\t\t\t\t\t\t\t.queryParam("offset", "20")
\t\t\t\t\t\t\t.queryParam("filter", "email")
\t\t\t\t\t\t\t.queryParam("sort", "name")
\t\t\t\t\t\t\t.queryParam("search", "55")
\t\t\t\t\t\t\t.queryParam("age", "99")
\t\t\t\t\t\t\t.queryParam("name", "Denis.Stepanov")
\t\t\t\t\t\t\t.queryParam("email", "bob@email.com")
\t\t\t\t\t\t\t.request()
\t\t\t\t\t\t\t.build("GET")
\t\t\t\t\t\t\t.invoke();
\t\t\tString responseAsString = response.readEntity(String.class);
\t\t// then:
\t\t\tassertThat(response.getStatus()).isEqualTo(200);
\t\t// and:
\t\t\tDocumentContext parsedJson = JsonPath.parse(responseAsString);
\t\t\tassertThatJson(parsedJson).field("['property1']").isEqualTo("a");
\t}
}
"""</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_async_support"><a class="link" href="#_async_support">Async Support</a></h3>
<div class="paragraph">
<p>If you&#8217;re using asynchronous communication on the server side (your controllers are
returning <code>Callable</code>, <code>DeferredResult</code>, and so on), then, inside your contract, you must
provide an <code>async()</code> method in the <code>response</code> section. The following code shows an example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method GET()
url '/get'
}
response {
status OK()
body 'Passed'
async()
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">response:
async: true</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can also use the <code>fixedDelayMilliseconds</code> method / property to add delay to your stubs.</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method GET()
url '/get'
}
response {
status 200
body 'Passed'
fixedDelayMilliseconds 1000
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">response:
fixedDelayMilliseconds: 1000</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_working_with_context_paths"><a class="link" href="#_working_with_context_paths">Working with Context Paths</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract supports context paths.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
The only change needed to fully support context paths is the switch on the
<strong>PRODUCER</strong> side. Also, the autogenerated tests must use <strong>EXPLICIT</strong> mode. The consumer
side remains untouched. In order for the generated test to pass, you must use <strong>EXPLICIT</strong>
mode.
</td>
</tr>
</table>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;testMode&gt;EXPLICIT&lt;/testMode&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
testMode = 'EXPLICIT'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>That way, you generate a test that <strong>DOES NOT</strong> use MockMvc. It means that you generate
real requests and you need to setup your generated test&#8217;s base class to work on a real
socket.</p>
</div>
<div class="paragraph">
<p>Consider the following contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'GET'
url '/my-context-path/url'
}
response {
status OK()
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to set up a base class and Rest Assured:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">import io.restassured.RestAssured;
import org.junit.Before;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = ContextPathTestingBaseClass.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ContextPathTestingBaseClass {
@LocalServerPort int port;
@Before
public void setup() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = this.port;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you do it this way:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>All of your requests in the autogenerated tests are sent to the real endpoint with your
context path included (for example, <code>/my-context-path/url</code>).</p>
</li>
<li>
<p>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 <code>/my-context-path/url</code>).</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_working_with_webflux"><a class="link" href="#_working_with_webflux">Working with WebFlux</a></h3>
<div class="paragraph">
<p>Spring Cloud Contract offers two ways of working with WebFlux.</p>
</div>
<div class="sect3">
<h4 id="_webflux_with_webtestclient"><a class="link" href="#_webflux_with_webtestclient">WebFlux with WebTestClient</a></h4>
<div class="paragraph">
<p>One of them is via the <code>WebTestClient</code> mode.</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;testMode&gt;WEBTESTCLIENT&lt;/testMode&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
testMode = 'WEBTESTCLIENT'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to set up a <code>WebTestClient</code> base class and <code>RestAssured</code>
for WebFlux:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">import io.restassured.module.webtestclient.RestAssuredWebTestClient;
import org.junit.Before;
public abstract class BeerRestBase {
@Before
public void setup() {
RestAssuredWebTestClient.standaloneSetup(
new ProducerController(personToCheck -&gt; personToCheck.age &gt;= 20));
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_webflux_with_explicit_mode"><a class="link" href="#_webflux_with_explicit_mode">WebFlux with Explicit mode</a></h4>
<div class="paragraph">
<p>Another way is with the <code>EXPLICIT</code> mode in your generated tests
to work with WebFlux.</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;testMode&gt;EXPLICIT&lt;/testMode&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">contracts {
testMode = 'EXPLICIT'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following example shows how to set up a base class and Rest Assured for Web Flux:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">@RunWith(SpringRunner.class)
@SpringBootTest(classes = BeerRestBase.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "server.port=0")
public abstract class BeerRestBase {
// your tests go here
// in this config class you define all controllers and mocked services
@Configuration
@EnableAutoConfiguration
static class Config {
@Bean
PersonCheckingService personCheckingService() {
return personToCheck -&gt; personToCheck.age &gt;= 20;
}
@Bean
ProducerController producerController() {
return new ProducerController(personCheckingService());
}
}
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_xml_support_for_rest"><a class="link" href="#_xml_support_for_rest">XML Support for REST</a></h3>
<div class="paragraph">
<p>For REST contracts, we also support XML request and response body.
The XML body has to be passed within the <code>body</code> element
as a <code>String</code> or <code>GString</code>. Also body matchers can be provided for
both request and response. In place of the <code>jsonPath(&#8230;&#8203;)</code> method, the <code>org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath</code>
method should be used, with the desired <code>xPath</code> provided as the first argument
and the appropriate <code>MatchingType</code> as second. All the body matchers apart from <code>byType()</code> are supported.</p>
</div>
<div class="paragraph">
<p>Here is an example of a Groovy DSL contract with XML response body:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> Contract.make {
request {
method GET()
urlPath '/get'
headers {
contentType(applicationXml())
}
}
response {
status(OK())
headers {
contentType(applicationXml())
}
body """
&lt;test&gt;
&lt;duck type='xtype'&gt;123&lt;/duck&gt;
&lt;alpha&gt;abc&lt;/alpha&gt;
&lt;list&gt;
&lt;elem&gt;abc&lt;/elem&gt;
&lt;elem&gt;def&lt;/elem&gt;
&lt;elem&gt;ghi&lt;/elem&gt;
&lt;/list&gt;
&lt;number&gt;123&lt;/number&gt;
&lt;aBoolean&gt;true&lt;/aBoolean&gt;
&lt;date&gt;2017-01-01&lt;/date&gt;
&lt;dateTime&gt;2017-01-01T01:23:45&lt;/dateTime&gt;
&lt;time&gt;01:02:34&lt;/time&gt;
&lt;valueWithoutAMatcher&gt;foo&lt;/valueWithoutAMatcher&gt;
&lt;key&gt;&lt;complex&gt;foo&lt;/complex&gt;&lt;/key&gt;
&lt;/test&gt;"""
bodyMatchers {
xPath('/test/duck/text()', byRegex("[0-9]{3}"))
xPath('/test/duck/text()', byCommand('equals($it)'))
xPath('/test/duck/xxx', byNull())
xPath('/test/duck/text()', byEquality())
xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode()))
xPath('/test/alpha/text()', byEquality())
xPath('/test/number/text()', byRegex(number()))
xPath('/test/date/text()', byDate())
xPath('/test/dateTime/text()', byTimestamp())
xPath('/test/time/text()', byTime())
xPath('/test/*/complex/text()', byEquality())
xPath('/test/duck/@type', byEquality())
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>And below is an example of a YAML contract with XML request and response bodies:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here is an example of an automatically generated test for XML response body:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void validate_xmlMatches() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/xml");
// when:
ResponseOptions response = given().spec(request).get("/get");
// then:
assertThat(response.statusCode()).isEqualTo(200);
// and:
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document parsedXml = documentBuilder.parse(new InputSource(
new StringReader(response.getBody().asString())));
// and:
assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc");
assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def");
assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}");
assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull();
assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*");
assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo");
assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype");
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_messaging_top_level_elements"><a class="link" href="#_messaging_top_level_elements">Messaging Top-Level Elements</a></h3>
<div class="paragraph">
<p>The DSL for messaging looks a little bit different than the one that focuses on HTTP. The
following sections explain the differences:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#contract-dsl-output-triggered-method">Output Triggered by a Method</a></p>
</li>
<li>
<p><a href="#contract-dsl-output-triggered-message">Output Triggered by a Message</a></p>
</li>
<li>
<p><a href="#contract-dsl-consumer-producer">Consumer/Producer</a></p>
</li>
<li>
<p><a href="#contract-dsl-common">Common</a></p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="contract-dsl-output-triggered-method"><a class="link" href="#contract-dsl-output-triggered-method">Output Triggered by a Method</a></h4>
<div class="paragraph">
<p>The output message can be triggered by calling a method (such as a <code>Scheduler</code> when a was
started and a message was sent), as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">def dsl = Contract.make {
// Human readable description
description 'Some description'
// Label by means of which the output message can be triggered
label 'some_label'
// input to the contract
input {
// the contract will be triggered by a method
triggeredBy('bookReturnedTriggered()')
}
// output message of the contract
outputMessage {
// destination to which the output message will be sent
sentTo('output')
// the body of the output message
body('''{ "bookName" : "foo" }''')
// the headers of the output message
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml"># Human readable description
description: Some description
# Label by means of which the output message can be triggered
label: some_label
input:
# the contract will be triggered by a method
triggeredBy: bookReturnedTriggered()
# output message of the contract
outputMessage:
# destination to which the output message will be sent
sentTo: output
# the body of the output message
body:
bookName: foo
# the headers of the output message
headers:
BOOK-NAME: foo</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the previous example case, the output message is sent to <code>output</code> if a method called
<code>bookReturnedTriggered</code> is executed. On the message <strong>publisher&#8217;s</strong> side, we generate a
test that calls that method to trigger the message. On the <strong>consumer</strong> side, you can use
the <code>some_label</code> to trigger the message.</p>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-output-triggered-message"><a class="link" href="#contract-dsl-output-triggered-message">Output Triggered by a Message</a></h4>
<div class="paragraph">
<p>The output message can be triggered by receiving a message, as shown in the following
example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">def dsl = Contract.make {
description 'Some Description'
label 'some_label'
// input is a message
input {
// the message was received from this destination
messageFrom('input')
// has the following body
messageBody([
bookName: 'foo'
])
// and the following headers
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml"># Human readable description
description: Some description
# Label by means of which the output message can be triggered
label: some_label
# input is a message
input:
messageFrom: input
# has the following body
messageBody:
bookName: 'foo'
# and the following headers
messageHeaders:
sample: 'header'
# output message of the contract
outputMessage:
# destination to which the output message will be sent
sentTo: output
# the body of the output message
body:
bookName: foo
# the headers of the output message
headers:
BOOK-NAME: foo</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the preceding example, the output message is sent to <code>output</code> if a proper message is
received on the <code>input</code> destination. On the message <strong>publisher&#8217;s</strong> side, the engine
generates a test that sends the input message to the defined destination. On the
<strong>consumer</strong> side, you can either send a message to the input destination or use a label
(<code>some_label</code> in the example) to trigger the message.</p>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-consumer-producer"><a class="link" href="#contract-dsl-consumer-producer">Consumer/Producer</a></h4>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>In HTTP, you have a notion of <code>client</code>/<code>stub and `server</code>/<code>test</code> notation. You can also
use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also
provides the <code>consumer</code> and <code>producer</code> methods, as presented in the following example
(note that you can use either <code>$</code> or <code>value</code> methods to provide <code>consumer</code> and <code>producer</code>
parts):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"> Contract.make {
name "foo"
label 'some_label'
input {
messageFrom value(consumer('jms:output'), producer('jms:input'))
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo $(consumer('jms:input'), producer('jms:output'))
body([
bookName: 'foo'
])
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="contract-dsl-common"><a class="link" href="#contract-dsl-common">Common</a></h4>
<div class="paragraph">
<p>In the <code>input</code> or <code>outputMessage</code> section you can call <code>assertThat</code> with the name
of a <code>method</code> (e.g. <code>assertThatMessageIsOnTheQueue()</code>) that you have defined in the
base class or in a static import. Spring Cloud Contract will execute that method
in the generated test.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_multiple_contracts_in_one_file"><a class="link" href="#_multiple_contracts_in_one_file">Multiple Contracts in One File</a></h3>
<div class="paragraph">
<p>You can define multiple contracts in one file. Such a contract might resemble the
following example:</p>
</div>
<div class="listingblock">
<div class="title">Groovy DSL</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">import org.springframework.cloud.contract.spec.Contract
[
Contract.make {
name("should post a user")
request {
method 'POST'
url('/users/1')
}
response {
status OK()
}
},
Contract.make {
request {
method 'POST'
url('/users/2')
}
response {
status OK()
}
}
]</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">YAML</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">---
name: should post a user
request:
method: POST
url: /users/1
response:
status: 200
---
request:
method: POST
url: /users/2
response:
status: 200
---
request:
method: POST
url: /users/3
response:
status: 200</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the preceding example, one contract has the <code>name</code> field and the other does not. This
leads to generation of two tests that look more or less like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package org.springframework.cloud.contract.verifier.tests.com.hello;
import com.example.TestBase;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import com.jayway.restassured.response.ResponseOptions;
import org.junit.Test;
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
public class V1Test extends TestBase {
@Test
public void validate_should_post_a_user() throws Exception {
// given:
MockMvcRequestSpecification request = given();
// when:
ResponseOptions response = given().spec(request)
.post("/users/1");
// then:
assertThat(response.statusCode()).isEqualTo(200);
}
@Test
public void validate_withList_1() throws Exception {
// given:
MockMvcRequestSpecification request = given();
// when:
ResponseOptions response = given().spec(request)
.post("/users/2");
// then:
assertThat(response.statusCode()).isEqualTo(200);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice that, for the contract that has the <code>name</code> field, the generated test method is named
<code>validate_should_post_a_user</code>. For the one that does not have the name, it is called
<code>validate_withList_1</code>. It corresponds to the name of the file <code>WithList.groovy</code> and the
index of the contract in the list.</p>
</div>
<div class="paragraph">
<p>The generated stubs is shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>should post a user.json
1_WithList.json</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see, the first file got the <code>name</code> parameter from the contract. The second
got the name of the contract file (<code>WithList.groovy</code>) prefixed with the index (in this
case, the contract had an index of <code>1</code> in the list of contracts in the file).</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
As you can see, it is much better if you name your contracts because doing so makes
your tests far more meaningful.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_generating_spring_rest_docs_snippets_from_the_contracts"><a class="link" href="#_generating_spring_rest_docs_snippets_from_the_contracts">Generating Spring REST Docs snippets from the contracts</a></h3>
<div class="paragraph">
<p>When you want to include the requests and responses of your API using Spring REST Docs,
you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc.
Simply include the following dependencies if you haven&#8217;t already.</p>
</div>
<div class="listingblock">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-starter-contract-verifier&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.restdocs&lt;/groupId&gt;
&lt;artifactId&gt;spring-restdocs-mockmvc&lt;/artifactId&gt;
&lt;optional&gt;true&lt;/optional&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next you need to make some changes to your base class like the following example.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example.fraud;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public abstract class FraudBaseWithWebAppSetup {
private static final String OUTPUT = "target/generated-snippets";
@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
@Rule
public TestName testName = new TestName();
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
RestAssuredMockMvc.mockMvc(MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document(
getClass().getSimpleName() + "_" + testName.getMethodName()))
.build());
}
protected void assertThatRejectionReasonIsNull(Object rejectionReason) {
assert rejectionReason == null;
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In case you are using the standalone setup, you can set up RestAssuredMockMvc like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example.fraud;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
public abstract class FraudBaseWithStandaloneSetup {
private static final String OUTPUT = "target/generated-snippets";
@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(OUTPUT);
@Rule
public TestName testName = new TestName();
@Before
public void setup() {
RestAssuredMockMvc.standaloneSetup(MockMvcBuilders
.standaloneSetup(new FraudDetectionController())
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(document(
getClass().getSimpleName() + "_" + testName.getMethodName())));
}
}</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You don&#8217;t need to specify the output directory for the generated snippets since version 1.2.0.RELEASE of Spring REST Docs.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_customization"><a class="link" href="#_customization">Customization</a></h2>
<div class="sectionbody">
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
This section is valid only for Groovy DSL
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in
the remainder of this section.</p>
</div>
<div class="sect2">
<h3 id="_extending_the_dsl"><a class="link" href="#_extending_the_dsl">Extending the DSL</a></h3>
<div class="paragraph">
<p>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:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Creating a JAR with reusable classes.</p>
</li>
<li>
<p>Referencing of these classes in the DSLs.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can find the full example
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples">here</a>.</p>
</div>
<div class="sect3">
<h4 id="_common_jar"><a class="link" href="#_common_jar">Common JAR</a></h4>
<div class="paragraph">
<p>The following examples show three classes that can be reused in the DSLs.</p>
</div>
<div class="paragraph">
<p><strong>PatternUtils</strong> contains functions used by both the <strong>consumer</strong> and the <strong>producer</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example;
import java.util.regex.Pattern;
/**
* If you want to use {@link Pattern} directly in your tests
* then you can create a class resembling this one. It can
* contain all the {@link Pattern} you want to use in the DSL.
*
* &lt;pre&gt;
* {@code
* request {
* body(
* [ age: $(c(PatternUtils.oldEnough()))]
* )
* }
* &lt;/pre&gt;
*
* Notice that we're using both {@code $()} for dynamic values
* and {@code c()} for the consumer side.
*
* @author Marcin Grzejszczak
*/
//tag::impl[]
public class PatternUtils {
public static String tooYoung() {
//remove::start[]
return "[0-1][0-9]";
//remove::end[return]
}
public static Pattern oldEnough() {
//remove::start[]
return Pattern.compile("[2-9][0-9]");
//remove::end[return]
}
/**
* Makes little sense but it's just an example ;)
*/
public static Pattern ok() {
//remove::start[]
return Pattern.compile("OK");
//remove::end[return]
}
}
//end::impl[]</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>ConsumerUtils</strong> contains functions used by the <strong>consumer</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example;
import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
/**
* DSL Properties passed to the DSL from the consumer's perspective.
* That means that on the input side {@code Request} for HTTP
* or {@code Input} for messaging you can have a regular expression.
* On the {@code Response} for HTTP or {@code Output} for messaging
* you have to have a concrete value.
*
* @author Marcin Grzejszczak
*/
//tag::impl[]
public class ConsumerUtils {
/**
* Consumer side property. By using the {@link ClientDslProperty}
* you can omit most of boilerplate code from the perspective
* of dynamic values. Example
*
* &lt;pre&gt;
* {@code
* request {
* body(
* [ age: $(ConsumerUtils.oldEnough())]
* )
* }
* &lt;/pre&gt;
*
* That way it's in the implementation that we decide what value we will pass to the consumer
* and which one to the producer.
*
* @author Marcin Grzejszczak
*/
public static ClientDslProperty oldEnough() {
//remove::start[]
// this example is not the best one and
// theoretically you could just pass the regex instead of `ServerDslProperty` but
// it's just to show some new tricks :)
return new ClientDslProperty(PatternUtils.oldEnough(), 40);
//remove::end[return]
}
}
//end::impl[]</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>ProducerUtils</strong> contains functions used by the <strong>producer</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example;
import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
/**
* DSL Properties passed to the DSL from the producer's perspective.
* That means that on the input side {@code Request} for HTTP
* or {@code Input} for messaging you have to have a concrete value.
* On the {@code Response} for HTTP or {@code Output} for messaging
* you can have a regular expression.
*
* @author Marcin Grzejszczak
*/
//tag::impl[]
public class ProducerUtils {
/**
* Producer side property. By using the {@link ProducerUtils}
* you can omit most of boilerplate code from the perspective
* of dynamic values. Example
*
* &lt;pre&gt;
* {@code
* response {
* body(
* [ status: $(ProducerUtils.ok())]
* )
* }
* &lt;/pre&gt;
*
* That way it's in the implementation that we decide what value we will pass to the consumer
* and which one to the producer.
*/
public static ServerDslProperty ok() {
// this example is not the best one and
// theoretically you could just pass the regex instead of `ServerDslProperty` but
// it's just to show some new tricks :)
return new ServerDslProperty( PatternUtils.ok(), "OK");
}
}
//end::impl[]</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_adding_the_dependency_to_the_project"><a class="link" href="#_adding_the_dependency_to_the_project">Adding the Dependency to the Project</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
</div>
<div class="sect3">
<h4 id="_test_the_dependency_in_the_projects_dependencies"><a class="link" href="#_test_the_dependency_in_the_projects_dependencies">Test the Dependency in the Project&#8217;s Dependencies</a></h4>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;com.example&lt;/groupId&gt;
&lt;artifactId&gt;beer-common&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile("com.example:beer-common:0.0.1.BUILD-SNAPSHOT")</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_test_a_dependency_in_the_plugins_dependencies"><a class="link" href="#_test_a_dependency_in_the_plugins_dependencies">Test a Dependency in the Plugin&#8217;s Dependencies</a></h4>
<div class="paragraph">
<p>Now, you must add the dependency for the plugin to reuse at runtime, as shown in the
following example:</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example&lt;/packageWithBaseClasses&gt;
&lt;baseClassMappings&gt;
&lt;baseClassMapping&gt;
&lt;contractPackageRegex&gt;.*intoxication.*&lt;/contractPackageRegex&gt;
&lt;baseClassFQN&gt;com.example.intoxication.BeerIntoxicationBase&lt;/baseClassFQN&gt;
&lt;/baseClassMapping&gt;
&lt;/baseClassMappings&gt;
&lt;/configuration&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.example&lt;/groupId&gt;
&lt;artifactId&gt;beer-common&lt;/artifactId&gt;
&lt;version&gt;${project.version}&lt;/version&gt;
&lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">classpath "com.example:beer-common:0.0.1.BUILD-SNAPSHOT"</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_referencing_classes_in_dsls"><a class="link" href="#_referencing_classes_in_dsls">Referencing classes in DSLs</a></h4>
<div class="paragraph">
<p>You can now reference your classes in your DSL, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package contracts.beer.rest
import com.example.ConsumerUtils
import com.example.ProducerUtils
import org.springframework.cloud.contract.spec.Contract
Contract.make {
description("""
Represents a successful scenario of getting a beer
```
given:
client is old enough
when:
he applies for a beer
then:
we'll grant him the beer
```
""")
request {
method 'POST'
url '/check'
body(
age: $(ConsumerUtils.oldEnough())
)
headers {
contentType(applicationJson())
}
}
response {
status 200
body("""
{
"status": "${value(ProducerUtils.ok())}"
}
""")
headers {
contentType(applicationJson())
}
}
}</code></pre>
</div>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
You can set the Spring Cloud Contract plugin up by setting <code>convertToYaml</code> to <code>true</code>. That way you will NOT have to add the dependency with the extended functionality to the consumer side, since the consumer side will be using YAML contracts instead of Groovy ones.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_using_the_pluggable_architecture"><a class="link" href="#_using_the_pluggable_architecture">Using the Pluggable Architecture</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>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).</p>
</div>
<div class="sect2">
<h3 id="_custom_contract_converter"><a class="link" href="#_custom_contract_converter">Custom Contract Converter</a></h3>
<div class="paragraph">
<p>The <code>ContractConverter</code> interface lets you register your own implementation of a contract
structure converter. The following code listing shows the <code>ContractConverter</code> interface:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package org.springframework.cloud.contract.spec;
import java.io.File;
import java.util.Collection;
/**
* Converter to be used to convert FROM {@link File} TO {@link Contract} and from
* {@link Contract} to {@code T}.
*
* @param &lt;T&gt; - type to which we want to convert the contract
* @author Marcin Grzejszczak
* @since 1.1.0
*/
public interface ContractConverter&lt;T&gt; extends ContractStorer&lt;T&gt; {
/**
* Should this file be accepted by the converter. Can use the file extension to check
* if the conversion is possible.
* @param file - file to be considered for conversion
* @return - {@code true} if the given implementation can convert the file
*/
boolean isAccepted(File file);
/**
* Converts the given {@link File} to its {@link Contract} representation.
* @param file - file to convert
* @return - {@link Contract} representation of the file
*/
Collection&lt;Contract&gt; convertFrom(File file);
/**
* Converts the given {@link Contract} to a {@link T} representation.
* @param contract - the parsed contract
* @return - {@link T} the type to which we do the conversion
*/
T convertTo(Collection&lt;Contract&gt; contract);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Your implementation must define the condition on which it should start the
conversion. Also, you must define how to perform that conversion in both directions.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
Once you create your implementation, you must create a
<code>/META-INF/spring.factories</code> file in which you provide the fully qualified name of your
implementation.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>The following example shows a typical <code>spring.factories</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>org.springframework.cloud.contract.spec.ContractConverter=\
org.springframework.cloud.contract.verifier.converter.YamlContractConverter</code></pre>
</div>
</div>
<div class="sect3">
<h4 id="pact-converter"><a class="link" href="#pact-converter">Pact Converter</a></h4>
<div class="paragraph">
<p>Spring Cloud Contract includes support for <a href="https://docs.pact.io/">Pact</a> representation of
contracts up until v4. Instead of using the Groovy DSL, you can use Pact files. In this section, we
present how to add Pact support for your project. Note however that not all functionality is supported.
Starting with v3 you can combine multiple matcher for the same element;
you can use matchers for the body, headers, request and path; and you can use value generators.
Spring Cloud Contract currently only supports multiple matchers that are combined using the AND rule logic.
Next to that the request and path matchers are skipped during the conversion.
When using a date, time or datetime value generator with a given format,
the given format will be skipped and the ISO format will be used.</p>
</div>
<div class="paragraph">
<p>In order to properly support the Spring Cloud Contract way of doing messaging
with Pact you&#8217;ll have to provide some additional meta data entries. Below you can find a list of such entries:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>to define the destination to which a message gets sent, you have to
set a <code>metaData</code> entry in the Pact file, with key <code>sentTo</code> equal to the destination to which a message is to be sent. E.g. <code>"metaData": { "sentTo": "activemq:output" }</code></p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_pact_contract"><a class="link" href="#_pact_contract">Pact Contract</a></h4>
<div class="paragraph">
<p>Consider following example of a Pact contract, which is a file under the
<code>src/test/resources/contracts</code> folder.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-javascript hljs" data-lang="javascript">{
"provider": {
"name": "Provider"
},
"consumer": {
"name": "Consumer"
},
"interactions": [
{
"description": "",
"request": {
"method": "PUT",
"path": "/fraudcheck",
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": {
"clientId": "1234567890",
"loanAmount": 99999
},
"generators": {
"body": {
"$.clientId": {
"type": "Regex",
"regex": "[0-9]{10}"
}
}
},
"matchingRules": {
"header": {
"Content-Type": {
"matchers": [
{
"match": "regex",
"regex": "application/vnd\\.fraud\\.v1\\+json.*"
}
],
"combine": "AND"
}
},
"body": {
"$.clientId": {
"matchers": [
{
"match": "regex",
"regex": "[0-9]{10}"
}
],
"combine": "AND"
}
}
}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": {
"fraudCheckStatus": "FRAUD",
"rejectionReason": "Amount too high"
},
"matchingRules": {
"header": {
"Content-Type": {
"matchers": [
{
"match": "regex",
"regex": "application/vnd\\.fraud\\.v1\\+json.*"
}
],
"combine": "AND"
}
},
"body": {
"$.fraudCheckStatus": {
"matchers": [
{
"match": "regex",
"regex": "FRAUD"
}
],
"combine": "AND"
}
}
}
}
}
],
"metadata": {
"pact-specification": {
"version": "3.0.0"
},
"pact-jvm": {
"version": "3.5.13"
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The remainder of this section about using Pact refers to the preceding file.</p>
</div>
</div>
<div class="sect3">
<h4 id="_pact_for_producers"><a class="link" href="#_pact_for_producers">Pact for Producers</a></h4>
<div class="paragraph">
<p>On the producer side, you must add two additional dependencies to your plugin
configuration. One is the Spring Cloud Contract Pact support, and the other represents
the current Pact version that you use.</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;extensions&gt;true&lt;/extensions&gt;
&lt;configuration&gt;
&lt;packageWithBaseClasses&gt;com.example.fraud&lt;/packageWithBaseClasses&gt;
&lt;/configuration&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-pact&lt;/artifactId&gt;
&lt;version&gt;${spring-cloud-contract.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">classpath "org.springframework.cloud:spring-cloud-contract-pact:${findProperty('verifierVersion') ?: verifierVersion}"</code></pre>
</div>
</div>
<div class="paragraph">
<p>When you execute the build of your application, a test will be generated. The generated
test might be as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void validate_shouldMarkClientAsFraud() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/vnd.fraud.v1+json")
.body("{\"clientId\":\"1234567890\",\"loanAmount\":99999}");
// when:
ResponseOptions response = given().spec(request)
.put("/fraudcheck");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/vnd\\.fraud\\.v1\\+json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['rejectionReason']").isEqualTo("Amount too high");
// and:
assertThat(parsedJson.read("$.fraudCheckStatus", String.class)).matches("FRAUD");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The corresponding generated stub might be as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-javascript hljs" data-lang="javascript">{
"id" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
"uuid" : "996ae5ae-6834-4db6-8fac-358ca187ab62",
"request" : {
"url" : "/fraudcheck",
"method" : "PUT",
"headers" : {
"Content-Type" : {
"matches" : "application/vnd\\.fraud\\.v1\\+json.*"
}
},
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.['loanAmount'] == 99999)]"
}, {
"matchesJsonPath" : "$[?(@.clientId =~ /([0-9]{10})/)]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}",
"headers" : {
"Content-Type" : "application/vnd.fraud.v1+json;charset=UTF-8"
},
"transformers" : [ "response-template" ]
},
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_pact_for_consumers"><a class="link" href="#_pact_for_consumers">Pact for Consumers</a></h4>
<div class="paragraph">
<p>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.</p>
</div>
<div class="listingblock primary">
<div class="title">Maven</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-pact&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="listingblock secondary">
<div class="title">Gradle</div>
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">testCompile "org.springframework.cloud:spring-cloud-contract-pact"</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_the_custom_test_generator"><a class="link" href="#_using_the_custom_test_generator">Using the Custom Test Generator</a></h3>
<div class="paragraph">
<p>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.</p>
</div>
<div class="paragraph">
<p>The <code>SingleTestGenerator</code> interface lets you register your own implementation. The
following code listing shows the <code>SingleTestGenerator</code> interface:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.springframework.cloud.contract.verifier.builder;
import java.nio.file.Path;
import java.util.Collection;
import org.springframework.cloud.contract.verifier.config.ContractVerifierConfigProperties;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;
/**
* Builds a single test.
*
* @since 1.1.0
*/
public interface SingleTestGenerator {
/**
* Creates contents of a single test class in which all test scenarios from the
* contract metadata should be placed.
* @param properties - properties passed to the plugin
* @param listOfFiles - list of parsed contracts with additional metadata
* @param className - the name of the generated test class
* @param classPackage - the name of the package in which the test class should be
* stored
* @param includedDirectoryRelativePath - relative path to the included directory
* @return contents of a single test class
* @deprecated use{@link SingleTestGenerator#buildClass(ContractVerifierConfigProperties, Collection, String, GeneratedClassData)}
*/
@Deprecated
String buildClass(ContractVerifierConfigProperties properties,
Collection&lt;ContractMetadata&gt; listOfFiles, String className,
String classPackage, String includedDirectoryRelativePath);
/**
* Creates contents of a single test class in which all test scenarios from the
* contract metadata should be placed.
* @param properties - properties passed to the plugin
* @param listOfFiles - list of parsed contracts with additional metadata
* @param generatedClassData - information about the generated class
* @param includedDirectoryRelativePath - relative path to the included directory
* @return contents of a single test class
*/
default String buildClass(ContractVerifierConfigProperties properties,
Collection&lt;ContractMetadata&gt; listOfFiles,
String includedDirectoryRelativePath, GeneratedClassData generatedClassData) {
String className = generatedClassData.className;
String classPackage = generatedClassData.classPackage;
String path = includedDirectoryRelativePath;
return buildClass(properties, listOfFiles, className, classPackage, path);
}
/**
* Extension that should be appended to the generated test class. E.g. {@code .java}
* or {@code .php}
* @param properties - properties passed to the plugin
*/
String fileExtension(ContractVerifierConfigProperties properties);
class GeneratedClassData {
public final String className;
public final String classPackage;
public final Path testClassPath;
public GeneratedClassData(String className, String classPackage,
Path testClassPath) {
this.className = className;
this.classPackage = classPackage;
this.testClassPath = testClassPath;
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Again, you must provide a <code>spring.factories</code> file, such as the one shown in the following
example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/
com.example.MyGenerator</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_the_custom_stub_generator"><a class="link" href="#_using_the_custom_stub_generator">Using the Custom Stub Generator</a></h3>
<div class="paragraph">
<p>If you want to generate stubs for stub servers other than WireMock, you can plug in your
own implementation of the <code>StubGenerator</code> interface. The following code listing shows the
<code>StubGenerator</code> interface:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.springframework.cloud.contract.verifier.converter;
import java.util.Map;
import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.verifier.file.ContractMetadata;
/**
* Converts contracts into their stub representation.
*
* @since 1.1.0
*/
public interface StubGenerator {
/**
* @param fileName - file name
* @return {@code true} if the converter can handle the file to convert it into a
* stub.
*/
default boolean canHandleFileName(String fileName) {
return fileName.endsWith(fileExtension());
}
/**
* @param rootName - root name of the contract
* @param content - metadata of the contract
* @return the collection of converted contracts into stubs. One contract can result
* in multiple stubs.
*/
Map&lt;Contract, String&gt; convertContents(String rootName, ContractMetadata content);
/**
* @param inputFileName - name of the input file
* @return the name of the converted stub file. If you have multiple contracts in a
* single file then a prefix will be added to the generated file. If you provide the
* {@link Contract#name} field then that field will override the generated file name.
*
* Example: name of file with 2 contracts is {@code foo.groovy}, it will be converted
* by the implementation to {@code foo.json}. The recursive file converter will create
* two files {@code 0_foo.json} and {@code 1_foo.json}
*/
String generateOutputFileNameForInput(String inputFileName);
/**
* Describes the file extension that this stub generator can handle.
* @return string describing the file extension
*/
default String fileExtension() {
return ".json";
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Again, you must provide a <code>spring.factories</code> file, such as the one shown in the following
example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code># Stub converters
org.springframework.cloud.contract.verifier.converter.StubGenerator=\
org.springframework.cloud.contract.verifier.wiremock.DslToWireMockClientConverter</code></pre>
</div>
</div>
<div class="paragraph">
<p>The default implementation is the WireMock stub generation.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
You can provide multiple stub generator implementations. For example, from a single
DSL, you can produce both WireMock stubs and Pact files.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_using_the_custom_stub_runner"><a class="link" href="#_using_the_custom_stub_runner">Using the Custom Stub Runner</a></h3>
<div class="paragraph">
<p>If you decide to use a custom stub generation, you also need a custom way of running
stubs with your different stub provider.</p>
</div>
<div class="paragraph">
<p>Assume that you use <a href="https://github.com/dreamhead/moco">Moco</a> to build your stubs and that
you have written a stub generator and placed your stubs in a JAR file.</p>
</div>
<div class="paragraph">
<p>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:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">package org.springframework.cloud.contract.stubrunner.provider.moco
import com.github.dreamhead.moco.bootstrap.arg.HttpArgs
import com.github.dreamhead.moco.runner.JsonRunner
import com.github.dreamhead.moco.runner.RunnerSetting
import groovy.util.logging.Commons
import org.springframework.cloud.contract.stubrunner.HttpServerStub
import org.springframework.util.SocketUtils
@Commons
class MocoHttpServerStub implements HttpServerStub {
private boolean started
private JsonRunner runner
private int port
@Override
int port() {
if (!isRunning()) {
return -1
}
return port
}
@Override
boolean isRunning() {
return started
}
@Override
HttpServerStub start() {
return start(SocketUtils.findAvailableTcpPort())
}
@Override
HttpServerStub start(int port) {
this.port = port
return this
}
@Override
HttpServerStub stop() {
if (!isRunning()) {
return this
}
this.runner.stop()
return this
}
@Override
HttpServerStub registerMappings(Collection&lt;File&gt; stubFiles) {
List&lt;RunnerSetting&gt; settings = stubFiles.findAll { it.name.endsWith("json") }
.collect {
log.info("Trying to parse [${it.name}]")
try {
return RunnerSetting.aRunnerSetting().withStream(it.newInputStream()).
build()
}
catch (Exception e) {
log.warn("Exception occurred while trying to parse file [${it.name}]", e)
return null
}
}.findAll { it }
this.runner = JsonRunner.newJsonRunnerWithSetting(settings,
HttpArgs.httpArgs().withPort(this.port).build())
this.runner.run()
this.started = true
return this
}
@Override
String registeredMappings() {
return ""
}
@Override
boolean isAccepted(File file) {
return file.name.endsWith(".json")
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then, you can register it in your <code>spring.factories</code> file, as shown in the following
example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>org.springframework.cloud.contract.stubrunner.HttpServerStub=\
org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now you can run stubs with Moco.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
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.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_using_the_custom_stub_downloader"><a class="link" href="#_using_the_custom_stub_downloader">Using the Custom Stub Downloader</a></h3>
<div class="paragraph">
<p>You can customize the way your stubs are downloaded by creating an implementation of the
<code>StubDownloaderBuilder</code> interface, as shown in the following example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example;
class CustomStubDownloaderBuilder implements StubDownloaderBuilder {
@Override
public StubDownloader build(final StubRunnerOptions stubRunnerOptions) {
return new StubDownloader() {
@Override
public Map.Entry&lt;StubConfiguration, File&gt; downloadAndUnpackStubJar(
StubConfiguration config) {
File unpackedStubs = retrieveStubs();
return new AbstractMap.SimpleEntry&lt;&gt;(
new StubConfiguration(config.getGroupId(), config.getArtifactId(), version,
config.getClassifier()), unpackedStubs);
}
File retrieveStubs() {
// here goes your custom logic to provide a folder where all the stubs reside
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then you can register it in your <code>spring.factories</code> file, as shown in the following
example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code># Example of a custom Stub Downloader Provider
org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\
com.example.CustomStubDownloaderBuilder</code></pre>
</div>
</div>
<div class="paragraph">
<p>Now you can pick a folder with the source of your stubs.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
If you do not provide any implementation, then the default is used (scan classpath).
If you provide the <code>stubsMode = StubRunnerProperties.StubsMode.LOCAL</code> or
<code>, stubsMode = StubRunnerProperties.StubsMode.REMOTE</code> then the Aether implementation will be used
If you provide more than one, then the first one on the list is used.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="scm-stub-downloader"><a class="link" href="#scm-stub-downloader">Using the SCM Stub Downloader</a></h3>
<div class="paragraph">
<p>Whenever the <code>repositoryRoot</code> starts with a SCM protocol
(currently we support only <code>git://</code>), the stub downloader will try
to clone the repository and use it as a source of contracts
to generate tests or stubs.</p>
</div>
<div class="paragraph">
<p>Either via environment variables, system properties, properties set
inside the plugin or contracts repository configuration you can
tweak the downloader&#8217;s behaviour. Below you can find the list of
properties</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<caption class="title">Table 1. SCM Stub Downloader properties</caption>
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">Type of a property</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Name of the property</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Description</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>git.branch</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.git.branch</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_GIT_BRANCH</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">master</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Which branch to checkout</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>git.username</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.git.username</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_GIT_USERNAME</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Git clone username</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>git.password</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.git.password</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_GIT_PASSWORD</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Git clone password</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>git.no-of-attempts</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.git.no-of-attempts</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_GIT_NO_OF_ATTEMPTS</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">10</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Number of attempts to push the commits to <code>origin</code></p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>git.wait-between-attempts</code> (Plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.git.wait-between-attempts</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_GIT_WAIT_BETWEEN_ATTEMPTS</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">1000</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Number of millis to wait between attempts to push the commits to <code>origin</code></p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect2">
<h3 id="pact-stub-downloader"><a class="link" href="#pact-stub-downloader">Using the Pact Stub Downloader</a></h3>
<div class="paragraph">
<p>Whenever the <code>repositoryRoot</code> starts with a Pact protocol
(starts with <code>pact://</code>), the stub downloader will try
to fetch the Pact contract definitions from the Pact Broker.
Whatever is set after <code>pact://</code> will be parsed as the Pact Broker URL.</p>
</div>
<div class="paragraph">
<p>Either via environment variables, system properties, properties set
inside the plugin or contracts repository configuration you can
tweak the downloader&#8217;s behaviour. Below you can find the list of
properties</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<caption class="title">Table 2. SCM Stub Downloader properties</caption>
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">Name of a property</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Default</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Description</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.host</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.host</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_HOST</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Host from URL passed to <code>repositoryRoot</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">What is the URL of Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.port</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.port</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_PORT</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Port from URL passed to <code>repositoryRoot</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">What is the port of Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.protocol</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.protocol</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_PROTOCOL</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Protocol from URL passed to <code>repositoryRoot</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">What is the protocol of Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.tags</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.tags</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_TAGS</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Version of the stub, or <code>latest</code> if version is <code>+</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">What tags should be used to fetch the stub</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.auth.scheme</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.auth.scheme</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_SCHEME</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Basic</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">What kind of authentication should be used to connect to the Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.auth.username</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.auth.username</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_USERNAME</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The username passed to <code>contractsRepositoryUsername</code> (maven) or <code>contractRepository.username</code> (gradle)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Username used to connect to the Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.auth.password</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.auth.password</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_AUTH_PASSWORD</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The password passed to <code>contractsRepositoryPassword</code> (maven) or <code>contractRepository.password</code> (gradle)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Password used to connect to the Pact Broker</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">* <code>pactbroker.provider-name-with-group-id</code> (plugin prop)</p>
<p class="tableblock">* <code>stubrunner.properties.pactbroker.provider-name-with-group-id</code> (system prop)</p>
<p class="tableblock">* <code>STUBRUNNER_PROPERTIES_PACTBROKER_PROVIDER_NAME_WITH_GROUP_ID</code> (env prop)</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">false</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">When <code>true</code>, the provider name will be a combination of <code>groupId:artifactId</code>. If <code>false</code>, just <code>artifactId</code> is used</p></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="js/tocbot/tocbot.min.js"></script>
<script type="text/javascript" src="js/toc.js"></script>
<link rel="stylesheet" href="js/highlight/styles/atom-one-dark-reasonable.min.css">
<script src="js/highlight/highlight.min.js"></script>
<script>hljs.initHighlighting()</script>
</body>
</html>