14911 lines
567 KiB
HTML
14911 lines
567 KiB
HTML
<!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">
|
||
<meta name="author" content="Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant">
|
||
<title>Spring Cloud Contract Reference Documentation</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 id="spring-cloud-contract-reference-documentation" class="book toc2 toc-left">
|
||
<div id="header">
|
||
<h1>Spring Cloud Contract Reference Documentation</h1>
|
||
<div class="details">
|
||
<span id="author" class="author">Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant</span><br>
|
||
</div>
|
||
<div id="toc" class="toc2">
|
||
<div id="toctitle">Table of Contents</div>
|
||
<ul class="sectlevel1">
|
||
<li><a href="#legal">Legal</a></li>
|
||
<li><a href="#documentation">1. Spring Cloud Contract Documentation</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#contract-documentation-about">1.1. About the Documentation</a></li>
|
||
<li><a href="#documentation-getting-help">1.2. Getting Help</a></li>
|
||
<li><a href="#contract-documentation-first-steps">1.3. First Steps</a></li>
|
||
<li><a href="#working-with-spring-cloud-contract">1.4. Working with Spring Cloud Contract</a></li>
|
||
<li><a href="#learning-about-spring-cloud-contract-features">1.5. Learning about Spring Cloud Contract Features</a></li>
|
||
<li><a href="#advanced-topics">1.6. Advanced Topics</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started">2. Getting Started</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#getting-started-introducing-spring-cloud-contract">2.1. Introducing Spring Cloud Contract</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#getting-started-introducing-spring-cloud-contract-history">2.1.1. History</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#getting-started-introducing-spring-cloud-contract-why">Why Do You Need It?</a></li>
|
||
<li><a href="#getting-started-introducing-spring-cloud-contract-testing-issues">Testing Issues</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-introducing-spring-cloud-contract-purposes">2.1.2. Purposes</a></li>
|
||
<li><a href="#getting-started-what-is-a-contract">2.1.3. What Is a Contract?</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-three-second-tour">2.2. A Three-second Tour</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#getting-started-three-second-tour-producer">2.2.1. On the Producer Side</a></li>
|
||
<li><a href="#getting-started-three-second-tour-consumer">2.2.2. On the Consumer Side</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-first-application">2.3. Developing Your First Spring Cloud Contract-based Application</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#getting-started-first-application-producer">2.3.1. On the Producer Side</a></li>
|
||
<li><a href="#getting-started-first-application-consumer">2.3.2. On the Consumer Side</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-cdc">2.4. Step-by-step Guide to Consumer Driven Contracts (CDC) with Contracts on the Producer Side</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#getting-started-cdc-technical-note">2.4.1. Technical Note</a></li>
|
||
<li><a href="#getting-started-cdc-consumer">2.4.2. The Consumer Side (Loan Issuance)</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#getting-started-cdc-consumer-start">Start Doing TDD by Writing a Test for Your Feature</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-write">Write the Missing Implementation</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-clone">Clone the Fraud Detection service repository locally</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-define">Define the Contract Locally in the Repository of the Fraud Detection Service</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-add">Add the Spring Cloud Contract Verifier Plugin</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-run">Running the Integration Tests</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-file">Filing a Pull Request</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-cdc-producer">2.4.3. The Producer Side (Fraud Detection server)</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#getting-started-cdc-producer-pr">Taking over the Pull Request</a></li>
|
||
<li><a href="#getting-started-cdc-producer-impl">Write the Missing Implementation</a></li>
|
||
<li><a href="#getting-started-cdc-producer-deploy">Deploying Your Application</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-cdc-consumer-final">2.4.4. Consumer Side (Loan Issuance), Final Step</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#getting-started-cdc-consumer-final-merge">Merging a Branch to Master</a></li>
|
||
<li><a href="#getting-started-cdc-consumer-final-online">Working Online</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#getting-started-whats-next">2.5. Next Steps</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#using">3. Using Spring Cloud Contract</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#flows-provider-nexus">3.1. Provider Contract Testing with Stubs in Nexus or Artifactory</a></li>
|
||
<li><a href="#flows-provider-git">3.2. Provider Contract Testing with Stubs in Git</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#prerequisites">3.2.1. Prerequisites</a></li>
|
||
<li><a href="#flows-provider-git-flow">3.2.2. The Flow</a></li>
|
||
<li><a href="#flows-provider-git-consumer">3.2.3. Consumer setup</a></li>
|
||
<li><a href="#flows-provider-git-producer">3.2.4. Setting up the Producer</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#flows-cdc-contracts-producer">3.3. Consumer Driven Contracts with Contracts on the Producer Side</a></li>
|
||
<li><a href="#flows-cdc-contracts-external">3.4. Consumer Driven Contracts with Contracts in an External Repository</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#prerequisites-2">3.4.1. Prerequisites</a></li>
|
||
<li><a href="#flows-cdc-contracts-external-consumer">3.4.2. Consumer Flow</a></li>
|
||
<li><a href="#flows-cdc-contracts-external-producer">3.4.3. Producer Flow</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#flows-cdc-contracts-stubs-git">3.5. Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git</a></li>
|
||
<li><a href="#flows-provider-non-spring">3.6. Provider Contract Testing with Stubs in Artifactory for a non-Spring Application</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#flows-provider-non-spring-flow">3.6.1. The Flow</a></li>
|
||
<li><a href="#flows-provider-non-spring-consumer">3.6.2. Setting up the Consumer</a></li>
|
||
<li><a href="#flows-provider-non-spring-producer">3.6.3. Setting up the Producer</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#flows-provider-non-jvm">3.7. Provider Contract Testing with Stubs in Artifactory in a non-JVM World</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#flows-provider-non-jvm-producer">3.7.1. Producer Flow</a></li>
|
||
<li><a href="#flows-provider-non-jvm-consumer">3.7.2. Consumer Flow</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#flows-provider-rest-docs">3.8. Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#flows-provider-rest-docs-producer">3.8.1. Producer Flow</a></li>
|
||
<li><a href="#flows-provider-rest-docs-consumer">3.8.2. Consumer Flow</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#using-whats-next">3.9. What to Read Next</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features">4. Spring Cloud Contract Features</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#contract-dsl">4.1. Contract DSL</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#contract-limitations">4.1.1. Limitations</a></li>
|
||
<li><a href="#contract-common-top-elements">4.1.2. Common Top-Level Elements</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#contract-dsl-description">Description</a></li>
|
||
<li><a href="#contract-dsl-name">Name</a></li>
|
||
<li><a href="#contract-dsl-ignoring-contracts">Ignoring Contracts</a></li>
|
||
<li><a href="#contract-dsl-in-progress">Contracts in Progress</a></li>
|
||
<li><a href="#contract-dsl-passing-values-from-files">Passing Values from Files</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-http">4.2. Contracts for HTTP</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#contract-dsl-http-top-level-elements">4.2.1. HTTP Top-Level Elements</a></li>
|
||
<li><a href="#contract-dsl-request">4.2.2. HTTP Request</a></li>
|
||
<li><a href="#contract-dsl-response">4.2.3. HTTP Response</a></li>
|
||
<li><a href="#contract-dsl-dynamic-properties">4.2.4. Dynamic properties</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#contract-dsl-dynamic-properties-in-body">Dynamic Properties inside the Body</a></li>
|
||
<li><a href="#contract-dsl-regex">Regular Expressions</a></li>
|
||
<li><a href="#contract-dsl-optional-params">Passing Optional Parameters</a></li>
|
||
<li><a href="#contract-dsl-custom-methods">Executing Custom Methods on the Server Side</a></li>
|
||
<li><a href="#contract-dsl-referencing-request-from-response">Referencing the Request from the Response</a></li>
|
||
<li><a href="#contract-dsl-matchers">Dynamic Properties in the Matchers Sections</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#contract-dsl-async">4.2.5. Asynchronous Support</a></li>
|
||
<li><a href="#contract-dsl-xml">4.2.6. XML Support for HTTP</a></li>
|
||
<li><a href="#contract-dsl-multiple">4.2.7. Multiple Contracts in One File</a></li>
|
||
<li><a href="#contract-stateful-contracts">4.2.8. Stateful Contracts</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#feature-integrations">4.3. Integrations</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#features-jax-rs">4.3.1. JAX-RS</a></li>
|
||
<li><a href="#feature-webflux">4.3.2. WebFlux with WebTestClient</a></li>
|
||
<li><a href="#feature-webflux-explicit">4.3.3. WebFlux with Explicit Mode</a></li>
|
||
<li><a href="#features-context-paths">4.3.4. Working with Context Paths</a></li>
|
||
<li><a href="#features-rest-docs">4.3.5. Working with REST Docs</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-rest-docs-contracts">Generating Contracts with REST Docs</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging">4.4. Messaging</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#contract-dsl-messaging-top-level">4.4.1. Messaging DSL Top-Level Elements</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#contract-dsl-output-triggered-method">Output Triggered by a Method</a></li>
|
||
<li><a href="#contract-dsl-output-triggered-message">Output Triggered by a Message</a></li>
|
||
<li><a href="#contract-dsl-consumer-producer">Consumer/Producer</a></li>
|
||
<li><a href="#contract-dsl-messaging-common">Common</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-integrations">4.4.2. Integrations</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-manual">Manual Integration Testing</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-test-generation">4.4.3. Producer Side Messaging Test Generation</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-scenario1">Scenario 1: No Input Message</a></li>
|
||
<li><a href="#features-messaging-scenario2">Scenario 2: Output Triggered by Input</a></li>
|
||
<li><a href="#features-messaging-scenario3">Scenario 3: No Output Message</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-consumer">4.4.4. Consumer Stub Generation</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-stub-triggering">Stub triggering</a></li>
|
||
<li><a href="#features-messaging-trigger-label">Trigger by Label</a></li>
|
||
<li><a href="#features-messaging-trigger-group-artifact-ids">Trigger by Group and Artifact Ids</a></li>
|
||
<li><a href="#features-messaging-trigger-artifact-ids">Trigger by Artifact IDs</a></li>
|
||
<li><a href="#features-messaging-trigger-all-messages">Trigger All Messages</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-stub-runner-camel">4.4.5. Consumer Side Messaging With Apache Camel</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-stub-runner-camel-adding">Adding Apache Camel to the Project</a></li>
|
||
<li><a href="#features-messaging-stub-runner-camel-disabling">Disabling the Functionality</a></li>
|
||
<li><a href="#features-messaging-stub-runner-camel-example">Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-stub-runner-integration">4.4.6. Consumer Side Messaging with Spring Integration</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-stub-runner-integration-adding">Adding the Runner to the Project</a></li>
|
||
<li><a href="#features-messaging-stub-runner-integration-disabling">Disabling the Functionality</a></li>
|
||
<li><a href="#features-messaging-stub-runner-integration-example">Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-stub-runner-stream">4.4.7. Consumer Side Messaging With Spring Cloud Stream</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-stub-runner-stream-adding">Adding the Runner to the Project</a></li>
|
||
<li><a href="#features-messaging-stub-runner-stream-disabling">Disabling the Functionality</a></li>
|
||
<li><a href="#features-messaging-stub-runner-stream-example">Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-messaging-stub-runner-amqp">4.4.8. Consumer Side Messaging With Spring AMQP</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-messaging-stub-runner-amqp-adding">Adding the Runner to the Project</a></li>
|
||
<li><a href="#features-messaging-stub-runner-amqp-example">Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-stub-runner">4.5. Spring Cloud Contract Stub Runner</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#features-stub-runner-snapshot-versions">4.5.1. Snapshot Versions</a></li>
|
||
<li><a href="#features-stub-runner-publishing-stubs-as-jars">4.5.2. Publishing Stubs as JARs</a></li>
|
||
<li><a href="#features-stub-runner-core">4.5.3. Stub Runner Core</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-stub-runner-retrieving">Retrieving stubs</a></li>
|
||
<li><a href="#features-stub-runner-running-stubs">Running stubs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-stub-runner-junit">4.5.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-stub-runner-rule-maven-settings">Maven Settings</a></li>
|
||
<li><a href="#features-stub-runner-rule-fixed-ports">Providing Fixed Ports</a></li>
|
||
<li><a href="#features-stub-runner-rule-fluent-api">Fluent API</a></li>
|
||
<li><a href="#features-stub-runner-rule-spring">Stub Runner with Spring</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-stub-runner-cloud">4.5.5. Stub Runner Spring Cloud</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-stub-runner-cloud-stubbing-discovery">Stubbing Service Discovery</a></li>
|
||
<li><a href="#features-stub-runner-additional-config">Additional Configuration</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-stub-runner-boot">4.5.6. Using the Stub Runner Boot Application</a>
|
||
<ul class="sectlevel5">
|
||
<li><a href="#features-stub-runner-boot-server">Stub Runner Server</a></li>
|
||
<li><a href="#features-stub-runner-boot-how-fat-jar">Stub Runner Server Fat Jar</a></li>
|
||
<li><a href="#features-stub-runner-boot-how-cli">Spring Cloud CLI</a></li>
|
||
<li><a href="#features-stub-runner-boot-endpoints">Endpoints</a></li>
|
||
<li><a href="#features-stub-runner-boot-endpoints-example">Example</a></li>
|
||
<li><a href="#features-stub-runner-boot-service-discovery">Stub Runner Boot with Service Discovery</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-stub-runner-stubs-per-consumer">4.5.7. Consumer-Driven Contracts: Stubs Per Consumer</a></li>
|
||
<li><a href="#features-stub-runner-stubs-protocol">4.5.8. Fetching Stubs or Contract Definitions From A Location</a></li>
|
||
<li><a href="#features-stub-runner-generate-stubs-at-runtime">4.5.9. Generating Stubs at Runtime</a></li>
|
||
<li><a href="#features-stub-runner-fail-on-no-stubs">4.5.10. Fail On No Stubs</a></li>
|
||
<li><a href="#features-stub-runner-common">4.5.11. Common Properties</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#features-stub-runner-common-properties-junit-spring">Common Properties for JUnit and Spring</a></li>
|
||
<li><a href="#features-stub-runner-stub-runner-stub-ids">Stub Runner Stubs IDs</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-wiremock">4.6. Spring Cloud Contract WireMock</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#features-wiremock-registering-stubs">4.6.1. Registering Stubs Automatically</a></li>
|
||
<li><a href="#features-wiremock-using-files">4.6.2. Using Files to Specify the Stub Bodies</a></li>
|
||
<li><a href="#features-wiremock-junit-rule">4.6.3. Alternative: Using JUnit Rules</a></li>
|
||
<li><a href="#features-wiremock-relaxed-ssl">4.6.4. Relaxed SSL Validation for Rest Template</a></li>
|
||
<li><a href="#features-wiremock-spring-mvc-mocks">4.6.5. WireMock and Spring MVC Mocks</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#features-build-tools">4.7. Build Tools Integration</a></li>
|
||
<li><a href="#features-whats-next">4.8. What to Read Next</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#howto">5. “How-to” Guides</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#why-spring-cloud-contract">5.1. Why use Spring Cloud Contract?</a></li>
|
||
<li><a href="#how-to-not-write-contracts-in-groovy">5.2. How Can I Write Contracts in a Language Other than Groovy?</a></li>
|
||
<li><a href="#how-to-provide-dynamic-values">5.3. How Can I Provide Dynamic Values to a Contract?</a></li>
|
||
<li><a href="#how-to-do-stubs-versioning">5.4. How to Do Stubs versioning?</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#how-to-api-versioning">5.4.1. API Versioning</a></li>
|
||
<li><a href="#how-to-jar-versioning">5.4.2. JAR versioning</a></li>
|
||
<li><a href="#how-to-dev-or-prod-stubs">5.4.3. Development or Production Stubs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#how-to-common-repo-with-contracts">5.5. How Can I use a Common Repository with Contracts Instead of Storing Them with the Producer?</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#how-to-repo-structure">5.5.1. Repo Structure</a></li>
|
||
<li><a href="#how-to-workflow">5.5.2. Workflow</a></li>
|
||
<li><a href="#how-to-workflow-consumer">5.5.3. Consumer</a></li>
|
||
<li><a href="#how-to-workflow-producer">5.5.4. Producer</a></li>
|
||
<li><a href="#how-to-define-messaging-contracts-per-topic">5.5.5. How Can I Define Messaging Contracts per Topic Rather than per Producer?</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#how-to-define-messaging-contracts-per-topic-maven">For Maven Projects</a></li>
|
||
<li><a href="#how-to-define-messaging-contracts-per-topic-gradle">For Gradle Projects</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#how-to-use-git-as-storage">5.6. How Can I Use Git as the Storage for Contracts and Stubs?</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#how-to-protocol-convention">5.6.1. Protocol Convention</a></li>
|
||
<li><a href="#how-to-protocol-convention-producer">5.6.2. Producer</a></li>
|
||
<li><a href="#how-to-protocol-convention-producer-with-contracts-stored-locally">5.6.3. Producer with Contracts Stored Locally</a></li>
|
||
<li><a href="#how-to-protocol-convention-contracts-producer-stubs-external">5.6.4. Keeping Contracts with the Producer and Stubs in an External Repository</a></li>
|
||
<li><a href="#how-to-protocol-convention-contracts-producer-stubs-external-consumer">5.6.5. Consumer</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#how-to-use-pact-broker">5.7. How Can I Use the Pact Broker?</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#how-to-use-pact-broker-pact">5.7.1. How to Work with Pact</a></li>
|
||
<li><a href="#how-to-use-pact-broker-pact-converter">5.7.2. Pact Converter</a></li>
|
||
<li><a href="#how-to-use-pact-broker-pact-contract">5.7.3. Pact Contract</a></li>
|
||
<li><a href="#how-to-use-pact-broker-pact-for-producers">5.7.4. Pact for Producers</a></li>
|
||
<li><a href="#how-to-use-pact-broker-pact-consumers">5.7.5. Pact for Consumers</a></li>
|
||
<li><a href="#pact-stub-downloader">5.7.6. Communicating with the Pact Broker</a></li>
|
||
<li><a href="#how-to-pact-consumer">5.7.7. Flow: Consumer Contract approach with Pact Broker | Consumer Side</a></li>
|
||
<li><a href="#how-to-pact-producer">5.7.8. Flow: Consumer Contract Approach with Pact Broker on the Producer Side</a></li>
|
||
<li><a href="#how-to-pact-consumer-producer-contract">5.7.9. Flow: Producer Contract approach with Pact on the Consumer Side</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#how-to-debug">5.8. How Can I Debug the Request/Response Being Sent by the Generated Tests Client?</a></li>
|
||
<li><a href="#how-to-debug-wiremock">5.9. How Can I Debug the Mapping, Request, or Response Being Sent by WireMock?</a></li>
|
||
<li><a href="#how-to-see-registered-stubs">5.10. How Can I See What Got Registered in the HTTP Server Stub?</a></li>
|
||
<li><a href="#how-to-reference-text-from-file">5.11. How Can I Reference Text from File?</a></li>
|
||
<li><a href="#how-to-generate-pact-from-scc">5.12. How Can I Generate Pact, YAML, or X files from Spring Cloud Contract Contracts?</a></li>
|
||
<li><a href="#how-to-work-with-transitivie">5.13. How Can I Work with Transitive Dependencies?</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#how-to-work-with-transitivie-optional">5.13.1. How Can I Mark All Application Dependencies as Optional?</a></li>
|
||
<li><a href="#how-to-work-with-transitivie-separate">5.13.2. How can I Create a Separate <code>artifactid</code> for the Stubs?</a></li>
|
||
<li><a href="#how-to-work-with-transitivie-exclude">5.13.3. How can I Exclude Dependencies on the Consumer Side?</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#contract-dsl-rest-docs">5.14. How can I Generate Spring REST Docs Snippets from the Contracts?</a></li>
|
||
<li><a href="#how-to-use-stubs-from-a-location">5.15. How can I Use Stubs from a Location</a></li>
|
||
<li><a href="#how-to-generate-stubs-at-runtime">5.16. How can I Generate Stubs at Runtime</a></li>
|
||
<li><a href="#how-to-use-the-failonnostubs-feature">5.17. How can I Make The Build Pass if There Are No Contracts or Stubs</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div id="content">
|
||
<div class="sect1">
|
||
<h2 id="legal"><a class="anchor" href="#legal"></a><a class="link" href="#legal">Legal</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>2.2.0.BUILD-SNAPSHOT</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Copyright © 2012-2019</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Copies of this document may be made for your own use and for distribution to
|
||
others, provided that you do not charge any fee for such copies and further
|
||
provided that each copy contains this Copyright Notice, whether distributed in
|
||
print or electronically.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="documentation"><a class="anchor" href="#documentation"></a><a class="link" href="#documentation">1. Spring Cloud Contract Documentation</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>This section provides a brief overview of Spring Cloud Contract reference documentation. It serves
|
||
as a map for the rest of the document.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="contract-documentation-about"><a class="anchor" href="#contract-documentation-about"></a><a class="link" href="#contract-documentation-about">1.1. About the Documentation</a></h3>
|
||
<div class="paragraph">
|
||
<p>The Spring Cloud Contract reference guide is available as</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="https://cloud.spring.io/spring-cloud-contract/html/">Multi-page HTML</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://cloud.spring.io/spring-cloud-contract//htmlsingle/">Single-page HTML</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://cloud.spring.io/spring-cloud-contract/pdf/spring-cloud-contract.pdf">PDF</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Copies of this document may be made for your own use and for distribution to others,
|
||
provided that you do not charge any fee for such copies and further provided that each
|
||
copy contains this Copyright Notice, whether distributed in print or electronically.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="documentation-getting-help"><a class="anchor" href="#documentation-getting-help"></a><a class="link" href="#documentation-getting-help">1.2. Getting Help</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you have trouble with Spring Cloud Contract, we would like to help.</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Try the <a href="#howto">How-to documents</a>. They provide solutions to the most
|
||
common questions.</p>
|
||
</li>
|
||
<li>
|
||
<p>Learn the Spring Cloud Contract basics. If you are
|
||
starting out with Spring Cloud Contract, try one of the <a href="https://spring.io/guides">guides</a>.</p>
|
||
</li>
|
||
<li>
|
||
<p>Ask a question. We monitor <a href="https://stackoverflow.com">stackoverflow.com</a> for questions
|
||
tagged with <a href="https://stackoverflow.com/tags/spring-cloud-contract"><code>spring-cloud-contract</code></a>.</p>
|
||
</li>
|
||
<li>
|
||
<p>Report bugs with Spring Cloud Contract at <a href="https://github.com/spring-cloud/spring-cloud-contract/issues" class="bare">github.com/spring-cloud/spring-cloud-contract/issues</a>.</p>
|
||
</li>
|
||
<li>
|
||
<p>Chat with us at <a href="http://https://gitter.im/spring-cloud/spring-cloud-contract">Spring Cloud Contract Gitter</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
All of Spring Cloud Contract is open source, including the documentation. If you find
|
||
problems with the docs or if you want to improve them, please <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/${github-tag}">get
|
||
involved</a>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="contract-documentation-first-steps"><a class="anchor" href="#contract-documentation-first-steps"></a><a class="link" href="#contract-documentation-first-steps">1.3. First Steps</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you are getting started with Spring Cloud Contract or 'Spring' in general, start with
|
||
<a href="#getting-started">the following topics</a>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>From scratch:</strong>
|
||
<a href="#getting-started-introducing-spring-cloud-contract">Overview</a> |
|
||
<a href="#getting-started-three-second-tour">Three-second Tour</a> |
|
||
<a href="#getting-started-first-application">First application</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Tutorial:</strong>
|
||
<a href="#getting-started-cdc">Introduction</a> |
|
||
<a href="#consumer-side-loan-issuance">Consumer, Part 1</a> |
|
||
<a href="#producer-side-fraud-detection-server">Producer</a> |
|
||
<a href="#consumer-side-loan-issuance-final-step">Consumer, Part 2</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="working-with-spring-cloud-contract"><a class="anchor" href="#working-with-spring-cloud-contract"></a><a class="link" href="#working-with-spring-cloud-contract">1.4. Working with Spring Cloud Contract</a></h3>
|
||
<div class="paragraph">
|
||
<p>Ready to actually start using Spring Cloud Contract? <a href="#using">We have
|
||
you covered</a>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>Provider contract testing:</strong></p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#flows-provider-nexus">Provider contract testing with stubs in Nexus or Artifactory</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-provider-git">Provider contract testing with stubs in Git</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-provider-non-spring">Provider contract testing with stubs in Artifactory for a non-Spring application</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-provider-non-jvm">Provider contract testing with stubs in Artifactory in non JVM world</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-provider-rest-docs">Provider contract testing with REST Docs and stubs in Nexus / Artifactory</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p><strong>Consumer-Driven contract testing:</strong></p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#flows-cdc-contracts-producer">Consumer Driven Contracts with contracts on the producer side</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-cdc-contracts-external">Consumer Driven Contracts with contracts in external repo</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#flows-cdc-contracts-stubs-git">Consumer Driven Contracts with contracts on the producer side, pushed to git</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
We talk about <strong>Provider Contracts</strong> when it is the producer of the API that defines the contracts and
|
||
publishes it for all its consumers to use. This approach is useful for producers that cannot
|
||
directly collaborate with their consumers — for example, when there are too many consumers or
|
||
the consumers are external (do not work within the same company).
|
||
</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">
|
||
We use the term, <strong>Consumer-Driven Contracts</strong>, to refer to workflows where the consumers of an API
|
||
play a vital role in the process of creating the contracts. We recommended this approach, because it is easy
|
||
to implement when both producer and consumer teams work for the same organizations and the number
|
||
of consumers is not extremely large.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="learning-about-spring-cloud-contract-features"><a class="anchor" href="#learning-about-spring-cloud-contract-features"></a><a class="link" href="#learning-about-spring-cloud-contract-features">1.5. Learning about Spring Cloud Contract Features</a></h3>
|
||
<div class="paragraph">
|
||
<p>Need more details about Spring Cloud Contract’s core features?
|
||
<a href="#features">The following content is for you</a>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>Core Features:</strong>
|
||
<a href="#contract-dsl">Contract DSL</a> |
|
||
<a href="#features-http">Contracts for HTTP</a> |
|
||
<a href="#features-messaging">Contracts for Messaging</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Integrations:</strong>
|
||
<a href="#features-jax-rs">JAX-RS</a> |
|
||
<a href="#features-context-paths">Context Paths</a> |
|
||
<a href="#features-rest-docs">RESTDocs</a>
|
||
<a href="#how-to-generate-pact-from-scc">Pact</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Modules:</strong>
|
||
<a href="#features-stub-runner">Stub Runner</a> |
|
||
<a href="#features-wiremock">WireMock</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Build Tools:</strong>
|
||
<a href="maven-project.html">Contract Verifier - Maven</a> |
|
||
<a href="gradle-project.html">Contract Verifier - Gradle</a> |
|
||
<a href="docker-project.html">Docker</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="advanced-topics"><a class="anchor" href="#advanced-topics"></a><a class="link" href="#advanced-topics">1.6. Advanced Topics</a></h3>
|
||
<div class="paragraph">
|
||
<p>Finally, we have a few topics for more advanced users:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>Customizing the DSL:</strong>
|
||
<a href="advanced.html#contract-dsl-customization">DSL Customization</a> |
|
||
<a href="advanced.html#contract-dsl-extending-common-jar">Common JAR</a> |
|
||
<a href="advanced.html#contract-dsl-test-dep">Test Dependency</a> |
|
||
<a href="advanced.html#contract-dsl-plugin-dep">Plugin Dependency</a> |
|
||
<a href="advanced.html#contract-dsl-referencing">Referencing the DSL</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Customizing WireMock:</strong>
|
||
<a href="advanced.html#customization-wiremock-extension">Extensions</a> |
|
||
<a href="advanced.html#customization-wiremock-configuration">Configuration</a></p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Customizing Spring Cloud Contract:</strong>
|
||
<a href="advanced.html#contract-dsl-pluggable-architecture">Pluggable Architecture</a> |
|
||
<a href="advanced.html#contract-dsl-custom-contract-converter">Contract Converter</a> |
|
||
<a href="advanced.html#contract-dsl-custom-test-generator">Test Generator</a> |
|
||
<a href="advanced.html#contract-dsl-custom-stub-generator">Stub Generator</a> |
|
||
<a href="advanced.html#contract-dsl-custom-stub-runner">Stub Runner</a> |
|
||
<a href="advanced.html#contract-dsl-custom-stub-downloader">Stub Downloader</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="getting-started"><a class="anchor" href="#getting-started"></a><a class="link" href="#getting-started">2. Getting Started</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>If you are getting started with Spring Cloud Contract, or Spring in general, start by reading
|
||
this section. It answers the basic “what?”, “how?” and “why?” questions. It
|
||
includes an introduction to Spring Cloud Contract, along with installation instructions. We then
|
||
walk you through building your first Spring Cloud Contract application, discussing some core
|
||
principles as we go.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="getting-started-introducing-spring-cloud-contract"><a class="anchor" href="#getting-started-introducing-spring-cloud-contract"></a><a class="link" href="#getting-started-introducing-spring-cloud-contract">2.1. Introducing Spring Cloud Contract</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract moves TDD to the level of software architecture.
|
||
It lets you perform consumer-driven and producer-driven contract testing.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-introducing-spring-cloud-contract-history"><a class="anchor" href="#getting-started-introducing-spring-cloud-contract-history"></a><a class="link" href="#getting-started-introducing-spring-cloud-contract-history">2.1.1. History</a></h4>
|
||
<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 class="sect4">
|
||
<h5 id="getting-started-introducing-spring-cloud-contract-why"><a class="anchor" href="#getting-started-introducing-spring-cloud-contract-why"></a><a class="link" href="#getting-started-introducing-spring-cloud-contract-why">Why Do You Need It?</a></h5>
|
||
<div class="paragraph">
|
||
<p>Assume that we have a system that consists of multiple microservices, as the following
|
||
image shows:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/Deps.png" alt="Microservices Architecture">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-introducing-spring-cloud-contract-testing-issues"><a class="anchor" href="#getting-started-introducing-spring-cloud-contract-testing-issues"></a><a class="link" href="#getting-started-introducing-spring-cloud-contract-testing-issues">Testing Issues</a></h5>
|
||
<div class="paragraph">
|
||
<p>If we want to test the application in the top left corner of the image in the preceding
|
||
section 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 and 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 six microservices, a couple of databases,
|
||
and other items.</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 and 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 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. The following image shows the relationship
|
||
of stubs to an application:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/Stubs2.png" alt="Stubbed Services">
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract gives you the certainty that the stubs that you use were
|
||
created by the service that you call. Also, if you can use them, it means that they
|
||
were tested against the producer’s side. In short, you can trust those stubs.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-introducing-spring-cloud-contract-purposes"><a class="anchor" href="#getting-started-introducing-spring-cloud-contract-purposes"></a><a class="link" href="#getting-started-introducing-spring-cloud-contract-purposes">2.1.2. Purposes</a></h4>
|
||
<div class="paragraph">
|
||
<p>The main purposes of Spring Cloud Contract are:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>To ensure that HTTP and Messaging stubs (used when developing the client) do exactly
|
||
what the actual server-side implementation does.</p>
|
||
</li>
|
||
<li>
|
||
<p>To promote the ATDD (acceptance test-driven developement) method and the 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="paragraph">
|
||
<p>By default, Spring Cloud Contract integrates with <a href="http://wiremock.org">Wiremock</a> as the HTTP server stub.</p>
|
||
</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’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 two
|
||
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="sect3">
|
||
<h4 id="getting-started-what-is-a-contract"><a class="anchor" href="#getting-started-what-is-a-contract"></a><a class="link" href="#getting-started-what-is-a-contract">2.1.3. What Is a 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. In other words, a contract is
|
||
an agreement on how the API or message communication should look. Consider the following example:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Assume that you want to send a request that contains the ID of a client company and the
|
||
amount it wants to borrow from us. You also want to send it to the <code>/fraudcheck</code> URL via
|
||
the <code>PUT</code> method. The following listing shows a contract to check whether a client should
|
||
be marked as a fraud in both Groovy and YAML:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">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 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 secondary">
|
||
<div class="title">yaml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="getting-started-three-second-tour"><a class="anchor" href="#getting-started-three-second-tour"></a><a class="link" href="#getting-started-three-second-tour">2.2. A Three-second Tour</a></h3>
|
||
<div class="paragraph">
|
||
<p>This very brief tour walks through using Spring Cloud Contract. It consists of the
|
||
following topics:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#getting-started-three-second-tour-producer">On the Producer Side</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#getting-started-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="#getting-started-first-application">here</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the relationship of the parts within Spring Cloud Contract:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/getting-started-three-second.png" alt="getting started three second" width="986" height="704">
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-three-second-tour-producer"><a class="anchor" href="#getting-started-three-second-tour-producer"></a><a class="link" href="#getting-started-three-second-tour-producer">2.2.1. On the Producer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>To start working with Spring Cloud Contract, you can add files with REST or 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 you can add the Spring Cloud Contract Verifier dependency and plugin to your build file, as
|
||
the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</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 information 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.
|
||
You can now merge the changes, and you can publish both the application and the stub artifacts
|
||
in an online repository.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-three-second-tour-consumer"><a class="anchor" href="#getting-started-three-second-tour-consumer"></a><a class="link" href="#getting-started-three-second-tour-consumer">2.2.2. On the Consumer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can use <code>Spring Cloud Contract Stub Runner</code> 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 the
|
||
following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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 the following example shows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner:
|
||
ids: 'com.example:http-server-dsl:+:stubs:8080'
|
||
repositoryRoot: https://repo.spring.io/libs-snapshot</code></pre>
|
||
</div>
|
||
</div>
|
||
</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 the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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="sect2">
|
||
<h3 id="getting-started-first-application"><a class="anchor" href="#getting-started-first-application"></a><a class="link" href="#getting-started-first-application">2.3. Developing Your First Spring Cloud Contract-based Application</a></h3>
|
||
<div class="paragraph">
|
||
<p>This brief tour walks through using Spring Cloud Contract. It consists of the following topics:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#getting-started-first-application-producer">On the Producer Side</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#getting-started-first-application-consumer">On the Consumer Side</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can find an even more brief tour
|
||
<a href="#getting-started-three-second-tour">here</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the sake of this example, the <code>Stub Storage</code> is Nexus/Artifactory.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the relationship of the parts of Spring Cloud Contract:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/getting-started-three-second.png" alt="Getting started first application">
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-first-application-producer"><a class="anchor" href="#getting-started-first-application-producer"></a><a class="link" href="#getting-started-first-application-producer">2.3.1. On the Producer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>To start working with <code>Spring Cloud Contract</code>, you can add Spring Cloud Contract Verifier
|
||
dependency and plugin to your build file, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now you can 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 an HTTP stub contract in both Groovy and YAML:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">yaml</div>
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the case of messaging, you can define:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The input and output messages (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:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yaml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">label: some_label
|
||
input:
|
||
messageFrom: jms:delete
|
||
messageBody:
|
||
bookName: 'foo'
|
||
messageHeaders:
|
||
sample: header
|
||
assertThat: bookWasDeleted()</code></pre>
|
||
</div>
|
||
</div>
|
||
</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 generated tests may differ, depending on which framework and test type you have setup in your plugin.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the next listing, you can find:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The default test mode for HTTP contracts in <code>MockMvc</code></p>
|
||
</li>
|
||
<li>
|
||
<p>A JAX-RS client with the <code>JAXRS</code> test mode</p>
|
||
</li>
|
||
<li>
|
||
<p>A <code>WebTestClient</code>-based test (this is particularly recommended while working with
|
||
Reactive, <code>Web-Flux</code>-based applications) set with the <code>WEBTESTCLIENT</code> test mode</p>
|
||
</li>
|
||
<li>
|
||
<p>A Spock-based test with the <code>testFramework</code> property set to <code>SPOCK</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following listing shows all these samples:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">mockmvc</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">jaxrs</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SuppressWarnings("rawtypes")
|
||
public class FooTest {
|
||
WebTarget webTarget;
|
||
|
||
@Test
|
||
public void validate_() throws Exception {
|
||
|
||
// when:
|
||
Response response = webTarget
|
||
.path("/users")
|
||
.queryParam("limit", "10")
|
||
.queryParam("offset", "20")
|
||
.queryParam("filter", "email")
|
||
.queryParam("sort", "name")
|
||
.queryParam("search", "55")
|
||
.queryParam("age", "99")
|
||
.queryParam("name", "Denis.Stepanov")
|
||
.queryParam("email", "bob@email.com")
|
||
.request()
|
||
.build("GET")
|
||
.invoke();
|
||
String responseAsString = response.readEntity(String.class);
|
||
|
||
// then:
|
||
assertThat(response.getStatus()).isEqualTo(200);
|
||
|
||
// and:
|
||
DocumentContext parsedJson = JsonPath.parse(responseAsString);
|
||
assertThatJson(parsedJson).field("['property1']").isEqualTo("a");
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">webtestclient</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@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");
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">spock</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">given:
|
||
ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
|
||
\'\'\'{"bookName":"foo"}\'\'\',
|
||
['sample': 'header']
|
||
)
|
||
|
||
when:
|
||
contractVerifierMessaging.send(inputMessage, 'jms:delete')
|
||
|
||
then:
|
||
noExceptionThrown()
|
||
bookWasDeleted()</code></pre>
|
||
</div>
|
||
</div>
|
||
</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 information needed 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
|
||
the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-first-application-consumer"><a class="anchor" href="#getting-started-first-application-consumer"></a><a class="link" href="#getting-started-first-application-consumer">2.3.2. On the Consumer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can use Spring Cloud Contract Stub Runner 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>, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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 the following example shows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner:
|
||
ids: 'com.example:http-server-dsl:+:stubs:8080'
|
||
repositoryRoot: https://repo.spring.io/libs-snapshot</code></pre>
|
||
</div>
|
||
</div>
|
||
</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 the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="getting-started-cdc"><a class="anchor" href="#getting-started-cdc"></a><a class="link" href="#getting-started-cdc">2.4. Step-by-step Guide to Consumer Driven Contracts (CDC) with Contracts on the Producer Side</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,
|
||
we mark the client as a fraud.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Technical remarks</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Fraud Detection has an <code>artifact-id</code> of <code>http-server</code></p>
|
||
</li>
|
||
<li>
|
||
<p>Loan Issuance has an artifact-id of <code>http-client</code></p>
|
||
</li>
|
||
<li>
|
||
<p>Both have a <code>group-id</code> of <code>com.example</code></p>
|
||
</li>
|
||
<li>
|
||
<p>For the sake of this example the <code>Stub Storage</code> is Nexus/Artifactory</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Social remarks</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Both the client and the server development teams need to communicate directly and
|
||
discuss changes while going through the process</p>
|
||
</li>
|
||
<li>
|
||
<p>CDC is all about communication</p>
|
||
</li>
|
||
</ul>
|
||
</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 is available 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 of the contracts are
|
||
in the producer’s repository.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-cdc-technical-note"><a class="anchor" href="#getting-started-cdc-technical-note"></a><a class="link" href="#getting-started-cdc-technical-note">2.4.1. Technical Note</a></h4>
|
||
<div class="paragraph">
|
||
<p>If you use the SNAPSHOT, Milestone, or Release Candidate versions you need to add the
|
||
following section to your build:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><repositories>
|
||
<repository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
</repositories>
|
||
<pluginRepositories>
|
||
<pluginRepository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
</pluginRepositories></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>
|
||
<div class="paragraph">
|
||
<p>For simplicity, we use the following acronyms:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Loan Issuance (LI): The HTTP client</p>
|
||
</li>
|
||
<li>
|
||
<p>Fraud Detection (FD): The HTTP server</p>
|
||
</li>
|
||
<li>
|
||
<p>Spring Cloud Contract (SCC)</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-cdc-consumer"><a class="anchor" href="#getting-started-cdc-consumer"></a><a class="link" href="#getting-started-cdc-consumer">2.4.2. The 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 the fraud detection service.</p>
|
||
</li>
|
||
<li>
|
||
<p>Add the Spring Cloud Contract (SCC) 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>We start with the loan issuance flow, which the following UML diagram shows:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/getting-started-cdc-client.png" alt="getting started cdc client" width="1138" height="1223">
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-start"><a class="anchor" href="#getting-started-cdc-consumer-start"></a><a class="link" href="#getting-started-cdc-consumer-start">Start Doing TDD by Writing a Test for Your Feature</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following listing shows a test that we might use to check whether a loan amount is too
|
||
large:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-write"><a class="anchor" href="#getting-started-cdc-consumer-write"></a><a class="link" href="#getting-started-cdc-consumer-write">Write the Missing Implementation</a></h5>
|
||
<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 by using the <code>PUT</code> method.
|
||
To do so, you might use code similar to the following:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
|
||
"http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
|
||
new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);</code></pre>
|
||
</div>
|
||
</div>
|
||
</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="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
If you start the test at this point, it breaks, because no service currently runs on port
|
||
<code>8080</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-clone"><a class="anchor" href="#getting-started-cdc-consumer-clone"></a><a class="link" href="#getting-started-cdc-consumer-clone">Clone the Fraud Detection service repository locally</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can start by playing around with the server side contract. To do so, you must first
|
||
clone it, by running the following command:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-define"><a class="anchor" href="#getting-started-cdc-consumer-define"></a><a class="link" href="#getting-started-cdc-consumer-define">Define the Contract Locally in the Repository of the Fraud Detection Service</a></h5>
|
||
<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 in the <code>src/test/resources/contracts/fraud</code> folder. The <code>fraud</code> folder
|
||
is important because the producer’s test base class name references that folder.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows our contract, in both Groovy and YAML:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">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 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 secondary">
|
||
<div class="title">yaml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
<div class="paragraph">
|
||
<p>The YML contract is quite straightforward. However, when you take a look at the Contract
|
||
written with a statically typed Groovy DSL, you might wonder what the
|
||
<code>value(client(…​), server(…​))</code> parts are. By using this notation, Spring Cloud
|
||
Contract lets you define parts of a JSON block, a URL, or other structure that is 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
|
||
that match those values for the consumer side. You can provide the body by means of either
|
||
a map notation or String with interpolations. 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. See 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>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 of <code>FRAUD</code> and
|
||
the <code>rejectionReason</code> field having a value of <code>Amount too high</code></p>
|
||
</li>
|
||
<li>
|
||
<p>Has 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>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-add"><a class="anchor" href="#getting-started-cdc-consumer-add"></a><a class="link" href="#getting-started-cdc-consumer-add">Add the Spring Cloud Contract Verifier Plugin</a></h5>
|
||
<div class="paragraph">
|
||
<p>We can add either a Maven or a Gradle plugin. In this example, we show how to add Maven.
|
||
First, we add the <code>Spring Cloud Contract</code> BOM, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependencyManagement>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-dependencies</artifactId>
|
||
<version>${spring-cloud-release.version}</version>
|
||
<type>pom</type>
|
||
<scope>import</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
</dependencyManagement></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Next, add the <code>Spring Cloud Contract Verifier</code> Maven plugin, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
|
||
<convertToYaml>true</convertToYaml>
|
||
</configuration>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</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. To do so, run the following commands:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Once you run those commands, you should you see something like the following content in the logs:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following line is extremely important:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-run"><a class="anchor" href="#getting-started-cdc-consumer-run"></a><a class="link" href="#getting-started-cdc-consumer-run">Running the Integration Tests</a></h5>
|
||
<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="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Add the <code>Spring Cloud Contract</code> BOM, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependencyManagement>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-dependencies</artifactId>
|
||
<version>${spring-cloud-release-train.version}</version>
|
||
<type>pom</type>
|
||
<scope>import</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
</dependencyManagement></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Add the dependency to <code>Spring Cloud Contract Stub Runner</code>, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<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 are playing with the collaborators offline, you
|
||
can also provide the offline work switch (<code>StubRunnerProperties.StubsMode.LOCAL</code>).</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now, when you run your tests, you see something like the following output in the logs:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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="paragraph">
|
||
<p>This output means that Stub Runner has found your stubs and started a server for your application
|
||
with a group ID of <code>com.example</code> and an artifact ID of <code>http-server</code> with version <code>0.0.1-SNAPSHOT</code> of
|
||
the stubs and with the <code>stubs</code> classifier on port <code>8080</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-file"><a class="anchor" href="#getting-started-cdc-consumer-file"></a><a class="link" href="#getting-started-cdc-consumer-file">Filing a Pull Request</a></h5>
|
||
<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, you can publish a pull request to
|
||
the server side. Currently, the consumer side work is done.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-cdc-producer"><a class="anchor" href="#getting-started-cdc-producer"></a><a class="link" href="#getting-started-cdc-producer">2.4.3. The 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), you
|
||
might want to do the following</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Take over the pull request</p>
|
||
</li>
|
||
<li>
|
||
<p>Write the missing implementation</p>
|
||
</li>
|
||
<li>
|
||
<p>Deploy the application</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the fraud detection flow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/getting-started-cdc-server.png" alt="getting started cdc server" width="688" height="903">
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-producer-pr"><a class="anchor" href="#getting-started-cdc-producer-pr"></a><a class="link" href="#getting-started-cdc-producer-pr">Taking over the Pull Request</a></h5>
|
||
<div class="paragraph">
|
||
<p>As a reminder, the following listing shows the initial implementation:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then you can run the following commands:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You must add the dependencies needed by the autogenerated tests, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the configuration of the Maven plugin, you must pass the <code>packageWithBaseClasses</code> property, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
|
||
<convertToYaml>true</convertToYaml>
|
||
</configuration>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</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, you should use <a href="https://github.com/rest-assured/rest-assured">Rest Assured MVC</a> to
|
||
start the server side <code>FraudDetectionController</code>. The following listing shows the
|
||
<code>FraudBase</code> class:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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 -> {
|
||
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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now, if you run the <code>./mvnw clean install</code>, you get something like the following output:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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 the following test method:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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="paragraph">
|
||
<p>If you used the Groovy DSL, you can see that all of the <code>producer()</code> parts of the Contract that were present in the
|
||
<code>value(consumer(…​), producer(…​))</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 is also 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>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-producer-impl"><a class="anchor" href="#getting-started-cdc-producer-impl"></a><a class="link" href="#getting-started-cdc-producer-impl">Write the Missing Implementation</a></h5>
|
||
<div class="paragraph">
|
||
<p>Because you know the expected input and expected output, you can write the missing
|
||
implementation as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When you run <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>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-producer-deploy"><a class="anchor" href="#getting-started-cdc-producer-deploy"></a><a class="link" href="#getting-started-cdc-producer-deploy">Deploying Your Application</a></h5>
|
||
<div class="paragraph">
|
||
<p>Once you finish your work, you can deploy your changes. To do so, you must first merge the
|
||
branch by running the following commands:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Your CI might run something a command such as <code>./mvnw clean deploy</code>, which would publish both the
|
||
application and the stub artifacts.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="getting-started-cdc-consumer-final"><a class="anchor" href="#getting-started-cdc-consumer-final"></a><a class="link" href="#getting-started-cdc-consumer-final">2.4.4. 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), I want to:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Merge our feature branch to <code>master</code></p>
|
||
</li>
|
||
<li>
|
||
<p>Switch to online mode of working</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the final state of the process:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/getting-started-cdc-client-final.png" alt="getting started cdc client final" width="590" height="685">
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-final-merge"><a class="anchor" href="#getting-started-cdc-consumer-final-merge"></a><a class="link" href="#getting-started-cdc-consumer-final-merge">Merging a Branch to Master</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following commands show one way to merge a branch into master with Git:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="getting-started-cdc-consumer-final-online"><a class="anchor" href="#getting-started-cdc-consumer-final-online"></a><a class="link" href="#getting-started-cdc-consumer-final-online">Working Online</a></h5>
|
||
<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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">stubrunner:
|
||
ids: 'com.example:http-server-dsl:+:stubs:8080'
|
||
repositoryRoot: https://repo.spring.io/libs-snapshot</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>That’s it. You have finished the tutorial.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="getting-started-whats-next"><a class="anchor" href="#getting-started-whats-next"></a><a class="link" href="#getting-started-whats-next">2.5. Next Steps</a></h3>
|
||
<div class="paragraph">
|
||
<p>Hopefully, this section provided some of the Spring Cloud Contract basics and got you on your way
|
||
to writing your own applications. If you are a task-oriented type of developer, you might
|
||
want to jump over to <a href="https://spring.io" class="bare">spring.io</a> and check out some of the
|
||
<a href="https://spring.io/guides/">getting started</a> guides that solve specific “How do I do that
|
||
with Spring?” problems. We also have Spring Cloud Contract-specific
|
||
“<a href="#howto">how-to</a>” reference documentation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Otherwise, the next logical step is to read <a href="#using">Using Spring Cloud Contract</a>. If
|
||
you are really impatient, you could also jump ahead and read about
|
||
<a href="#project-features">Spring Cloud Contract features</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In addition to that you can check out the following videos:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>"Consumer Driven Contracts and Your Microservice Architecture" by Olga Maciaszek-Sharma and Marcin Grzejszczak</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="videoblock">
|
||
<div class="content">
|
||
<iframe width="640" height="480" src="https://www.youtube.com/embed/pDkC_00hhvA?rel=0" frameborder="0" allowfullscreen></iframe>
|
||
</div>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>"Contract Tests in the Enterprise" by Marcin Grzejszczak</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="videoblock">
|
||
<div class="content">
|
||
<iframe width="640" height="480" src="https://www.youtube.com/embed/ZyHG-VOzPZg?rel=0" frameborder="0" allowfullscreen></iframe>
|
||
</div>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>"Why Contract Tests Matter?" by Marcin Grzejszczak</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="videoblock">
|
||
<div class="content">
|
||
<iframe width="640" height="480" src="https://www.youtube.com/embed/TvpkZu1e2Dc?rel=0&start=6262" frameborder="0" allowfullscreen></iframe>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can find the default project samples at
|
||
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples">samples</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can find the Spring Cloud Contract workshops <a href="https://cloud-samples.spring.io/spring-cloud-contract-samples/">here</a>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="using"><a class="anchor" href="#using"></a><a class="link" href="#using">3. Using Spring Cloud Contract</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>This section goes into more detail about how you should use Spring Cloud Contract. It covers topics
|
||
such as flows of how to work with Spring Cloud Contract. We also
|
||
cover some Spring Cloud Contract best practices.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you are starting out with Spring Cloud Contract, you should probably read the
|
||
<a href="#getting-started">Getting Started</a> guide before diving into this
|
||
section.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-provider-nexus"><a class="anchor" href="#flows-provider-nexus"></a><a class="link" href="#flows-provider-nexus">3.1. Provider Contract Testing with Stubs in Nexus or Artifactory</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can check the <a href="#getting-started-first-application">Developing Your First Spring Cloud Contract based application</a> link to see the provider contract testing with stubs in the Nexus or Artifactory flow.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also check the <a href="https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html">workshop page</a> for a step-by-step instruction on how to do this flow.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-provider-git"><a class="anchor" href="#flows-provider-git"></a><a class="link" href="#flows-provider-git">3.2. Provider Contract Testing with Stubs in Git</a></h3>
|
||
<div class="paragraph">
|
||
<p>In this flow, we perform the provider contract testing (the producer has no knowledge of how consumers use their API). The stubs are uploaded to a separate repository (they are not uploaded to Artifactory or Nexus).</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="prerequisites"><a class="anchor" href="#prerequisites"></a><a class="link" href="#prerequisites">3.2.1. Prerequisites</a></h4>
|
||
<div class="paragraph">
|
||
<p>Before testing provider contracts with stubs in git, you must provide a git repository
|
||
that contains all the stubs for each producer. For an example of such a project, see
|
||
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//contract_git">this samples </a> or <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//contract_git">this sample</a>.
|
||
As a result of pushing stubs there, the repository has the following structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>$ tree .
|
||
└── META-INF
|
||
└── folder.with.group.id.as.its.name
|
||
└── folder-with-artifact-id
|
||
└── folder-with-version
|
||
├── contractA.groovy
|
||
├── contractB.yml
|
||
└── contractC.groovy</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You must also provide consumer code that has Spring Cloud Contract Stub Runner set up. For
|
||
an example of such a project, see <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//consumer">this sample</a> and search for a
|
||
<code>BeerControllerGitTest</code> test. You must also provide producer code that has Spring Cloud
|
||
Contract set up, together with a plugin. For an example of such a project, see
|
||
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//producer_with_empty_git">this sample</a>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-git-flow"><a class="anchor" href="#flows-provider-git-flow"></a><a class="link" href="#flows-provider-git-flow">3.2.2. The Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>The flow looks exactly as the one presented in
|
||
<a href="#getting-started-first-application">Developing Your First Spring Cloud Contract based application</a>,
|
||
but the <code>Stub Storage</code> implementation is a git repository.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can read more about setting up a git repository and setting consumer and producer side
|
||
in the <a href="#how-to-use-git-as-storage">How To page</a> of the documentation.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-git-consumer"><a class="anchor" href="#flows-provider-git-consumer"></a><a class="link" href="#flows-provider-git-consumer">3.2.3. Consumer setup</a></h4>
|
||
<div class="paragraph">
|
||
<p>In order to fetch the stubs from a git repository instead of Nexus or Artifactory, you
|
||
need to use the <code>git</code> protocol in the URL of the <code>repositoryRoot</code> property in Stub Runner.
|
||
The following example shows how to set it up:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Annotation</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
|
||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||
repositoryRoot = "git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git",
|
||
ids = "com.example:artifact-id:0.0.1")</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RegisterExtension
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-git-producer"><a class="anchor" href="#flows-provider-git-producer"></a><a class="link" href="#flows-provider-git-producer">3.2.4. Setting up the Producer</a></h4>
|
||
<div class="paragraph">
|
||
<p>In order to push the stubs to a git repository instead of Nexus or Artifactory, you need
|
||
to use the <code>git</code> protocol in the URL of the plugin setup. Also you need to explicitly tell
|
||
the plugin to push the stubs at the end of the build process. The following example shows
|
||
how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- Base class mappings etc. -->
|
||
|
||
<!-- We want to pick contracts from a Git repository -->
|
||
<contractsRepositoryUrl>git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
|
||
|
||
<!-- We reuse the contract dependency section to set up the path
|
||
to the folder that contains the contract definitions. In our case the
|
||
path will be /groupId/artifactId/version/contracts -->
|
||
<contractDependency>
|
||
<groupId>${project.groupId}</groupId>
|
||
<artifactId>${project.artifactId}</artifactId>
|
||
<version>${project.version}</version>
|
||
</contractDependency>
|
||
|
||
<!-- The contracts mode can't be classpath -->
|
||
<contractsMode>REMOTE</contractsMode>
|
||
</configuration>
|
||
<executions>
|
||
<execution>
|
||
<phase>package</phase>
|
||
<goals>
|
||
<!-- By default we will not push the stubs back to SCM,
|
||
you have to explicitly add it as a goal -->
|
||
<goal>pushStubsToScm</goal>
|
||
</goals>
|
||
</execution>
|
||
</executions>
|
||
</plugin></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 {
|
||
// We want to pick contracts from a Git repository
|
||
contractDependency {
|
||
stringNotation = "${project.group}:${project.name}:${project.version}"
|
||
}
|
||
/*
|
||
We reuse the contract dependency section to set up the path
|
||
to the folder that contains the contract definitions. In our case the
|
||
path will be /groupId/artifactId/version/contracts
|
||
*/
|
||
contractRepository {
|
||
repositoryUrl = "git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git"
|
||
}
|
||
// The mode can't be classpath
|
||
contractsMode = "REMOTE"
|
||
// Base class mappings etc.
|
||
}
|
||
|
||
/*
|
||
In this scenario we want to publish stubs to SCM whenever
|
||
the `publish` task is executed
|
||
*/
|
||
publish.dependsOn("publishStubsToScm")</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can read more about setting up a git repository in the
|
||
<a href="#how-to-use-git-as-storage">How To page</a> of the documentation.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-cdc-contracts-producer"><a class="anchor" href="#flows-cdc-contracts-producer"></a><a class="link" href="#flows-cdc-contracts-producer">3.3. Consumer Driven Contracts with Contracts on the Producer Side</a></h3>
|
||
<div class="paragraph">
|
||
<p>See <a href="#getting-started-cdc">Step-by-step Guide to Consumer Driven
|
||
Contracts (CDC) with Contracts on the Producer Side</a> to see the Consumer Driven Contracts
|
||
with contracts on the producer side flow.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-cdc-contracts-external"><a class="anchor" href="#flows-cdc-contracts-external"></a><a class="link" href="#flows-cdc-contracts-external">3.4. Consumer Driven Contracts with Contracts in an External Repository</a></h3>
|
||
<div class="paragraph">
|
||
<p>In this flow, we perform Consumer Driven Contract testing. The contract definitions are
|
||
stored in a separate repository.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See the <a href="https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/contracts_on_the_producer_side.html">workshop page</a>
|
||
for step-by-step instructions on how to do this flow.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="prerequisites-2"><a class="anchor" href="#prerequisites-2"></a><a class="link" href="#prerequisites-2">3.4.1. Prerequisites</a></h4>
|
||
<div class="paragraph">
|
||
<p>To use consumer-driven contracts with the contracts held in an external repository, you need to set up a git repository that:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Contains all the contract definitions for each producer.</p>
|
||
</li>
|
||
<li>
|
||
<p>Can package the contract definitions in a JAR.</p>
|
||
</li>
|
||
<li>
|
||
<p>For each contract producer, contains a way (for example, <code>pom.xml</code>) to install stubs
|
||
locally through the Spring Cloud Contract Plugin (SCC Plugin)</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For more information, see the <a href="#how-to-common-repo-with-contracts">How To section</a>,
|
||
where we describe how to set up such a repository
|
||
For an example of such a project, see <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//beer_contracts">this sample</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You also need consumer code that has Spring Cloud Contract Stub Runner set up.
|
||
For an example of such a project, see <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//consumer">this sample</a>.
|
||
You also need producer code that has Spring Cloud Contract set up, together with a plugin.
|
||
For an example of such a project, see <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x//producer_with_external_contracts">this sample</a>.
|
||
The stub storage is Nexus or Artifactory</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>At a high level, the flow looks as follows:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>The consumer works with the contract definitions from the separate repository</p>
|
||
</li>
|
||
<li>
|
||
<p>Once the consumer’s work is done, a branch with working code is done on the consumer
|
||
side and a pull request is made to the separate repository that holds the contract definitions.</p>
|
||
</li>
|
||
<li>
|
||
<p>The producer takes over the pull request to the separate repository with contract
|
||
definitions and installs the JAR with all contracts locally.</p>
|
||
</li>
|
||
<li>
|
||
<p>The producer generates tests from the locally stored JAR and writes the missing
|
||
implementation to make the tests pass.</p>
|
||
</li>
|
||
<li>
|
||
<p>Once the producer’s work is done, the pull request to the repository that holds the
|
||
contract definitions is merged.</p>
|
||
</li>
|
||
<li>
|
||
<p>After the CI tool builds the repository with the contract definitions and the JAR with
|
||
contract definitions gets uploaded to Nexus or Artifactory, the producer can merge its branch.</p>
|
||
</li>
|
||
<li>
|
||
<p>Finally, the consumer can switch to working online to fetch stubs of the producer from a
|
||
remote location, and the branch can be merged to master.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-cdc-contracts-external-consumer"><a class="anchor" href="#flows-cdc-contracts-external-consumer"></a><a class="link" href="#flows-cdc-contracts-external-consumer">3.4.2. Consumer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>The consumer:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Writes a test that would send a request to the producer.</p>
|
||
<div class="paragraph">
|
||
<p>The test fails due to no server being present.</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Clones the repository that holds the contract definitions.</p>
|
||
</li>
|
||
<li>
|
||
<p>Set up the requirements as contracts under the folder with the consumer name as a subfolder of the producer.</p>
|
||
<div class="paragraph">
|
||
<p>For example, for a producer named <code>producer</code> and a consumer named <code>consumer</code>, the contracts would be stored under <code>src/main/resources/contracts/producer/consumer/</code>)</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Once the contracts are defined, installs the producer stubs to local storage, as the following example shows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>$ cd src/main/resource/contracts/producer
|
||
$ ./mvnw clean install</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Sets up Spring Cloud Contract (SCC) Stub Runner in the consumer tests, to:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Fetch the producer stubs from local storage.</p>
|
||
</li>
|
||
<li>
|
||
<p>Work in the stubs-per-consumer mode (this enables consumer driven contracts mode).</p>
|
||
<div class="paragraph">
|
||
<p>The SCC Stub Runner:</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Fetches the producer stubs.</p>
|
||
</li>
|
||
<li>
|
||
<p>Runs an in-memory HTTP server stub with the producer stubs.</p>
|
||
</li>
|
||
<li>
|
||
<p>Now your test communicates with the HTTP server stub and your tests pass</p>
|
||
</li>
|
||
<li>
|
||
<p>Create a pull request to the repository with contract definitions, with the new contracts for the producer</p>
|
||
</li>
|
||
<li>
|
||
<p>Branch your consumer code, until the producer team has merged their code</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the consumer flow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/flow-overview-consumer-cdc-external-consumer.png" alt="flow overview consumer cdc external consumer" width="886" height="676">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-cdc-contracts-external-producer"><a class="anchor" href="#flows-cdc-contracts-external-producer"></a><a class="link" href="#flows-cdc-contracts-external-producer">3.4.3. Producer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>The producer:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Takes over the pull request to the repository with contract definitions. You can do it
|
||
from the command line, as follows</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>$ git checkout -b the_branch_with_pull_request master
|
||
git pull https://github.com/user_id/project_name.git the_branch_with_pull_request</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Installs the contract definitions, as follows</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>$ ./mvnw clean install</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Sets up the plugin to fetch the contract definitions from a JAR instead of from
|
||
<code>src/test/resources/contracts</code>, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- We want to use the JAR with contracts with the following coordinates -->
|
||
<contractDependency>
|
||
<groupId>com.example</groupId>
|
||
<artifactId>beer-contracts</artifactId>
|
||
</contractDependency>
|
||
<!-- The JAR with contracts should be taken from Maven local -->
|
||
<contractsMode>LOCAL</contractsMode>
|
||
<!-- ... additional configuration -->
|
||
</configuration>
|
||
</plugin></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 {
|
||
// We want to use the JAR with contracts with the following coordinates
|
||
// group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
|
||
contractDependency {
|
||
stringNotation = 'com.example:beer-contracts:+:'
|
||
}
|
||
// The JAR with contracts should be taken from Maven local
|
||
contractsMode = "LOCAL"
|
||
// Additional configuration
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Runs the build to generate tests and stubs, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">./mvnw clean install</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">./gradlew clean build</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Writes the missing implementation, to make the tests pass.</p>
|
||
</li>
|
||
<li>
|
||
<p>Merges the pull request to the repository with contract definitions, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>$ git commit -am "Finished the implementation to make the contract tests pass"
|
||
$ git checkout master
|
||
$ git merge --no-ff the_branch_with_pull_request
|
||
$ git push origin master</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>The CI system builds the project with the contract definitions and uploads the JAR with
|
||
the contract definitions to Nexus or Artifactory.</p>
|
||
</li>
|
||
<li>
|
||
<p>Switches to working remotely.</p>
|
||
</li>
|
||
<li>
|
||
<p>Sets up the plugin so that the contract definitions are no longer taken from the local
|
||
storage but from a remote location, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- We want to use the JAR with contracts with the following coordinates -->
|
||
<contractDependency>
|
||
<groupId>com.example</groupId>
|
||
<artifactId>beer-contracts</artifactId>
|
||
</contractDependency>
|
||
<!-- The JAR with contracts should be taken from a remote location -->
|
||
<contractsMode>REMOTE</contractsMode>
|
||
<!-- ... additional configuration -->
|
||
</configuration>
|
||
</plugin></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 {
|
||
// We want to use the JAR with contracts with the following coordinates
|
||
// group id `com.example`, artifact id `beer-contracts`, LATEST version and NO classifier
|
||
contractDependency {
|
||
stringNotation = 'com.example:beer-contracts:+:'
|
||
}
|
||
// The JAR with contracts should be taken from a remote location
|
||
contractsMode = "REMOTE"
|
||
// Additional configuration
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Merges the producer code with the new implementation.</p>
|
||
</li>
|
||
<li>
|
||
<p>The CI system:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Builds the project</p>
|
||
</li>
|
||
<li>
|
||
<p>Generates tests, stubs, and the stub JAR</p>
|
||
</li>
|
||
<li>
|
||
<p>Uploads the artifact with the application and the stubs to Nexus or Artifactory.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the producer process:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/flow-overview-consumer-cdc-external-producer.png" alt="flow overview consumer cdc external producer" width="1213" height="1341">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-cdc-contracts-stubs-git"><a class="anchor" href="#flows-cdc-contracts-stubs-git"></a><a class="link" href="#flows-cdc-contracts-stubs-git">3.5. Consumer Driven Contracts with Contracts on the Producer Side, Pushed to Git</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can check <a href="#getting-started-cdc">Step-by-step Guide to Consumer Driven Contracts (CDC) with contracts laying on the producer side</a> to see the consumer driven contracts with contracts on the producer side flow.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The stub storage implementation is a git repository. We describe its setup in the
|
||
<a href="#flows-provider-git">Provider Contract Testing with Stubs in Git</a> section.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can read more about setting up a git repository for the consumer and producer sides in
|
||
the <a href="#how-to-use-git-as-storage">How To page</a> of the documentation.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-provider-non-spring"><a class="anchor" href="#flows-provider-non-spring"></a><a class="link" href="#flows-provider-non-spring">3.6. Provider Contract Testing with Stubs in Artifactory for a non-Spring Application</a></h3>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-non-spring-flow"><a class="anchor" href="#flows-provider-non-spring-flow"></a><a class="link" href="#flows-provider-non-spring-flow">3.6.1. The Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can check <a href="#getting-started-first-application">Developing Your First Spring Cloud Contract based application</a> to see the flow for provider contract testing with stubs in Nexus or Artifactory.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-non-spring-consumer"><a class="anchor" href="#flows-provider-non-spring-consumer"></a><a class="link" href="#flows-provider-non-spring-consumer">3.6.2. Setting up the Consumer</a></h4>
|
||
<div class="paragraph">
|
||
<p>For the consumer side, you can use a JUnit rule. That way, you need not start a Spring context. The follwoing listing shows such a rule (in JUnit4 and JUnit 5);</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example","artifact-id", "0.0.1")
|
||
.repoRoot("git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-non-spring-producer"><a class="anchor" href="#flows-provider-non-spring-producer"></a><a class="link" href="#flows-provider-non-spring-producer">3.6.3. Setting up the Producer</a></h4>
|
||
<div class="paragraph">
|
||
<p>By default, the Spring Cloud Contract Plugin uses Rest Assured’s <code>MockMvc</code> setup for the
|
||
generated tests. Since non-Spring applications do not use <code>MockMvc</code>, you can change the
|
||
<code>testMode</code> to <code>EXPLICIT</code> to send a real request to an application bound at a specific port.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In this example, we use a framework called <a href="https://javalin.io">Javalin</a> to start a
|
||
non-Spring HTTP server.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Assume that we have the following application:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package com.example.demo;
|
||
|
||
import io.javalin.Javalin;
|
||
|
||
public class DemoApplication {
|
||
|
||
public static void main(String[] args) {
|
||
new DemoApplication().run(7000);
|
||
}
|
||
|
||
public Javalin start(int port) {
|
||
return Javalin.create().start(port);
|
||
}
|
||
|
||
public Javalin registerGet(Javalin app) {
|
||
return app.get("/", ctx -> ctx.result("Hello World"));
|
||
}
|
||
|
||
public Javalin run(int port) {
|
||
return registerGet(start(port));
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Given that application, we can set up the plugin to use the <code>EXPLICIT</code> mode (that is, to
|
||
send out requests to a real port), as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<baseClassForTests>com.example.demo.BaseClass</baseClassForTests>
|
||
<!-- This will setup the EXPLICIT mode for the tests -->
|
||
<testMode>EXPLICIT</testMode>
|
||
</configuration>
|
||
</plugin></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 {
|
||
// This will setup the EXPLICIT mode for the tests
|
||
testMode = "EXPLICIT"
|
||
baseClassForTests = "com.example.demo.BaseClass"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The base class might resemble the following:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">import io.javalin.Javalin;
|
||
import io.restassured.RestAssured;
|
||
import org.junit.After;
|
||
import org.junit.Before;
|
||
import org.springframework.util.SocketUtils;
|
||
|
||
public class BaseClass {
|
||
|
||
Javalin app;
|
||
|
||
@Before
|
||
public void setup() {
|
||
// pick a random port
|
||
int port = SocketUtils.findAvailableTcpPort();
|
||
// start the application at a random port
|
||
this.app = start(port);
|
||
// tell Rest Assured where the started application is
|
||
RestAssured.baseURI = "http://localhost:" + port;
|
||
}
|
||
|
||
@After
|
||
public void close() {
|
||
// stop the server after each test
|
||
this.app.stop();
|
||
}
|
||
|
||
private Javalin start(int port) {
|
||
// reuse the production logic to start a server
|
||
return new DemoApplication().run(port);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With such a setup:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>We have setup the Spring Cloud Contract plugin to use the <code>EXPLICIT</code> mode to send real
|
||
requests instead of mocked ones.</p>
|
||
</li>
|
||
<li>
|
||
<p>We have defined a base class that:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Starts the HTTP server on a random port for each test.</p>
|
||
</li>
|
||
<li>
|
||
<p>Sets Rest Assured to send requests to that port.</p>
|
||
</li>
|
||
<li>
|
||
<p>Closes the HTTP server after each test.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-provider-non-jvm"><a class="anchor" href="#flows-provider-non-jvm"></a><a class="link" href="#flows-provider-non-jvm">3.7. Provider Contract Testing with Stubs in Artifactory in a non-JVM World</a></h3>
|
||
<div class="paragraph">
|
||
<p>In this flow, we assume that:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The API Producer and API Consumer are non-JVM applications.</p>
|
||
</li>
|
||
<li>
|
||
<p>The contract definitions are written in YAML.</p>
|
||
</li>
|
||
<li>
|
||
<p>The Stub Storage is Artifactory or Nexus.</p>
|
||
</li>
|
||
<li>
|
||
<p>Spring Cloud Contract Docker (SCC Docker) and Spring Cloud Contract Stub Runner Docker
|
||
(SCC Stub Runner Docker) images are used.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can read more about how to use Spring Cloud Contract with Docker
|
||
<a href="#docker-project.adoc">in this page</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><a href="https://spring.io/blog/2018/02/13/spring-cloud-contract-in-a-polyglot-world">Here</a>, you can
|
||
read a blog post about how to use Spring Cloud Contract in a polyglot world.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><a href="https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs/">Here</a>, you can find
|
||
a sample of a NodeJS application that uses Spring Cloud Contract both as a producer and a
|
||
consumer.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-non-jvm-producer"><a class="anchor" href="#flows-provider-non-jvm-producer"></a><a class="link" href="#flows-provider-non-jvm-producer">3.7.1. Producer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>At a high level, the producer:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Writes contract definitions (for example, in YAML).</p>
|
||
</li>
|
||
<li>
|
||
<p>Sets up the build tool to:</p>
|
||
<div class="olist loweralpha">
|
||
<ol class="loweralpha" type="a">
|
||
<li>
|
||
<p>Start the application with mocked services on a given port.</p>
|
||
<div class="paragraph">
|
||
<p>If mocking is not possible, you can setup the infrastructure and define tests in a stateful way.</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Run the Spring Cloud Contract Docker image and pass the port of a running application as an environment variable.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The SCC Docker image:
|
||
* Generates the tests from the attached volume.
|
||
* Runs the tests against the running application.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Upon test completion, stubs get uploaded to a stub storage site (such as Artifactory or Git).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the producer flow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/flows-provider-non-jvm-producer.png" alt="flows provider non jvm producer" width="930" height="810">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-non-jvm-consumer"><a class="anchor" href="#flows-provider-non-jvm-consumer"></a><a class="link" href="#flows-provider-non-jvm-consumer">3.7.2. Consumer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>At a high level, the consumer:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Sets up the build tool to:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Start the Spring Cloud Contract Stub Runner Docker image and start the stubs.</p>
|
||
<div class="paragraph">
|
||
<p>The environment variables configure:</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>The stubs to fetch.</p>
|
||
</li>
|
||
<li>
|
||
<p>The location of the repositories.</p>
|
||
<div class="paragraph">
|
||
<p>Note that:</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>To use the local storage, you can also attach it as a volume.</p>
|
||
</li>
|
||
<li>
|
||
<p>The ports at which the stubs are running need to be exposed.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Run the application tests against the running stubs.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the consumer flow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/flows-provider-non-jvm-consumer.png" alt="flows provider non jvm consumer" width="815" height="618">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="flows-provider-rest-docs"><a class="anchor" href="#flows-provider-rest-docs"></a><a class="link" href="#flows-provider-rest-docs">3.8. Provider Contract Testing with REST Docs and Stubs in Nexus or Artifactory</a></h3>
|
||
<div class="paragraph">
|
||
<p>In this flow, we do not use a Spring Cloud Contract plugin to generate tests and stubs. We write <a href="https://spring.io/projects/spring-restdocs">Spring RESTDocs</a> and, from them, we automatically generate stubs. Finally, we set up our builds to package the stubs and upload them to the stub storage site — in our case, Nexus or Artifactory.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See the <a href="https://cloud-samples.spring.io/spring-cloud-contract-samples/tutorials/rest_docs.html">workshop page</a> for a step-by-step instruction on how to use this flow.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-rest-docs-producer"><a class="anchor" href="#flows-provider-rest-docs-producer"></a><a class="link" href="#flows-provider-rest-docs-producer">3.8.1. Producer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>As a producer, we:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>We write RESTDocs tests of our API.</p>
|
||
</li>
|
||
<li>
|
||
<p>We add Spring Cloud Contract Stub Runner starter to our build (<code>spring-cloud-starter-contract-stub-runner</code>), as follows</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||
<scope>test</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
|
||
<dependencyManagement>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-dependencies</artifactId>
|
||
<version>${spring-cloud.version}</version>
|
||
<type>pom</type>
|
||
<scope>import</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
</dependencyManagement></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">dependencies {
|
||
testImplementation 'org.springframework.cloud:spring-cloud-starter-contract-stub-runner'
|
||
}
|
||
|
||
dependencyManagement {
|
||
imports {
|
||
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>We set up the build tool to package our stubs, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><!-- pom.xml -->
|
||
<plugins>
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-assembly-plugin</artifactId>
|
||
<executions>
|
||
<execution>
|
||
<id>stub</id>
|
||
<phase>prepare-package</phase>
|
||
<goals>
|
||
<goal>single</goal>
|
||
</goals>
|
||
<inherited>false</inherited>
|
||
<configuration>
|
||
<attach>true</attach>
|
||
<descriptors>
|
||
${basedir}/src/assembly/stub.xml
|
||
</descriptors>
|
||
</configuration>
|
||
</execution>
|
||
</executions>
|
||
</plugin>
|
||
</plugins>
|
||
|
||
<!-- src/assembly/stub.xml -->
|
||
<assembly
|
||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
|
||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
|
||
<id>stubs</id>
|
||
<formats>
|
||
<format>jar</format>
|
||
</formats>
|
||
<includeBaseDirectory>false</includeBaseDirectory>
|
||
<fileSets>
|
||
<fileSet>
|
||
<directory>${project.build.directory}/generated-snippets/stubs</directory>
|
||
<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
|
||
<includes>
|
||
<include>**/*</include>
|
||
</includes>
|
||
</fileSet>
|
||
</fileSets>
|
||
</assembly></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">task stubsJar(type: Jar) {
|
||
classifier = "stubs"
|
||
into("META-INF/${project.group}/${project.name}/${project.version}/mappings") {
|
||
include('**/*.*')
|
||
from("${project.buildDir}/generated-snippets/stubs")
|
||
}
|
||
}
|
||
// we need the tests to pass to build the stub jar
|
||
stubsJar.dependsOn(test)
|
||
bootJar.dependsOn(stubsJar)</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now, when we run the tests, stubs are automatically published and packaged.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following UML diagram shows the producer flow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/flows-provider-rest-docs-producer.png" alt="flows provider rest docs producer" width="783" height="677">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="flows-provider-rest-docs-consumer"><a class="anchor" href="#flows-provider-rest-docs-consumer"></a><a class="link" href="#flows-provider-rest-docs-consumer">3.8.2. Consumer Flow</a></h4>
|
||
<div class="paragraph">
|
||
<p>Since the consumer flow is not affected by the tool used to generate the stubs, you can check <a href="#getting-started-first-application-consumer">Developing Your First Spring Cloud Contract based application</a> to see the flow for consumer side of the provider contract testing with stubs in Nexus or Artifactory.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="using-whats-next"><a class="anchor" href="#using-whats-next"></a><a class="link" href="#using-whats-next">3.9. What to Read Next</a></h3>
|
||
<div class="paragraph">
|
||
<p>You should now understand how you can use Spring Cloud Contract and some best practices that you
|
||
should follow. You can now go on to learn about specific
|
||
<a href="#project-features">Spring Cloud Contract features</a>, or you could
|
||
skip ahead and read about the <a href="advanced.html">advanced features of Spring Cloud Contract</a>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="features"><a class="anchor" href="#features"></a><a class="link" href="#features">4. Spring Cloud Contract Features</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>This section dives into the details of Spring Cloud Contract. Here you can learn about the key
|
||
features that you may want to use and customize. If you have not already done so, you
|
||
might want to read the "<a href="#getting-started">Getting Started</a>" and
|
||
"<a href="#using">Using Spring Cloud Contract</a>" sections, so that you have a good grounding of the
|
||
basics.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="contract-dsl"><a class="anchor" href="#contract-dsl"></a><a class="link" href="#contract-dsl">4.1. Contract DSL</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract supports the DSLs written in the following languages:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Groovy</p>
|
||
</li>
|
||
<li>
|
||
<p>YAML</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">
|
||
If you are not familiar with Groovy, do not worry - you can use Java syntax in the
|
||
Groovy DSL files as well.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</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 { …​ }</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 { …​ }</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 example shows a contract definition:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 'PUT'
|
||
url '/api/12'
|
||
headers {
|
||
header 'Content-Type': 'application/vnd.org.springframework.cloud.contract.verifier.twitter-places-analyzer.v1+json'
|
||
}
|
||
body '''\
|
||
[{
|
||
"created_at": "Sat Jul 26 09:38:57 +0000 2014",
|
||
"id": 492967299297845248,
|
||
"id_str": "492967299297845248",
|
||
"text": "Gonna see you at Warsaw",
|
||
"place":
|
||
{
|
||
"attributes":{},
|
||
"bounding_box":
|
||
{
|
||
"coordinates":
|
||
[[
|
||
[-77.119759,38.791645],
|
||
[-76.909393,38.791645],
|
||
[-76.909393,38.995548],
|
||
[-77.119759,38.995548]
|
||
]],
|
||
"type":"Polygon"
|
||
},
|
||
"country":"United States",
|
||
"country_code":"US",
|
||
"full_name":"Washington, DC",
|
||
"id":"01fbe706f872cb32",
|
||
"name":"Washington",
|
||
"place_type":"city",
|
||
"url": "https://api.twitter.com/1/geo/id/01fbe706f872cb32.json"
|
||
}
|
||
}]
|
||
'''
|
||
}
|
||
response {
|
||
status OK()
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">yml</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>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
<div class="paragraph">
|
||
<p>You can compile contracts to stubs mapping by using the following standalone Maven command:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert</pre>
|
||
</div>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-limitations"><a class="anchor" href="#contract-limitations"></a><a class="link" href="#contract-limitations">4.1.1. Limitations</a></h4>
|
||
<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, 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 set 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(…​), producer(…​))</code> notation in <code>GString</code>. That
|
||
is why you should use the Groovy Map notation.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-common-top-elements"><a class="anchor" href="#contract-common-top-elements"></a><a class="link" href="#contract-common-top-elements">4.1.2. Common Top-Level Elements</a></h4>
|
||
<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-in-progress">Contracts in Progress</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#contract-dsl-passing-values-from-files">Passing Values from Files</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-description"><a class="anchor" href="#contract-dsl-description"></a><a class="link" href="#contract-dsl-description">Description</a></h5>
|
||
<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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-name"><a class="anchor" href="#contract-dsl-name"></a><a class="link" href="#contract-dsl-name">Name</a></h5>
|
||
<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="paragraph">
|
||
<p>The following example shows how to add a name to a contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">name: some name</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-ignoring-contracts"><a class="anchor" href="#contract-dsl-ignoring-contracts"></a><a class="link" href="#contract-dsl-ignoring-contracts">Ignoring Contracts</a></h5>
|
||
<div class="paragraph">
|
||
<p>If you want to ignore a contract, you can either set a value for ignored contracts in the
|
||
plugin configuration or set the <code>ignored</code> property on the contract itself. The following
|
||
example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">ignored: true</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-in-progress"><a class="anchor" href="#contract-dsl-in-progress"></a><a class="link" href="#contract-dsl-in-progress">Contracts in Progress</a></h5>
|
||
<div class="paragraph">
|
||
<p>A contract in progress will not generate tests on the producer side, but will allow generation of stubs.</p>
|
||
</div>
|
||
<div class="admonitionblock important">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-important" title="Important"></i>
|
||
</td>
|
||
<td class="content">
|
||
Use this feature with caution as it may lead to false positives. You generate stubs for your consumers to use without actually having the implementation in place!
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you want to set a contract in progress the following
|
||
example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
|
||
inProgress()
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">inProgress: true</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-passing-values-from-files"><a class="anchor" href="#contract-dsl-passing-values-from-files"></a><a class="link" href="#contract-dsl-passing-values-from-files">Passing Values from Files</a></h5>
|
||
<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 your 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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">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.
|
||
*/
|
||
|
||
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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">request:
|
||
method: GET
|
||
url: /foo
|
||
bodyFromFile: request.json
|
||
response:
|
||
status: 200
|
||
bodyFromFile: response.json</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Further assume that the JSON files is as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">request.json</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"status": "REQUEST"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">response.json</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">{
|
||
"status": "RESPONSE"
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When test or stub generation takes place, the contents of the <code>request.json</code> and <code>response.json</code> files are 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 binary form,
|
||
you can use the <code>fileAsBytes</code> method in Groovy DSL or a <code>bodyFromFileAsBytes</code> field in YAML.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to pass the contents of binary files:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</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>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="features-http"><a class="anchor" href="#features-http"></a><a class="link" href="#features-http">4.2. Contracts for HTTP</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract lets you verify applications that use REST or HTTP as a
|
||
means of communication. Spring Cloud Contract verifies that, for a request that matches the
|
||
criteria from the <code>request</code> part of the contract, the server provides a response that is in
|
||
keeping with the <code>response</code> part of the contract. Subsequently, the contracts are used to
|
||
generate WireMock stubs that, for any request matching the provided criteria, provide a
|
||
suitable response.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-dsl-http-top-level-elements"><a class="anchor" href="#contract-dsl-http-top-level-elements"></a><a class="link" href="#contract-dsl-http-top-level-elements">4.2.1. HTTP Top-Level Elements</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can call the following methods in the top-level closure of a contract definition:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>request</code>: Mandatory</p>
|
||
</li>
|
||
<li>
|
||
<p><code>response</code> : Mandatory</p>
|
||
</li>
|
||
<li>
|
||
<p><code>priority</code>: Optional</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to define an HTTP request contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</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 higher priority,
|
||
you need to pass a lower number to the <code>priority</code> tag or method. For example, a <code>priority</code> with
|
||
a value of <code>5</code> has higher priority than a <code>priority</code> with a value of <code>10</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-dsl-request"><a class="anchor" href="#contract-dsl-request"></a><a class="link" href="#contract-dsl-request">4.2.2. HTTP Request</a></h4>
|
||
<div class="paragraph">
|
||
<p>The HTTP protocol requires only the method and the URL to be specified in a request. The
|
||
same information is mandatory in request definition of the contract.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a contract for a request:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">method: PUT
|
||
url: /foo</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can specify an absolute rather than a relative <code>url</code>, but using <code>urlPath</code> is
|
||
the recommended way, as doing so makes the tests be host-independent.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example uses <code>url</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">request:
|
||
method: PUT
|
||
urlPath: /foo</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>request</code> may contain query parameters, as the following example (which uses <code>urlPath</code>) shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">request:
|
||
...
|
||
queryParameters:
|
||
a: b
|
||
b: c</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>request</code> can contain additional request headers, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>request</code> may contain additional request cookies, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>request</code> may contain a request body, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>request</code> can contain multipart elements. To include multipart elements, use the
|
||
<code>multipart</code> method/section, as the following examples show:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
|
||
request {
|
||
method 'PUT'
|
||
url '/multipart'
|
||
headers {
|
||
contentType('multipart/form-data;boundary=AaB03x')
|
||
}
|
||
multipart(
|
||
// key (parameter name), value (parameter value) pair
|
||
formParameter: $(c(regex('".+"')), p('"formParameterValue"')),
|
||
someBooleanParameter: $(c(regex(anyBoolean())), p('true')),
|
||
// a named parameter (e.g. with `file` name) that represents file with
|
||
// `name` and `content`. You can also call `named("fileName", "fileContent")`
|
||
file: named(
|
||
// name of the file
|
||
name: $(c(regex(nonEmpty())), p('filename.csv')),
|
||
// content of the file
|
||
content: $(c(regex(nonEmpty())), p('file content')),
|
||
// content type for the part
|
||
contentType: $(c(regex(nonEmpty())), p('application/json')))
|
||
)
|
||
}
|
||
response {
|
||
status OK()
|
||
}
|
||
}
|
||
org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
|
||
request {
|
||
method "PUT"
|
||
url "/multipart"
|
||
headers {
|
||
contentType('multipart/form-data;boundary=AaB03x')
|
||
}
|
||
multipart(
|
||
file: named(
|
||
name: value(stub(regex('.+')), test('file')),
|
||
content: value(stub(regex('.+')), test([100, 117, 100, 97] as byte[]))
|
||
)
|
||
)
|
||
}
|
||
response {
|
||
status 200
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</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(…​), producer(…​))</code>).</p>
|
||
</li>
|
||
<li>
|
||
<p>By using the <code>named(…​)</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 by using a method with two arguments,
|
||
such as <code>named("fileName", "fileContent")</code>, or by using 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 in the <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 in the <code>multipart.named</code> section. That section contains
|
||
the <code>paramName</code> (the name of the parameter), <code>fileName</code> (the name of the file),
|
||
<code>fileContent</code> (the 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, which 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 with <code>paramName</code>. Then you can pass the
|
||
parametrization of either <code>fileName</code> or <code>fileContent</code> in a
|
||
<code>regex</code> or in a <code>predefined</code> regular expression.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>From the contract in the preceding example, the generated test and stubs look as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Test</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">Stub</div>
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-dsl-response"><a class="anchor" href="#contract-dsl-response"></a><a class="link" href="#contract-dsl-response">4.2.3. HTTP Response</a></h4>
|
||
<div class="paragraph">
|
||
<p>The response must contain an HTTP status code and may contain other information. The
|
||
following code shows an example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">response:
|
||
...
|
||
status: 200</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Besides status, the response may contain headers, cookies, and a body, which are
|
||
specified the same way as in the request (see <a href="#contract-dsl-request">HTTP Request</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 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. For example, 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="sect3">
|
||
<h4 id="contract-dsl-dynamic-properties"><a class="anchor" href="#contract-dsl-dynamic-properties"></a><a class="link" href="#contract-dsl-dynamic-properties">4.2.4. Dynamic properties</a></h4>
|
||
<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 the 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 by using <code>testMatchers</code> and <code>stubMatchers</code>.
|
||
See 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 use only the <code>matchers</code> section.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-dynamic-properties-in-body"><a class="anchor" href="#contract-dsl-dynamic-properties-in-body"></a><a class="link" href="#contract-dsl-dynamic-properties-in-body">Dynamic Properties inside the Body</a></h5>
|
||
<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 the Groovy DSL. Check out the
|
||
<a href="#contract-dsl-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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">value</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">$</div>
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Both approaches work equally well. The <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="sect4">
|
||
<h5 id="contract-dsl-regex"><a class="anchor" href="#contract-dsl-regex"></a><a class="link" href="#contract-dsl-regex">Regular Expressions</a></h5>
|
||
<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-dsl-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 the 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 tests 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"><code>Pattern.matches()</code></a>
|
||
is called. For instance, <code>abc</code> does not match <code>aabc</code>, but <code>.abc</code> does.
|
||
There are several additional <a href="#contract-dsl-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 the following example shows:</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 -> '^' + 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 follows:</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 automatically
|
||
assume that you want a regular expression to be passed.
|
||
All of those methods start with the <code>any</code> prefix, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">T anyAlphaUnicode();
|
||
|
||
T anyAlphaNumeric();
|
||
|
||
T anyNumber();
|
||
|
||
T anyInteger();
|
||
|
||
T anyPositiveInt();
|
||
|
||
T anyDouble();
|
||
|
||
T anyHex();
|
||
|
||
T aBoolean();
|
||
|
||
T anyIpAddress();
|
||
|
||
T anyHostname();
|
||
|
||
T anyEmail();
|
||
|
||
T anyUrl();
|
||
|
||
T anyHttpsUrl();
|
||
|
||
T anyUuid();
|
||
|
||
T anyDate();
|
||
|
||
T anyDateTime();
|
||
|
||
T anyTime();
|
||
|
||
T anyIso8601WithOffset();
|
||
|
||
T anyNonBlankString();
|
||
|
||
T anyNonEmptyString();
|
||
|
||
T anyOf(String... values);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows 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="sect5">
|
||
<h6 id="contract-dsl-regex-limitations"><a class="anchor" href="#contract-dsl-regex-limitations"></a><a class="link" href="#contract-dsl-regex-limitations">Limitations</a></h6>
|
||
<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 the <code>Xeger</code> library that generates a string out of
|
||
a regex, do not use the <code>$</code> and <code>^</code> signs in your regex if you rely on automatic
|
||
generation. See <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 a <code>LocalDate</code> instance as a value for <code>$</code> (for example, <code>$(consumer(LocalDate.now()))</code>).
|
||
It causes a <code>java.lang.StackOverflowError</code>. Use <code>$(consumer(LocalDate.now().toString()))</code> instead.
|
||
See <a href="https://github.com/spring-cloud/spring-cloud-contract/issues/900">Issue 900</a>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-optional-params"><a class="anchor" href="#contract-dsl-optional-params"></a><a class="link" href="#contract-dsl-optional-params">Passing Optional Parameters</a></h5>
|
||
<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-dsl-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 provide optional parameters in your contract. However, you can provide
|
||
optional parameters only for the following:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The STUB side of the Request</p>
|
||
</li>
|
||
<li>
|
||
<p>The TEST 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, 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="sect4">
|
||
<h5 id="contract-dsl-custom-methods"><a class="anchor" href="#contract-dsl-custom-methods"></a><a class="link" href="#contract-dsl-custom-methods">Executing Custom Methods on the Server Side</a></h5>
|
||
<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-dsl-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 runs on the server side during the test. Such a
|
||
method can be added to the class defined as <code>baseClassForTests</code> 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">method GET()</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 <code>String</code> 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>, and other numeric type 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="sect4">
|
||
<h5 id="contract-dsl-referencing-request-from-response"><a class="anchor" href="#contract-dsl-referencing-request-from-response"></a><a class="link" href="#contract-dsl-referencing-request-from-response">Referencing the Request from the Response</a></h5>
|
||
<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 write contracts in the 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 use 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. In that case, you can use the following options:</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.
|
||
For example, for a key of <code>thing</code>, the first entry is <code>{{{ request.query.thing.[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. For example,
|
||
the first entry is <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. For example, for a JSON path of <code>$.here</code>, use <code>{{{ jsonpath this '$.here' }}}</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Contract contractDsl = Contract.make {
|
||
request {
|
||
method 'GET'
|
||
url('/api/v1/xxxx') {
|
||
queryParameters {
|
||
parameter('foo', 'bar')
|
||
parameter('foo', 'bar2')
|
||
}
|
||
}
|
||
headers {
|
||
header(authorization(), 'secret')
|
||
header(authorization(), 'secret2')
|
||
}
|
||
body(foo: 'bar', baz: 5)
|
||
}
|
||
response {
|
||
status OK()
|
||
headers {
|
||
header(authorization(), "foo ${fromRequest().header(authorization())} bar")
|
||
}
|
||
body(
|
||
url: fromRequest().url(),
|
||
path: fromRequest().path(),
|
||
pathIndex: fromRequest().path(1),
|
||
param: fromRequest().query('foo'),
|
||
paramIndex: fromRequest().query('foo', 1),
|
||
authorization: fromRequest().header('Authorization'),
|
||
authorization2: fromRequest().header('Authorization', 1),
|
||
fullBody: fromRequest().body(),
|
||
responseFoo: fromRequest().body('$.foo'),
|
||
responseBaz: fromRequest().body('$.baz'),
|
||
responseBaz2: "Bla bla ${fromRequest().body('$.foo')} bla bla",
|
||
rawUrl: fromRequest().rawUrl(),
|
||
rawPath: fromRequest().rawPath(),
|
||
rawPathIndex: fromRequest().rawPath(1),
|
||
rawParam: fromRequest().rawQuery('foo'),
|
||
rawParamIndex: fromRequest().rawQuery('foo', 1),
|
||
rawAuthorization: fromRequest().rawHeader('Authorization'),
|
||
rawAuthorization2: fromRequest().rawHeader('Authorization', 1),
|
||
rawResponseFoo: fromRequest().rawBody('$.foo'),
|
||
rawResponseBaz: fromRequest().rawBody('$.baz'),
|
||
rawResponseBaz2: "Bla bla ${fromRequest().rawBody('$.foo')} bla bla"
|
||
)
|
||
}
|
||
}
|
||
Contract contractDsl = Contract.make {
|
||
request {
|
||
method 'GET'
|
||
url('/api/v1/xxxx') {
|
||
queryParameters {
|
||
parameter('foo', 'bar')
|
||
parameter('foo', 'bar2')
|
||
}
|
||
}
|
||
headers {
|
||
header(authorization(), 'secret')
|
||
header(authorization(), 'secret2')
|
||
}
|
||
body(foo: "bar", baz: 5)
|
||
}
|
||
response {
|
||
status OK()
|
||
headers {
|
||
contentType(applicationJson())
|
||
}
|
||
body('''
|
||
{
|
||
"responseFoo": "{{{ jsonPath request.body '$.foo' }}}",
|
||
"responseBaz": {{{ jsonPath request.body '$.baz' }}},
|
||
"responseBaz2": "Bla bla {{{ jsonPath request.body '$.foo' }}} bla bla"
|
||
}
|
||
'''.toString())
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</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&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&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 versions greater than or equal
|
||
to 2.5.1. The Spring Cloud Contract Verifier uses WireMock’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="sect4">
|
||
<h5 id="contract-dsl-matchers"><a class="anchor" href="#contract-dsl-matchers"></a><a class="link" href="#contract-dsl-matchers">Dynamic Properties in the Matchers Sections</a></h5>
|
||
<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="sect5">
|
||
<h6 id="groovy-dsl"><a class="anchor" href="#groovy-dsl"></a><a class="link" href="#groovy-dsl">Groovy DSL</a></h6>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>For the stubs (in tests on the consumer’s side):</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>byEquality()</code>: The value taken from the consumer’s request in the provided JSON path must be
|
||
equal to the value provided in the contract.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>byRegex(…​)</code>: The value taken from the consumer’s request in the provided JSON path must
|
||
match the regex. You can also pass the type of the expected matched value (for example, <code>asString()</code>, <code>asLong()</code>, and so on).</p>
|
||
</li>
|
||
<li>
|
||
<p><code>byDate()</code>: The value taken from the consumer’s request in 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’s request in 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’s request in 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’s side):</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>byEquality()</code>: The value taken from the producer’s response in the provided JSON path must be
|
||
equal to the provided value in the contract.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>byRegex(…​)</code>: The value taken from the producer’s response in the provided JSON path must
|
||
match the regex.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>byDate()</code>: The value taken from the producer’s response in 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’s response in 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’s response in 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’s response in 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(…​)</code> <code>testMatcher</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>byCommand(…​)</code>: The value taken from the producer’s response in the provided JSON path is
|
||
passed as an input to the custom method that you provide. For example,
|
||
<code>byCommand('thing($it)')</code> results in calling a <code>thing</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 another 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 in the provided JSON path must be null.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="yaml"><a class="anchor" href="#yaml"></a><a class="link" href="#yaml">YAML</a></h6>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
See the Groovy section for detailed explanation of
|
||
what the types mean.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For YAML, the structure of a matcher resembles the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">- path: $.thing1
|
||
type: by_regex
|
||
value: thing2
|
||
regexType: as_string</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Alternatively, 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>, you can use something similar to the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">- path: $.thing1
|
||
type: by_regex
|
||
predefined: only_alpha_unicode</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following list shows the allowed list of <code>type</code> values:</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>Two additional fields (<code>minOccurrence</code> and <code>maxOccurrence</code>) are accepted.</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>Two additional fields (<code>minOccurrence</code> and <code>maxOccurrence</code>) are accepted.</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 in the <code>regexType</code>
|
||
field. The following list shows the allowed regular expression types:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>as_integer</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_double</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_float</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_long</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_short</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_boolean</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>as_string</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 & 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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">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>
|
||
</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 checks 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 minimum and maximum occurrence.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The resulting test resembles 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() >= 1)]"
|
||
}, {
|
||
"matchesJsonPath" : "$[?(@.valueWithMax.size() <= 3)]"
|
||
}, {
|
||
"matchesJsonPath" : "$[?(@.valueWithMinMax.size() >= 1 && @.valueWithMinMax.size() <= 3)]"
|
||
}, {
|
||
"matchesJsonPath" : "$[?(@.valueWithOccurrence.size() >= 4 && @.valueWithOccurrence.size() <= 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>, 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(…​)</code> method.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-dsl-async"><a class="anchor" href="#contract-dsl-async"></a><a class="link" href="#contract-dsl-async">4.2.5. Asynchronous Support</a></h4>
|
||
<div class="paragraph">
|
||
<p>If you use 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="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">response:
|
||
async: true</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also use the <code>fixedDelayMilliseconds</code> method or property to add delay to your stubs.
|
||
The following example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-dsl-xml"><a class="anchor" href="#contract-dsl-xml"></a><a class="link" href="#contract-dsl-xml">4.2.6. XML Support for HTTP</a></h4>
|
||
<div class="paragraph">
|
||
<p>For HTTP contracts, we also support using XML in the 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 the request and the response. In place of the <code>jsonPath(…​)</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>The following example shows a Groovy DSL contract with XML in the response body:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</div>
|
||
<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 """
|
||
<test>
|
||
<duck type='xtype'>123</duck>
|
||
<alpha>abc</alpha>
|
||
<list>
|
||
<elem>abc</elem>
|
||
<elem>def</elem>
|
||
<elem>ghi</elem>
|
||
</list>
|
||
<number>123</number>
|
||
<aBoolean>true</aBoolean>
|
||
<date>2017-01-01</date>
|
||
<dateTime>2017-01-01T01:23:45</dateTime>
|
||
<time>01:02:34</time>
|
||
<valueWithoutAMatcher>foo</valueWithoutAMatcher>
|
||
<key><complex>foo</complex></key>
|
||
</test>"""
|
||
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="listingblock secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">include::/home/marcin/repo/spring-cloud-contract/spring-cloud-contract-verifier/src/test/resources/yml/contract_rest_xml.yml</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows an automatically generated test for XML in the 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="sect3">
|
||
<h4 id="contract-dsl-multiple"><a class="anchor" href="#contract-dsl-multiple"></a><a class="link" href="#contract-dsl-multiple">4.2.7. Multiple Contracts in One File</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can define multiple contracts in one file. Such a contract might resemble the
|
||
following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">---
|
||
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>
|
||
</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 the following:</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>. The one that does not have the <code>name</code> field 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 are shown in the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>should post a user.json
|
||
1_WithList.json</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>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">
|
||
It is much better to name your contracts, because doing so makes
|
||
your tests far more meaningful.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="contract-stateful-contracts"><a class="anchor" href="#contract-stateful-contracts"></a><a class="link" href="#contract-stateful-contracts">4.2.8. Stateful Contracts</a></h4>
|
||
<div class="paragraph">
|
||
<p>Stateful contracts (known also as scenarios) are contract definitions that should be read
|
||
in order. This might be useful in the following situations:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>You want to execute the contract in a precisely defined order, since you use Spring
|
||
Cloud Contract to test your stateful application</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">
|
||
We really discourage you from doing that, since contract tests should be stateless.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>You want the same endpoint to return different results for the same request.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To create stateful contracts (or scenarios), you need to
|
||
use the proper naming convention while creating your contracts. The convention
|
||
requires including an order number followed by an underscore. This works regardless
|
||
of whether you work with YAML or Groovy. The following listing shows an example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Such a tree causes Spring Cloud Contract Verifier to generate WireMock’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…​</p>
|
||
</li>
|
||
<li>
|
||
<p>showCart, marked as <code>Step1</code> pointing to…​</p>
|
||
</li>
|
||
<li>
|
||
<p>logout, marked as <code>Step2</code> (which closes the scenario).</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can find nore details about WireMock scenarios 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 also generates tests with a guaranteed order of execution.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="feature-integrations"><a class="anchor" href="#feature-integrations"></a><a class="link" href="#feature-integrations">4.3. Integrations</a></h3>
|
||
<div class="sect3">
|
||
<h4 id="features-jax-rs"><a class="anchor" href="#features-jax-rs"></a><a class="link" href="#features-jax-rs">4.3.1. JAX-RS</a></h4>
|
||
<div class="paragraph">
|
||
<p>The Spring Cloud Contract 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 be 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="sect3">
|
||
<h4 id="feature-webflux"><a class="anchor" href="#feature-webflux"></a><a class="link" href="#feature-webflux">4.3.2. WebFlux with WebTestClient</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can work with WebFlux by using WebTestClient. The following listing shows how to
|
||
configure WebTestClient as the test mode:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<testMode>WEBTESTCLIENT</testMode>
|
||
</configuration>
|
||
</plugin></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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to set up a WebTestClient base class and RestAssured
|
||
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 -> personToCheck.age >= 20));
|
||
}
|
||
}
|
||
}</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 <code>WebTestClient</code> mode is faster than the <code>EXPLICIT</code> mode.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="feature-webflux-explicit"><a class="anchor" href="#feature-webflux-explicit"></a><a class="link" href="#feature-webflux-explicit">4.3.3. WebFlux with Explicit Mode</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can also use WebFlux with the explicit mode in your generated tests
|
||
to work with WebFlux. The following example shows how to configure using explicit mode:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<testMode>EXPLICIT</testMode>
|
||
</configuration>
|
||
</plugin></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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to set up a base class and RestAssured 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 -> personToCheck.age >= 20;
|
||
}
|
||
|
||
@Bean
|
||
ProducerController producerController() {
|
||
return new ProducerController(personCheckingService());
|
||
}
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-context-paths"><a class="anchor" href="#features-context-paths"></a><a class="link" href="#features-context-paths">4.3.4. Working with Context Paths</a></h4>
|
||
<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">
|
||
<div class="paragraph">
|
||
<p>The only change needed to fully support context paths is the switch on the
|
||
producer side. Also, the autogenerated tests must use explicit mode. The consumer
|
||
side remains untouched. In order for the generated test to pass, you must use explicit
|
||
mode. The following example shows how to set the test mode to <code>EXPLICIT</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<testMode>EXPLICIT</testMode>
|
||
</configuration>
|
||
</plugin></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>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>That way, you generate a test that does not use MockMvc. It means that you generate
|
||
real requests and you need to set up your generated test’s base class to work on a real
|
||
socket.</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 RestAssured:</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="sect3">
|
||
<h4 id="features-rest-docs"><a class="anchor" href="#features-rest-docs"></a><a class="link" href="#features-rest-docs">4.3.5. Working with REST Docs</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can use <a href="https://projects.spring.io/spring-restdocs">Spring REST Docs</a> to generate
|
||
documentation (for example, in Asciidoc format) for an HTTP API with Spring MockMvc,
|
||
<code>WebTestClient</code>, or RestAssured. At the same time that you generate documentation for your API, you can also
|
||
generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your
|
||
normal REST Docs test cases and use <code>@AutoConfigureRestDocs</code> to have stubs be
|
||
automatically generated in the REST Docs output directory.</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/rest-docs.png" alt="rest docs" width="1237" height="835">
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example uses <code>MockMvc</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
|
||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||
@AutoConfigureMockMvc
|
||
public class ApplicationTests {
|
||
|
||
@Autowired
|
||
private MockMvc mockMvc;
|
||
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
mockMvc.perform(get("/resource"))
|
||
.andExpect(content().string("Hello World"))
|
||
.andDo(document("resource"));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This test generates a WireMock stub at <code>target/snippets/stubs/resource.json</code>. It matches
|
||
all <code>GET</code> requests to the <code>/resource</code> path. The same example with <code>WebTestClient</code> (used
|
||
for testing Spring WebFlux applications) would be as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
|
||
@SpringBootTest
|
||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||
@AutoConfigureWebTestClient
|
||
public class ApplicationTests {
|
||
|
||
@Autowired
|
||
private WebTestClient client;
|
||
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
client.get().uri("/resource").exchange()
|
||
.expectBody(String.class).isEqualTo("Hello World")
|
||
.consumeWith(document("resource"));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Without any additional configuration, these tests create a stub with a request matcher
|
||
for the HTTP method and all headers except <code>host</code> and <code>content-length</code>. To match the
|
||
request more precisely (for example, to match the body of a POST or PUT), we need to
|
||
explicitly create a request matcher. Doing so has two effects:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Creating a stub that matches only in the way you specify.</p>
|
||
</li>
|
||
<li>
|
||
<p>Asserting that the request in the test case also matches the same conditions.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The main entry point for this feature is <code>WireMockRestDocs.verify()</code>, which can be used
|
||
as a substitute for the <code>document()</code> convenience method, as the following
|
||
example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">import static org.springframework.cloud.contract.wiremock.restdocs.WireMockRestDocs.verify;
|
||
|
||
@RunWith(SpringRunner.class)
|
||
@SpringBootTest
|
||
@AutoConfigureRestDocs(outputDir = "target/snippets")
|
||
@AutoConfigureMockMvc
|
||
public class ApplicationTests {
|
||
|
||
@Autowired
|
||
private MockMvc mockMvc;
|
||
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
mockMvc.perform(post("/resource")
|
||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||
.andExpect(status().isOk())
|
||
.andDo(verify().jsonPath("$.id")
|
||
.stub("resource"));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding contract specifies that any valid POST with an <code>id</code> field receives the response
|
||
defined in this test. You can chain together calls to <code>.jsonPath()</code> to add additional
|
||
matchers. If JSON Path is unfamiliar, the <a href="https://github.com/jayway/JsonPath">JayWay
|
||
documentation</a> can help you get up to speed. The <code>WebTestClient</code> version of this test
|
||
has a similar <code>verify()</code> static helper that you insert in the same place.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Instead of the <code>jsonPath</code> and <code>contentType</code> convenience methods, you can also use the
|
||
WireMock APIs to verify that the request matches the created stub, as the
|
||
following example shows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
|
||
public void contextLoads() throws Exception {
|
||
mockMvc.perform(post("/resource")
|
||
.content("{\"id\":\"123456\",\"message\":\"Hello World\"}"))
|
||
.andExpect(status().isOk())
|
||
.andDo(verify()
|
||
.wiremock(WireMock.post(
|
||
urlPathEquals("/resource"))
|
||
.withRequestBody(matchingJsonPath("$.id"))
|
||
.stub("post-resource"));
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The WireMock API is rich. You can match headers, query parameters, and the request body by
|
||
regex as well as by JSON path. You can use these features to create stubs with a wider
|
||
range of parameters. The preceding example generates a stub resembling the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="title">post-resource.json</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"request" : {
|
||
"url" : "/resource",
|
||
"method" : "POST",
|
||
"bodyPatterns" : [ {
|
||
"matchesJsonPath" : "$.id"
|
||
}]
|
||
},
|
||
"response" : {
|
||
"status" : 200,
|
||
"body" : "Hello World",
|
||
"headers" : {
|
||
"X-Application-Context" : "application:-1",
|
||
"Content-Type" : "text/plain"
|
||
}
|
||
}
|
||
}</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">
|
||
You can use either the <code>wiremock()</code> method or the <code>jsonPath()</code> and <code>contentType()</code>
|
||
methods to create request matchers, but you cannot use both approaches.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>On the consumer side, you can make the <code>resource.json</code> generated earlier in this section
|
||
available on the classpath (by
|
||
<a href="#features-stub-runner-publishing-stubs-as-jars">Publishing Stubs as JARs</a>, for example). After that, you can create a stub that uses WireMock in a
|
||
number of different ways, including by using
|
||
<code>@AutoConfigureWireMock(stubs="classpath:resource.json")</code>, as described earlier in this
|
||
document.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-rest-docs-contracts"><a class="anchor" href="#features-rest-docs-contracts"></a><a class="link" href="#features-rest-docs-contracts">Generating Contracts with REST Docs</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can also generate Spring Cloud Contract DSL files and documentation with Spring REST
|
||
Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts
|
||
and the stubs.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Why would you want to use this feature? Some people in the community asked questions
|
||
about a situation in which they would like to move to DSL-based contract definition,
|
||
but they already have a lot of Spring MVC tests. Using this feature lets you generate
|
||
the contract files that you can later modify and move to folders (defined in your
|
||
configuration) so that the plugin finds them.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
You might wonder why this functionality is in the WireMock module. The functionality
|
||
is there because it makes sense to generate both the contracts and the stubs.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following test:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> this.mockMvc
|
||
.perform(post("/foo").accept(MediaType.APPLICATION_PDF)
|
||
.accept(MediaType.APPLICATION_JSON)
|
||
.contentType(MediaType.APPLICATION_JSON)
|
||
.content("{\"foo\": 23, \"bar\" : \"baz\" }"))
|
||
.andExpect(status().isOk()).andExpect(content().string("bar"))
|
||
// first WireMock
|
||
.andDo(WireMockRestDocs.verify().jsonPath("$[?(@.foo >= 20)]")
|
||
.jsonPath("$[?(@.bar in ['baz','bazz','bazzz'])]")
|
||
.contentType(MediaType.valueOf("application/json"))
|
||
.stub("shouldGrantABeerIfOldEnough"))
|
||
// then Contract DSL documentation
|
||
.andDo(document("index", SpringCloudContractRestDocs.dslContract()));</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding test creates the stub presented in the previous section, generating both
|
||
the contract and a documentation file.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The contract is called <code>index.groovy</code> and might resemble the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<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 {
|
||
method 'POST'
|
||
url '/foo'
|
||
body('''
|
||
{"foo": 23 }
|
||
''')
|
||
headers {
|
||
header('''Accept''', '''application/json''')
|
||
header('''Content-Type''', '''application/json''')
|
||
}
|
||
}
|
||
response {
|
||
status OK()
|
||
body('''
|
||
bar
|
||
''')
|
||
headers {
|
||
header('''Content-Type''', '''application/json;charset=UTF-8''')
|
||
header('''Content-Length''', '''3''')
|
||
}
|
||
testMatchers {
|
||
jsonPath('$[?(@.foo >= 20)]', byType())
|
||
}
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The generated document (formatted in Asciidoc in this case) contains a formatted
|
||
contract. The location of this file would be <code>index/dsl-contract.adoc</code>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="features-messaging"><a class="anchor" href="#features-messaging"></a><a class="link" href="#features-messaging">4.4. Messaging</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract 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="sect3">
|
||
<h4 id="contract-dsl-messaging-top-level"><a class="anchor" href="#contract-dsl-messaging-top-level"></a><a class="link" href="#contract-dsl-messaging-top-level">4.4.1. Messaging DSL Top-Level Elements</a></h4>
|
||
<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-messaging-common">Common</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-output-triggered-method"><a class="anchor" href="#contract-dsl-output-triggered-method"></a><a class="link" href="#contract-dsl-output-triggered-method">Output Triggered by a Method</a></h5>
|
||
<div class="paragraph">
|
||
<p>The output message can be triggered by calling a method (such as a <code>Scheduler</code> when a contract was
|
||
started and a message was sent), as shown in the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"># 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>
|
||
</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 publisher’s side, we generate a
|
||
test that calls that method to trigger the message. On the consumer side, you can use
|
||
the <code>some_label</code> to trigger the message.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-output-triggered-message"><a class="anchor" href="#contract-dsl-output-triggered-message"></a><a class="link" href="#contract-dsl-output-triggered-message">Output Triggered by a Message</a></h5>
|
||
<div class="paragraph">
|
||
<p>The output message can be triggered by receiving a message, as shown in the following
|
||
example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy"># 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>
|
||
</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 publisher’s side, the engine
|
||
generates a test that sends the input message to the defined destination. On the
|
||
consumer side, you can either send a message to the input destination or use a label
|
||
(<code>some_label</code> in the example) to trigger the message.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="contract-dsl-consumer-producer"><a class="anchor" href="#contract-dsl-consumer-producer"></a><a class="link" href="#contract-dsl-consumer-producer">Consumer/Producer</a></h5>
|
||
<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="sect4">
|
||
<h5 id="contract-dsl-messaging-common"><a class="anchor" href="#contract-dsl-messaging-common"></a><a class="link" href="#contract-dsl-messaging-common">Common</a></h5>
|
||
<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> (for example, <code>assertThatMessageIsOnTheQueue()</code>) that you have defined in the
|
||
base class or in a static import. Spring Cloud Contract runs that method
|
||
in the generated test.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-integrations"><a class="anchor" href="#features-messaging-integrations"></a><a class="link" href="#features-messaging-integrations">4.4.2. Integrations</a></h4>
|
||
<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, the messaging part of Spring Cloud Contract 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">
|
||
<div class="paragraph">
|
||
<p>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 follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream-test-support</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></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>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-manual"><a class="anchor" href="#features-messaging-manual"></a><a class="link" href="#features-messaging-manual">Manual Integration Testing</a></h5>
|
||
<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.
|
||
The following example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-test-generation"><a class="anchor" href="#features-messaging-test-generation"></a><a class="link" href="#features-messaging-test-generation">4.4.3. Producer Side Messaging Test Generation</a></h4>
|
||
<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’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 three 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, a 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 Stream and Integration, 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 Camel, that’s a certain component (for example,
|
||
<code>jms</code>).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-scenario1"><a class="anchor" href="#features-messaging-scenario1"></a><a class="link" href="#features-messaging-scenario1">Scenario 1: No Input Message</a></h5>
|
||
<div class="paragraph">
|
||
<p>Consider the following contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the preceding example, the following test would be created:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">JUnit</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> '''\
|
||
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="listingblock secondary">
|
||
<div class="title">Spock</div>
|
||
<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>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-scenario2"><a class="anchor" href="#features-messaging-scenario2"></a><a class="link" href="#features-messaging-scenario2">Scenario 2: Output Triggered by Input</a></h5>
|
||
<div class="paragraph">
|
||
<p>Consider the following contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the preceding contract, the following test would be created:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">JUnit</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> '''\
|
||
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="listingblock secondary">
|
||
<div class="title">Spock</div>
|
||
<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>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-scenario3"><a class="anchor" href="#features-messaging-scenario3"></a><a class="link" href="#features-messaging-scenario3">Scenario 3: No Output Message</a></h5>
|
||
<div class="paragraph">
|
||
<p>Consider the following contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">groovy</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 secondary">
|
||
<div class="title">yml</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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the preceding contract, the following test would be created:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">JUnit</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> """\
|
||
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="listingblock secondary">
|
||
<div class="title">Spock</div>
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-consumer"><a class="anchor" href="#features-messaging-consumer"></a><a class="link" href="#features-messaging-consumer">4.4.4. Consumer Stub Generation</a></h4>
|
||
<div class="paragraph">
|
||
<p>Unlike in the HTTP part, in messaging, we need to publish the contract definition inside the JAR with
|
||
a stub. Then it is parsed on the consumer side, and proper stubbed routes are created.</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 needs to
|
||
define which one should be used. Assume that you have AMQP, Spring Cloud Stream, and Spring Integration
|
||
on the classpath and that you want to use Spring AMQP. 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="sect4">
|
||
<h5 id="features-messaging-stub-triggering"><a class="anchor" href="#features-messaging-stub-triggering"></a><a class="link" href="#features-messaging-stub-triggering">Stub triggering</a></h5>
|
||
<div class="paragraph">
|
||
<p>To trigger a message, use the <code>StubTrigger</code> interface, as the following example shows:</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<String, Collection<String>> 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="#features-messaging-trigger-label">Trigger by Label</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-trigger-group-artifact-ids">Trigger by Group and Artifact Ids</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-trigger-artifact-ids">Trigger by Artifact IDs</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-trigger-all-messages">Trigger All Messages</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-trigger-label"><a class="anchor" href="#features-messaging-trigger-label"></a><a class="link" href="#features-messaging-trigger-label">Trigger by Label</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to trigger a message with a label:</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>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-trigger-group-artifact-ids"><a class="anchor" href="#features-messaging-trigger-group-artifact-ids"></a><a class="link" href="#features-messaging-trigger-group-artifact-ids">Trigger by Group and Artifact Ids</a></h5>
|
||
<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="sect4">
|
||
<h5 id="features-messaging-trigger-artifact-ids"><a class="anchor" href="#features-messaging-trigger-artifact-ids"></a><a class="link" href="#features-messaging-trigger-artifact-ids">Trigger by Artifact IDs</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to trigger a message from artifact IDs:</p>
|
||
</div>
|
||
<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="sect4">
|
||
<h5 id="features-messaging-trigger-all-messages"><a class="anchor" href="#features-messaging-trigger-all-messages"></a><a class="link" href="#features-messaging-trigger-all-messages">Trigger All Messages</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to trigger all messages:</p>
|
||
</div>
|
||
<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="sect3">
|
||
<h4 id="features-messaging-stub-runner-camel"><a class="anchor" href="#features-messaging-stub-runner-camel"></a><a class="link" href="#features-messaging-stub-runner-camel">4.4.5. Consumer Side Messaging With Apache Camel</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel.
|
||
For the provided artifacts, it automatically downloads the stubs and registers the required
|
||
routes.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-camel-adding"><a class="anchor" href="#features-messaging-stub-runner-camel-adding"></a><a class="link" href="#features-messaging-stub-runner-camel-adding">Adding Apache Camel to the Project</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can have both Apache Camel and Spring Cloud Contract Stub Runner on the classpath.
|
||
Remember to annotate your test class with <code>@AutoConfigureStubRunner</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-camel-disabling"><a class="anchor" href="#features-messaging-stub-runner-camel-disabling"></a><a class="link" href="#features-messaging-stub-runner-camel-disabling">Disabling the Functionality</a></h5>
|
||
<div class="paragraph">
|
||
<p>If you need to disable this functionality, set the <code>stubrunner.camel.enabled=false</code> property.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-camel-example"><a class="anchor" href="#features-messaging-stub-runner-camel-example"></a><a class="link" href="#features-messaging-stub-runner-camel-example">Examples</a></h5>
|
||
<div class="paragraph">
|
||
<p>Assume that we have the following Maven repository with deployed stubs for the
|
||
<code>camelService</code> application.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Further assume that the stubs contain the following structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider the following contracts (we number them 1 and 2):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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="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>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-camel-scenario1"><a class="anchor" href="#features-messaging-stub-runner-camel-scenario1"></a><a class="link" href="#features-messaging-stub-runner-camel-scenario1">Scenario 1 (No Input Message)</a></h6>
|
||
<div class="paragraph">
|
||
<p>To trigger a message from the <code>return_book_1</code> label, we use the <code>StubTigger</code> interface, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
<div class="paragraph">
|
||
<p>Next, we want to listen to the output of the message sent to <code>jms:output</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message would then pass the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-camel-scenario2"><a class="anchor" href="#features-messaging-stub-runner-camel-scenario2"></a><a class="link" href="#features-messaging-stub-runner-camel-scenario2">Scenario 2 (Output Triggered by Input)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>jms:output</code> destination.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Next, we want to listen to the output of the message sent to <code>jms:output</code>, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message would pass the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-camel-scenario3"><a class="anchor" href="#features-messaging-stub-runner-camel-scenario3"></a><a class="link" href="#features-messaging-stub-runner-camel-scenario3">Scenario 3 (Input with No Output)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>jms:output</code> destination, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-stub-runner-integration"><a class="anchor" href="#features-messaging-stub-runner-integration"></a><a class="link" href="#features-messaging-stub-runner-integration">4.4.6. Consumer Side Messaging with Spring Integration</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract Stub Runner’s messaging module gives you an easy way to
|
||
integrate with Spring Integration. For the provided artifacts, it automatically downloads
|
||
the stubs and registers the required routes.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-integration-adding"><a class="anchor" href="#features-messaging-stub-runner-integration-adding"></a><a class="link" href="#features-messaging-stub-runner-integration-adding">Adding the Runner to the Project</a></h5>
|
||
<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="sect4">
|
||
<h5 id="features-messaging-stub-runner-integration-disabling"><a class="anchor" href="#features-messaging-stub-runner-integration-disabling"></a><a class="link" href="#features-messaging-stub-runner-integration-disabling">Disabling the Functionality</a></h5>
|
||
<div class="paragraph">
|
||
<p>If you need to disable this functionality, set the
|
||
<code>stubrunner.integration.enabled=false</code> property.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-integration-example"><a class="anchor" href="#features-messaging-stub-runner-integration-example"></a><a class="link" href="#features-messaging-stub-runner-integration-example">Examples</a></h5>
|
||
<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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Further assume the stubs contain the following structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following contracts (numbered 1 and 2):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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="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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider the following Spring Integration Route:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><?xml version="1.0" encoding="UTF-8"?>
|
||
<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">
|
||
|
||
|
||
<!-- REQUIRED FOR TESTING -->
|
||
<bridge input-channel="output"
|
||
output-channel="outputTest"/>
|
||
|
||
<channel id="outputTest">
|
||
<queue/>
|
||
</channel>
|
||
|
||
</beans:beans></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>These examples lend themselves to three scenarios:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-integration-scenario1">Scenario 1 (No Input Message)</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-integration-scenario2">Scenario 2 (Output Triggered by Input)</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-integration-scenario3">Scenario 3 (Input with No Output)</a></p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-integration-scenario1"><a class="anchor" href="#features-messaging-stub-runner-integration-scenario1"></a><a class="link" href="#features-messaging-stub-runner-integration-scenario1">Scenario 1 (No Input Message)</a></h6>
|
||
<div class="paragraph">
|
||
<p>To trigger a message from the <code>return_book_1</code> label, use the <code>StubTigger</code> interface, as
|
||
follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
<div class="paragraph">
|
||
<p>The following listing shows how to listen to the output of the message sent to <code>jms:output</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message<?> receivedMessage = messaging.receive('outputTest')</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message would pass the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-integration-scenario2"><a class="anchor" href="#features-messaging-stub-runner-integration-scenario2"></a><a class="link" href="#features-messaging-stub-runner-integration-scenario2">Scenario 2 (Output Triggered by Input)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>jms:output</code>
|
||
destination, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following listing shows how to listen to the output of the message sent to <code>jms:output</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message<?> receivedMessage = messaging.receive('outputTest')</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message passes the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-integration-scenario3"><a class="anchor" href="#features-messaging-stub-runner-integration-scenario3"></a><a class="link" href="#features-messaging-stub-runner-integration-scenario3">Scenario 3 (Input with No Output)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>jms:input</code> destination, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-stub-runner-stream"><a class="anchor" href="#features-messaging-stub-runner-stream"></a><a class="link" href="#features-messaging-stub-runner-stream">4.4.7. Consumer Side Messaging With Spring Cloud Stream</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract Stub Runner’s messaging module gives you an easy way to
|
||
integrate with Spring Stream. For the provided artifacts, it automatically downloads the
|
||
stubs and registers the required routes.</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’s integration with the Stream <code>messageFrom</code> or <code>sentTo</code> strings
|
||
are resolved first as the <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">
|
||
<div class="paragraph">
|
||
<p>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 follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream-test-support</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></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>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-stream-adding"><a class="anchor" href="#features-messaging-stub-runner-stream-adding"></a><a class="link" href="#features-messaging-stub-runner-stream-adding">Adding the Runner to the Project</a></h5>
|
||
<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="sect4">
|
||
<h5 id="features-messaging-stub-runner-stream-disabling"><a class="anchor" href="#features-messaging-stub-runner-stream-disabling"></a><a class="link" href="#features-messaging-stub-runner-stream-disabling">Disabling the Functionality</a></h5>
|
||
<div class="paragraph">
|
||
<p>If you need to disable this functionality, set the <code>stubrunner.stream.enabled=false</code>
|
||
property.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-stream-example"><a class="anchor" href="#features-messaging-stub-runner-stream-example"></a><a class="link" href="#features-messaging-stub-runner-stream-example">Examples</a></h5>
|
||
<div class="paragraph">
|
||
<p>Assume that you have the following Maven repository with deployed stubs for the
|
||
<code>streamService</code> application:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Further assume the stubs contain the following structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following contracts (numbered 1 and 2):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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="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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider the following Spring configuration:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>These examples lend themselves to three scenarios:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-stream-scenario1">Scenario 1 (No Input Message)</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-stream-scenario2">Scenario 2 (Output Triggered by Input)</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-messaging-stub-runner-stream-scenario3">Scenario 3 (Input with No Output)</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-stream-scenario1"><a class="anchor" href="#features-messaging-stub-runner-stream-scenario1"></a><a class="link" href="#features-messaging-stub-runner-stream-scenario1">Scenario 1 (No Input Message)</a></h6>
|
||
<div class="paragraph">
|
||
<p>To trigger a message from the <code>return_book_1</code> label, use the <code>StubTrigger</code> interface as
|
||
follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to listen to the output of the message sent to a channel whose <code>destination</code> is
|
||
<code>returnBook</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message<?> receivedMessage = messaging.receive('returnBook')</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message passes the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-stream-scenario2"><a class="anchor" href="#features-messaging-stub-runner-stream-scenario2"></a><a class="link" href="#features-messaging-stub-runner-stream-scenario2">Scenario 2 (Output Triggered by Input)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>bookStorage</code>
|
||
<code>destination</code>, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to listen to the output of the message sent to <code>returnBook</code>:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">Message<?> receivedMessage = messaging.receive('returnBook')</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The received message passes the following assertions:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-stream-scenario3"><a class="anchor" href="#features-messaging-stub-runner-stream-scenario3"></a><a class="link" href="#features-messaging-stub-runner-stream-scenario3">Scenario 3 (Input with No Output)</a></h6>
|
||
<div class="paragraph">
|
||
<p>Since the route is set for you, you can send a message to the <code>jms:output</code>
|
||
destination, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-messaging-stub-runner-amqp"><a class="anchor" href="#features-messaging-stub-runner-amqp"></a><a class="link" href="#features-messaging-stub-runner-amqp">4.4.8. Consumer Side Messaging With Spring AMQP</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract Stub Runner’s messaging module provides an easy way to
|
||
integrate with Spring AMQP’s Rabbit Template. For the provided artifacts, it
|
||
automatically downloads the stubs and registers the required routes.</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
|
||
matches 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, you can pass them by using the <code>amqp_receivedRoutingKey</code>
|
||
messaging header.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-amqp-adding"><a class="anchor" href="#features-messaging-stub-runner-amqp-adding"></a><a class="link" href="#features-messaging-stub-runner-amqp-adding">Adding the Runner to the Project</a></h5>
|
||
<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>
|
||
<div class="sect4">
|
||
<h5 id="features-messaging-stub-runner-amqp-example"><a class="anchor" href="#features-messaging-stub-runner-amqp-example"></a><a class="link" href="#features-messaging-stub-runner-amqp-example">Examples</a></h5>
|
||
<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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Further assume that the stubs contain the following structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then consider the following contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider the following Spring configuration:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-messaging-stub-runner-amqp-triggering"><a class="anchor" href="#features-messaging-stub-runner-amqp-triggering"></a><a class="link" href="#features-messaging-stub-runner-amqp-triggering">Triggering the Message</a></h6>
|
||
<div class="paragraph">
|
||
<p>To trigger a message using the contract in the preceding section, use the <code>StubTrigger</code> interface as
|
||
follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The binding definition binds the queue called <code>test.queue</code>. As a result, the following listener
|
||
definition is matched and invoked with the contract message:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Also, the following annotated listener matches and is invoked:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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="sect5">
|
||
<h6 id="features-messaging-stub-runner-amqp-configuration"><a class="anchor" href="#features-messaging-stub-runner-amqp-configuration"></a><a class="link" href="#features-messaging-stub-runner-amqp-configuration">Spring AMQP Test Configuration</a></h6>
|
||
<div class="paragraph">
|
||
<p>In order to avoid Spring AMQP trying to connect to a running broker during our tests, we
|
||
configure a mock <code>ConnectionFactory</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To disable the mocked <code>ConnectionFactory</code>, set the following property:
|
||
<code>stubrunner.amqp.mockConnection=false</code>, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
<div class="sect2">
|
||
<h3 id="features-stub-runner"><a class="anchor" href="#features-stub-runner"></a><a class="link" href="#features-stub-runner">4.5. Spring Cloud Contract Stub Runner</a></h3>
|
||
<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="sect3">
|
||
<h4 id="features-stub-runner-snapshot-versions"><a class="anchor" href="#features-stub-runner-snapshot-versions"></a><a class="link" href="#features-stub-runner-snapshot-versions">4.5.1. Snapshot Versions</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can add the additional snapshot repository to your <code>build.gradle</code> file to use snapshot
|
||
versions, which are automatically uploaded after every successful build, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><repositories>
|
||
<repository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
</repositories>
|
||
<pluginRepositories>
|
||
<pluginRepository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
</pluginRepositories></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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-publishing-stubs-as-jars"><a class="anchor" href="#features-stub-runner-publishing-stubs-as-jars"></a><a class="link" href="#features-stub-runner-publishing-stubs-as-jars">4.5.2. Publishing Stubs as JARs</a></h4>
|
||
<div class="paragraph">
|
||
<p>The easiest approach to publishing stubs as jars is to centralize the way stubs are kept.
|
||
For example, you can keep them as jars in a Maven repository.</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="paragraph">
|
||
<p>The following example shows how to publish stubs as jars:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><!-- First disable the default jar setup in the properties section -->
|
||
<!-- we don't want the verifier to do a jar for us -->
|
||
<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
|
||
|
||
<!-- Next add the assembly plugin to your build -->
|
||
<!-- we want the assembly plugin to generate the JAR -->
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-assembly-plugin</artifactId>
|
||
<executions>
|
||
<execution>
|
||
<id>stub</id>
|
||
<phase>prepare-package</phase>
|
||
<goals>
|
||
<goal>single</goal>
|
||
</goals>
|
||
<inherited>false</inherited>
|
||
<configuration>
|
||
<attach>true</attach>
|
||
<descriptors>
|
||
${basedir}/src/assembly/stub.xml
|
||
</descriptors>
|
||
</configuration>
|
||
</execution>
|
||
</executions>
|
||
</plugin>
|
||
|
||
<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
|
||
<assembly
|
||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
|
||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 https://maven.apache.org/xsd/assembly-1.1.3.xsd">
|
||
<id>stubs</id>
|
||
<formats>
|
||
<format>jar</format>
|
||
</formats>
|
||
<includeBaseDirectory>false</includeBaseDirectory>
|
||
<fileSets>
|
||
<fileSet>
|
||
<directory>src/main/java</directory>
|
||
<outputDirectory>/</outputDirectory>
|
||
<includes>
|
||
<include>**com/example/model/*.*</include>
|
||
</includes>
|
||
</fileSet>
|
||
<fileSet>
|
||
<directory>${project.build.directory}/classes</directory>
|
||
<outputDirectory>/</outputDirectory>
|
||
<includes>
|
||
<include>**com/example/model/*.*</include>
|
||
</includes>
|
||
</fileSet>
|
||
<fileSet>
|
||
<directory>${project.build.directory}/snippets/stubs</directory>
|
||
<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
|
||
<includes>
|
||
<include>**/*</include>
|
||
</includes>
|
||
</fileSet>
|
||
<fileSet>
|
||
<directory>${basedir}/src/test/resources/contracts</directory>
|
||
<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
|
||
<includes>
|
||
<include>**/*.groovy</include>
|
||
</includes>
|
||
</fileSet>
|
||
</fileSets>
|
||
</assembly></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="sect3">
|
||
<h4 id="features-stub-runner-core"><a class="anchor" href="#features-stub-runner-core"></a><a class="link" href="#features-stub-runner-core">4.5.3. Stub Runner Core</a></h4>
|
||
<div class="paragraph">
|
||
<p>The stub runner core runs stubs for service collaborators. Treating stubs as contracts of
|
||
services lets you 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 lets you automatically download the stubs of the provided dependencies (or
|
||
pick those from the classpath), start WireMock servers for them, and feed them with proper
|
||
stub definitions. For messaging, special stub routes are defined.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-retrieving"><a class="anchor" href="#features-stub-runner-retrieving"></a><a class="link" href="#features-stub-runner-retrieving">Retrieving stubs</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can pick from the following options of acquiring stubs:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Aether-based solution that downloads JARs with stubs from Artifactory or Nexus</p>
|
||
</li>
|
||
<li>
|
||
<p>Classpath-scanning solution that searches the classpath with a pattern to retrieve stubs</p>
|
||
</li>
|
||
<li>
|
||
<p>Writing 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="advanced.html#customization-custom-stub-runner">Custom Stub Runner</a> section.</p>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-downloading-stub"><a class="anchor" href="#features-stub-runner-downloading-stub"></a><a class="link" href="#features-stub-runner-downloading-stub">Downloading Stubs</a></h6>
|
||
<div class="paragraph">
|
||
<p>You can control the downloading of stubs with the <code>stubsMode</code> switch. It picks value from the
|
||
<code>StubRunnerProperties.StubsMode</code> enumeration. You can use the following options:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>StubRunnerProperties.StubsMode.CLASSPATH</code> (default value): Picks stubs from the classpath</p>
|
||
</li>
|
||
<li>
|
||
<p><code>StubRunnerProperties.StubsMode.LOCAL</code>: Picks stubs from a local storage (for example, <code>.m2</code>)</p>
|
||
</li>
|
||
<li>
|
||
<p><code>StubRunnerProperties.StubsMode.REMOTE</code>: Picks stubs from a remote location</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example picks stubs from a local location:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-classpath-scanning"><a class="anchor" href="#features-stub-runner-classpath-scanning"></a><a class="link" href="#features-stub-runner-classpath-scanning">Classpath scanning</a></h6>
|
||
<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), the classpath is scanned.
|
||
Consider the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can add the dependencies to your classpath, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>com.example</groupId>
|
||
<artifactId>beer-api-producer-restdocs</artifactId>
|
||
<classifier>stubs</classifier>
|
||
<version>0.0.1-SNAPSHOT</version>
|
||
<scope>test</scope>
|
||
<exclusions>
|
||
<exclusion>
|
||
<groupId>*</groupId>
|
||
<artifactId>*</artifactId>
|
||
</exclusion>
|
||
</exclusions>
|
||
</dependency>
|
||
<dependency>
|
||
<groupId>com.example.thing1</groupId>
|
||
<artifactId>thing2</artifactId>
|
||
<classifier>superstubs</classifier>
|
||
<version>1.0.0</version>
|
||
<scope>test</scope>
|
||
<exclusions>
|
||
<exclusion>
|
||
<groupId>*</groupId>
|
||
<artifactId>*</artifactId>
|
||
</exclusion>
|
||
</exclusions>
|
||
</dependency></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.thing1:thing2:1.0.0:superstubs") {
|
||
transitive = false
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then the specified locations on your classpath get scanned. For <code>com.example:beer-api-producer-restdocs</code>,
|
||
the following locations are scanned:</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>For <code>com.example.thing1:thing2</code>, the following locations are scanned:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>/META-INF/com.example.thing1/thing2/<strong>*/</strong>.*</p>
|
||
</li>
|
||
<li>
|
||
<p>/contracts/com.example.thing1/thing2/<strong>*/</strong>.*</p>
|
||
</li>
|
||
<li>
|
||
<p>/mappings/com.example.thing1/thing2/<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">
|
||
You have to explicitly provide the group and artifact IDs when you package the
|
||
producer stubs.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To achieve proper stub packaging, the producer would set up the contracts as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By 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="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By maintaining this structure, the classpath gets scanned and you can profit from the messaging or
|
||
HTTP stubs without the need to download artifacts.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-configuring-http-server-stubs"><a class="anchor" href="#features-stub-runner-configuring-http-server-stubs"></a><a class="link" href="#features-stub-runner-configuring-http-server-stubs">Configuring HTTP Server Stubs</a></h6>
|
||
<div class="paragraph">
|
||
<p>Stub Runner has a notion of a <code>HttpServerStub</code> that abstracts the underlying
|
||
concrete implementation of the HTTP server (for example, WireMock is one of the implementations).
|
||
Sometimes, you need to perform some additional tuning (which is concrete for the given implementation) of the stub servers.
|
||
To do that, Stub Runner gives you
|
||
the <code>httpServerStubConfigurer</code> property that is available in the annotation and the
|
||
JUnit rule and is accessible through system properties, where you can provide
|
||
your implementation of the <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. The following
|
||
example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="title">Example 1. WireMockHttpServerStubConfigurer implementation</div>
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can then reuse it with the <code>@AutoConfigureStubRunner</code> annotation, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Whenever an HTTPS port is found, it takes precedence over the HTTP port.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-running-stubs"><a class="anchor" href="#features-stub-runner-running-stubs"></a><a class="link" href="#features-stub-runner-running-stubs">Running stubs</a></h5>
|
||
<div class="paragraph">
|
||
<p>This section describes how to run stubs. It contains the following topics:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#features-stub-runner-http-stubs">HTTP Stubs</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-stub-runner-viewing">Viewing Registered Mappings</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-stub-runner-messaging">Messaging Stubs</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-http-stubs"><a class="anchor" href="#features-stub-runner-http-stubs"></a><a class="link" href="#features-stub-runner-http-stubs">HTTP Stubs</a></h6>
|
||
<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>The following example defines a stub in JSON:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-viewing"><a class="anchor" href="#features-stub-runner-viewing"></a><a class="link" href="#features-stub-runner-viewing">Viewing Registered Mappings</a></h6>
|
||
<div class="paragraph">
|
||
<p>Every stubbed collaborator exposes a list of defined mappings under the <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 the annotation-based approach, it would resembling the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the JUnit approach, it resembles the following example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then, if you check out the <code>target/outputmappings</code> folder, you would see the following structure;</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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)
|
||
the mappings available for the given server:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-messaging"><a class="anchor" href="#features-stub-runner-messaging"></a><a class="link" href="#features-stub-runner-messaging">Messaging Stubs</a></h6>
|
||
<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="sect3">
|
||
<h4 id="features-stub-runner-junit"><a class="anchor" href="#features-stub-runner-junit"></a><a class="link" href="#features-stub-runner-junit">4.5.4. Stub Runner JUnit Rule and Stub Runner JUnit5 Extension</a></h4>
|
||
<div class="paragraph">
|
||
<p>Stub Runner comes with a JUnit rule that lets you can download and run stubs for a given
|
||
group and artifact ID, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A <code>StubRunnerExtension</code> is also available for JUnit 5. <code>StubRunnerRule</code> and
|
||
<code>StubRunnerExtension</code> work in a very similar fashion. After the rule or extension is
|
||
executed, Stub Runner connects to your Maven repository and, for the given list of
|
||
dependencies, tries to:</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 or the provided port</p>
|
||
</li>
|
||
<li>
|
||
<p>Feed the WireMock server with all JSON files that are valid WireMock definitions</p>
|
||
</li>
|
||
<li>
|
||
<p>Send messages (remember to pass an implementation of <code>MessageVerifier</code> interface)</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Stub Runner uses the <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 let
|
||
you find the started stubs, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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<StubConfiguration, Collection<Contract>> getContracts();
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following examples provide more detail about using Stub Runner:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">spock</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">junit 4</div>
|
||
<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");
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">junit 5</div>
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See the <a href="#features-stub-runner-common-properties-junit-spring">Common Properties for JUnit and Spring</a> 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 (for example, <code>rule.messageVerifier(new MyMessageVerifier())</code>).
|
||
If you do not do this, then, whenever you try to send a message, an exception is thrown.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-rule-maven-settings"><a class="anchor" href="#features-stub-runner-rule-maven-settings"></a><a class="link" href="#features-stub-runner-rule-maven-settings">Maven Settings</a></h5>
|
||
<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 by using the properties mentioned above.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-rule-fixed-ports"><a class="anchor" href="#features-stub-runner-rule-fixed-ports"></a><a class="link" href="#features-stub-runner-rule-fixed-ports">Providing Fixed Ports</a></h5>
|
||
<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 is to use the fluent API of
|
||
JUnit rule.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-rule-fluent-api"><a class="anchor" href="#features-stub-runner-rule-fluent-api"></a><a class="link" href="#features-stub-runner-rule-fluent-api">Fluent API</a></h5>
|
||
<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. The following example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the preceding example, the following test is valid:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-rule-spring"><a class="anchor" href="#features-stub-runner-rule-spring"></a><a class="link" href="#features-stub-runner-rule-spring">Stub Runner with Spring</a></h5>
|
||
<div class="paragraph">
|
||
<p>Stub Runner with Spring 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, 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 follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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 > 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 > 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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Doing so depends on the following configuration file:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Instead of using the properties, you can also use the properties inside the <code>@AutoConfigureStubRunner</code>.
|
||
The following example achieves 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. The following example shows Stub Runner IDs for
|
||
<code>com.example:thing1</code> and <code>com.example:thing2</code>:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>stubrunner.runningstubs.thing1.port</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>stubrunner.runningstubs.com.example.thing1.port</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>stubrunner.runningstubs.thing2.port</code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>stubrunner.runningstubs.com.example.thing2.port</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can reference these values 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.
|
||
The value of the annotation can be the <code>groupid:artifactid</code> or just the <code>artifactid</code>.
|
||
The following example works shows Stub Runner IDs for
|
||
<code>com.example:thing1</code> and <code>com.example:thing2</code>.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StubRunnerPort("thing1")
|
||
int thing1Port;
|
||
@StubRunnerPort("com.example:thing2")
|
||
int thing2Port;</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-cloud"><a class="anchor" href="#features-stub-runner-cloud"></a><a class="link" href="#features-stub-runner-cloud">4.5.5. Stub Runner Spring Cloud</a></h4>
|
||
<div class="paragraph">
|
||
<p>Stub Runner can integrate with Spring Cloud.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For real life examples, see:</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">The 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">The consumer app sample</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-cloud-stubbing-discovery"><a class="anchor" href="#features-stub-runner-cloud-stubbing-discovery"></a><a class="link" href="#features-stub-runner-cloud-stubbing-discovery">Stubbing Service Discovery</a></h5>
|
||
<div class="paragraph">
|
||
<p>The most important feature of <code>Stub Runner Spring Cloud</code> is the fact that it stubs:</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 whether you use Zookeeper, Consul, Eureka, or anything
|
||
else, you do not need that in your tests. We are starting WireMock instances of your
|
||
dependencies and we are telling your application, whenever you use <code>Feign</code>, to load a
|
||
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, the following test passes:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Note that the preceding example requires the following configuration file:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-cloud-stubbing-profiles"><a class="anchor" href="#features-stub-runner-cloud-stubbing-profiles"></a><a class="link" href="#features-stub-runner-cloud-stubbing-profiles">Test Profiles and Service Discovery</a></h6>
|
||
<div class="paragraph">
|
||
<p>In your integration tests, you typically do not want to call either a discovery service (such as Eureka)
|
||
or Config Server. That is why you create an additional test configuration in which you want to disable
|
||
these features.</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 to disable these properties
|
||
in a static block such as the following example (for Eureka):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-additional-config"><a class="anchor" href="#features-stub-runner-additional-config"></a><a class="link" href="#features-stub-runner-additional-config">Additional Configuration</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can match the <code>artifactId</code> of the stub with the name of your application by using the <code>stubrunner.idsToServiceIds:</code> map.
|
||
You can disable Stub Runner Ribbon support by setting <code>stubrunner.cloud.ribbon.enabled</code> to <code>false</code>
|
||
You can disable Stub Runner support by setting <code>stubrunner.cloud.enabled</code> 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 is stubbed. This means that, regardless of whether you have
|
||
an existing <code>DiscoveryClient</code>, its results are ignored. However, if you want to reuse it, you can set
|
||
<code>stubrunner.cloud.delegate.enabled</code> to <code>true</code>, and then your existing <code>DiscoveryClient</code> results are
|
||
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
|
||
by setting the following system properties or by setting the corresponding 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="sect3">
|
||
<h4 id="features-stub-runner-boot"><a class="anchor" href="#features-stub-runner-boot"></a><a class="link" href="#features-stub-runner-boot">4.5.6. Using the Stub Runner Boot Application</a></h4>
|
||
<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 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="sect5">
|
||
<h6 id="features-stub-runner-boot-server"><a class="anchor" href="#features-stub-runner-boot-server"></a><a class="link" href="#features-stub-runner-boot-server">Stub Runner Server</a></h6>
|
||
<div class="paragraph">
|
||
<p>To use the Stub Runner Server, add the following dependency:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then annotate a class with <code>@EnableStubRunnerServer</code>, build a fat jar, and it is ready to work.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the properties, see the <a href="#features-stub-runner-rule-spring">Stub Runner Spring</a> section.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-boot-how-fat-jar"><a class="anchor" href="#features-stub-runner-boot-how-fat-jar"></a><a class="link" href="#features-stub-runner-boot-how-fat-jar">Stub Runner Server Fat Jar</a></h6>
|
||
<div class="paragraph">
|
||
<p>You can download a standalone JAR from Maven (for example, for version 2.0.1.RELEASE)
|
||
by running the following commands:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-boot-how-cli"><a class="anchor" href="#features-stub-runner-boot-how-cli"></a><a class="link" href="#features-stub-runner-boot-how-cli">Spring Cloud CLI</a></h6>
|
||
<div class="paragraph">
|
||
<p>Starting from the <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 running <code>spring cloud stubrunner</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In order to pass the configuration, you can create a <code>stubrunner.yml</code> file in the current working directory,
|
||
in a subdirectory called <code>config</code>, or in <code>~/.spring-cloud</code>. The file could resemble the following
|
||
example for running stubs installed locally:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="title">Example 2. stubrunner.yml</div>
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then you can call <code>spring cloud stubrunner</code> from your terminal window to start
|
||
the Stub Runner server. It is available at port <code>8750</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-boot-endpoints"><a class="anchor" href="#features-stub-runner-boot-endpoints"></a><a class="link" href="#features-stub-runner-boot-endpoints">Endpoints</a></h5>
|
||
<div class="paragraph">
|
||
<p>Stub Runner Boot offers two endpoints:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#features-stub-runner-boot-endpoints-http">HTTP</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-stub-runner-boot-endpoints-messaging">Messaging</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect5">
|
||
<h6 id="features-stub-runner-boot-endpoints-http"><a class="anchor" href="#features-stub-runner-boot-endpoints-http"></a><a class="link" href="#features-stub-runner-boot-endpoints-http">HTTP</a></h6>
|
||
<div class="paragraph">
|
||
<p>For HTTP, Stub Runner Boot makes the following endpoints available:</p>
|
||
</div>
|
||
<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="sect5">
|
||
<h6 id="features-stub-runner-boot-endpoints-messaging"><a class="anchor" href="#features-stub-runner-boot-endpoints-messaging"></a><a class="link" href="#features-stub-runner-boot-endpoints-messaging">Messaging</a></h6>
|
||
<div class="paragraph">
|
||
<p>For Messaging, Stub Runner Boot makes the following endpoints available:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>GET <code>/triggers</code>: Returns a list of all running labels in <code>ivy : [ label1, label2 …​]</code> notation</p>
|
||
</li>
|
||
<li>
|
||
<p>POST <code>/triggers/{label}</code>: Runs a trigger with <code>label</code></p>
|
||
</li>
|
||
<li>
|
||
<p>POST <code>/triggers/{ivy}/{label}</code>: Runs a trigger with a <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="sect4">
|
||
<h5 id="features-stub-runner-boot-endpoints-example"><a class="anchor" href="#features-stub-runner-boot-endpoints-example"></a><a class="link" href="#features-stub-runner-boot-endpoints-example">Example</a></h5>
|
||
<div class="paragraph">
|
||
<p>The following example shows typical usage of Stub Runner Boot:</p>
|
||
</div>
|
||
<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()) > 0
|
||
where:
|
||
stubId << ['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 << ['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="sect4">
|
||
<h5 id="features-stub-runner-boot-service-discovery"><a class="anchor" href="#features-stub-runner-boot-service-discovery"></a><a class="link" href="#features-stub-runner-boot-service-discovery">Stub Runner Boot with Service Discovery</a></h5>
|
||
<div class="paragraph">
|
||
<p>One way to use Stub Runner Boot is to use it as a feed of stubs for “smoke tests”. What does that mean?
|
||
Assume that you do not want to deploy 50 microservices to a test environment in order
|
||
to see whether your application works. You have already executed a suite of tests during the build process,
|
||
but you would also like to ensure that the packaging of your application works. You can
|
||
deploy your application to an environment, start it, and run a couple of tests on it to see whether
|
||
it works. We can call those tests “smoke tests”, because their purpose is to check only a handful
|
||
of testing scenarios.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The problem with this approach is thatm if you use microservices, you most likely also
|
||
use a service discovery tool. Stub Runner Boot lets you solve this issue by starting the
|
||
required stubs and registering them in a service discovery tool. Consider the following example of
|
||
such a setup with Eureka (assume that Eureka is already running):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We want to start a Stub Runner Boot server (<code>@EnableStubRunnerServer</code>), enable the Eureka client (<code>@EnableEurekaClient</code>),
|
||
and have the stub runner feature turned on (<code>@AutoConfigureStubRunner</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now assume that we want to start this application so that the stubs get automatically registered.
|
||
We can do so by running the application with <code>java -jar ${SYSTEM_PROPS} stub-runner-boot-eureka-example.jar</code>, where
|
||
<code>${SYSTEM_PROPS}</code> contains the following list of properties:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>That way, your deployed application can send requests to started WireMock servers through service
|
||
discovery. Most likely, points 1 through 3 could be set by default in <code>application.yml</code>, because they are not
|
||
likely to change. That way, you can provide only the list of stubs to download whenever you start
|
||
the Stub Runner Boot.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-stubs-per-consumer"><a class="anchor" href="#features-stub-runner-stubs-per-consumer"></a><a class="link" href="#features-stub-runner-stubs-per-consumer">4.5.7. Consumer-Driven Contracts: Stubs Per Consumer</a></h4>
|
||
<div class="paragraph">
|
||
<p>There are cases in which two consumers of the same endpoint want to have two 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 lets you immediately know which consumer uses which part of your API.
|
||
You can remove part of a response that your API produces and see which of your autogenerated tests
|
||
fails. If none fails, you can safely delete that part of the response, because nobody uses it.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following example of a contract defined for the producer called <code>producer</code>,
|
||
which has two consumers (<code>foo-consumer</code> and <code>bar-consumer</code>):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="title">Consumer <code>foo-service</code></div>
|
||
<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="listingblock">
|
||
<div class="title">Consumer <code>bar-service</code></div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">request {
|
||
url '/bar'
|
||
method GET()
|
||
}
|
||
response {
|
||
status OK()
|
||
body(
|
||
bar: "bar"
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You cannot produce two different responses for the same request. That is 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’s name. In other words, we scan the path of every stub and,
|
||
if it contains a subfolder with name of the consumer in the path, only then is it registered.</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>The <code>bar-consumer</code> consumer can either set the <code>spring.application.name</code> or the <code>stubrunner.consumer-name</code> to <code>bar-consumer</code>
|
||
Alternatively, you can set the test as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then only the stubs registered under a path that contains <code>bar-consumer</code> in its name (that is, those from the
|
||
<code>src/test/resources/contracts/bar-consumer/some/contracts/…​</code> folder) are allowed to be referenced.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also set the consumer name explicitly, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then only the stubs registered under a path that contains the <code>foo-consumer</code> in its name (that is, those from the
|
||
<code>src/test/resources/contracts/foo-consumer/some/contracts/…​</code> folder) are allowed to be referenced.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>See <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="sect3">
|
||
<h4 id="features-stub-runner-stubs-protocol"><a class="anchor" href="#features-stub-runner-stubs-protocol"></a><a class="link" href="#features-stub-runner-stubs-protocol">4.5.8. Fetching Stubs or Contract Definitions From A Location</a></h4>
|
||
<div class="paragraph">
|
||
<p>Instead of picking the stubs or contract definitions from
|
||
Artifactory / Nexus or Git, one can just want to point to
|
||
a location on drive or classpath. This can be especially useful in a multimodule project, where one module wants
|
||
to reuse stubs or contracts from another module without
|
||
the need to actually install those in a local maven
|
||
repository ot commit those changes to Git.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In order to achieve this it’s enough to use the <code>stubs://</code>
|
||
protocol when the repository root parameter is set either
|
||
in Stub Runner or in a Spring Cloud Contract plugin.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In this example the <code>producer</code> project has been successfully
|
||
built and stubs were generated under the <code>target/stubs</code> folder. As a consumer one can setup the Stub Runner to pick the stubs from that location using the <code>stubs://</code> protocol.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Annotation</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
|
||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||
repositoryRoot = "stubs://file://location/to/the/producer/target/stubs/",
|
||
ids = "com.example:some-producer")</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/producer/target/stubs/")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RegisterExtension
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/producer/target/stubs/")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Contracts and stubs may be stored in a location, where each producer has its own, dedicated folder for contracts and stub mappings. Under that folder each consumer can have its own setup. To make Stub Runner find the dedicated folder from the provided ids one can pass a property <code>stubs.find-producer=true</code> or a system property <code>stubrunner.stubs.find-producer=true</code> .</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="paragraph">
|
||
<p>└── com.example <1>
|
||
├── some-artifact-id <2>
|
||
│ └── 0.0.1
|
||
│ ├── contracts <3>
|
||
│ │ └── shouldReturnStuffForArtifactId.groovy
|
||
│ └── mappings <4>
|
||
│ └── shouldReturnStuffForArtifactId.json
|
||
└── some-other-artifact-id <5>
|
||
├── contracts
|
||
│ └── shouldReturnStuffForOtherArtifactId.groovy
|
||
└── mappings
|
||
└── shouldReturnStuffForOtherArtifactId.json</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="colist arabic">
|
||
<table>
|
||
<tr>
|
||
<td><i class="conum" data-value="1"></i><b>1</b></td>
|
||
<td>group id of the consumers</td>
|
||
</tr>
|
||
<tr>
|
||
<td><i class="conum" data-value="2"></i><b>2</b></td>
|
||
<td>consumer with artifact id [some-artifact-id]</td>
|
||
</tr>
|
||
<tr>
|
||
<td><i class="conum" data-value="3"></i><b>3</b></td>
|
||
<td>contracts for the consumer with artifact id [some-artifact-id]</td>
|
||
</tr>
|
||
<tr>
|
||
<td><i class="conum" data-value="4"></i><b>4</b></td>
|
||
<td>mappings for the consumer with artifact id [some-artifact-id]</td>
|
||
</tr>
|
||
<tr>
|
||
<td><i class="conum" data-value="5"></i><b>5</b></td>
|
||
<td>consumer with artifact id [some-other-artifact-id]</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Annotation</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
|
||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||
repositoryRoot = "stubs://file://location/to/the/contracts/directory",
|
||
ids = "com.example:some-producer",
|
||
properties="stubs.find-producer=true")</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> static Map<String, String> contractProperties() {
|
||
Map<String, String> map = new HashMap<>();
|
||
map.put("stubs.find-producer", "true");
|
||
return map;
|
||
}
|
||
|
||
@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts/directory")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.properties(contractProperties());</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> static Map<String, String> contractProperties() {
|
||
Map<String, String> map = new HashMap<>();
|
||
map.put("stubs.find-producer", "true");
|
||
return map;
|
||
}
|
||
|
||
@RegisterExtension
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts/directory")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.properties(contractProperties());</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-generate-stubs-at-runtime"><a class="anchor" href="#features-stub-runner-generate-stubs-at-runtime"></a><a class="link" href="#features-stub-runner-generate-stubs-at-runtime">4.5.9. Generating Stubs at Runtime</a></h4>
|
||
<div class="paragraph">
|
||
<p>As a consumer, you might not want to wait for the producer to finish its implementation and then publish their stubs. A solution to this problem can be generation of stubs at runtime.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As a producer, when a contract is defined, you are required to make the generated tests pass in order for the stubs to be published. There are cases where you would like to unblock the consumers so that they can fetch the stubs before your tests are actually passing. In this case you should set such contracts as in progress. You can read more about this under the <a href="#contract-dsl-in-progress">Contracts in Progress</a> section. That way your tests will not be generated, but the stubs will.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As a consumer, you can toggle a switch to generate stubs at runtime. Stub Runner will ignore all the existing stub mappings and will generate new ones for all the contract definitions. Another option is to pass the <code>stubrunner.generate-stubs</code> system property. Below you can find an example of such setup.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Annotation</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
|
||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||
repositoryRoot = "stubs://file://location/to/the/contracts",
|
||
ids = "com.example:some-producer",
|
||
generateStubs = true)</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.withGenerateStubs(true);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RegisterExtension
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.withGenerateStubs(true);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-fail-on-no-stubs"><a class="anchor" href="#features-stub-runner-fail-on-no-stubs"></a><a class="link" href="#features-stub-runner-fail-on-no-stubs">4.5.10. Fail On No Stubs</a></h4>
|
||
<div class="paragraph">
|
||
<p>By default Stub Runner will fail if no stubs were found. In order to change that behaviour, just set to <code>false</code> the <code>failOnNoStubs</code> property in the annotation or call the <code>withFailOnNoStubs(false)</code> method on a JUnit Rule or Extension.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Annotation</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureStubRunner(
|
||
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
|
||
repositoryRoot = "stubs://file://location/to/the/contracts",
|
||
ids = "com.example:some-producer",
|
||
failOnNoStubs = false)</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 4 Rule</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Rule
|
||
public StubRunnerRule rule = new StubRunnerRule()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.withFailOnNoStubs(false);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock secondary">
|
||
<div class="title">JUnit 5 Extension</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RegisterExtension
|
||
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
|
||
.downloadStub("com.example:some-producer")
|
||
.repoRoot("stubs://file://location/to/the/contracts")
|
||
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
|
||
.withFailOnNoStubs(false);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-stub-runner-common"><a class="anchor" href="#features-stub-runner-common"></a><a class="link" href="#features-stub-runner-common">4.5.11. Common Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>This section briefly describes common properties, including:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#features-stub-runner-common-properties-junit-spring">Common Properties for JUnit and Spring</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#features-stub-runner-stub-runner-stub-ids">Stub Runner Stubs IDs</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-common-properties-junit-spring"><a class="anchor" href="#features-stub-runner-common-properties-junit-spring"></a><a class="link" href="#features-stub-runner-common-properties-junit-spring">Common Properties for JUnit and Spring</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can set repetitive properties by using system properties or Spring configuration
|
||
properties. The following table shows 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"><code>false</code></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, change this value.</p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="features-stub-runner-stub-runner-stub-ids"><a class="anchor" href="#features-stub-runner-stub-runner-stub-ids"></a><a class="link" href="#features-stub-runner-stub-runner-stub-ids">Stub Runner Stubs IDs</a></h5>
|
||
<div class="paragraph">
|
||
<p>You can set the stubs to download in the <code>stubrunner.ids</code> system property. They
|
||
use the following pattern:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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 is 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 <code>+</code> is 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>
|
||
<div class="sect2">
|
||
<h3 id="features-wiremock"><a class="anchor" href="#features-wiremock"></a><a class="link" href="#features-wiremock">4.6. Spring Cloud Contract WireMock</a></h3>
|
||
<div class="paragraph">
|
||
<p>The Spring Cloud Contract WireMock modules let you use <a href="https://github.com/tomakehurst/wiremock">WireMock</a> in a
|
||
Spring Boot application. Check out the
|
||
<a href="https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples">samples</a>
|
||
for more details.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you have a Spring Boot application that uses Tomcat as an embedded server (which is
|
||
the default with <code>spring-boot-starter-web</code>), you can add
|
||
<code>spring-cloud-starter-contract-stub-runner</code> to your classpath and add <code>@AutoConfigureWireMock</code>
|
||
to use Wiremock in your tests. Wiremock runs as a stub server, and you
|
||
can register stub behavior by using a Java API or by using static JSON declarations as part of
|
||
your test. The following code shows an example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
|
||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||
@AutoConfigureWireMock(port = 0)
|
||
public class WiremockForDocsTests {
|
||
|
||
// A service that calls out over HTTP
|
||
@Autowired
|
||
private Service service;
|
||
|
||
@Before
|
||
public void setup() {
|
||
this.service.setBase("http://localhost:"
|
||
+ this.environment.getProperty("wiremock.server.port"));
|
||
}
|
||
|
||
// Using the WireMock APIs in the normal way:
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
// Stubbing WireMock
|
||
stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
|
||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||
// We're asserting if WireMock responded properly
|
||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To start the stub server on a different port, use (for example),
|
||
<code>@AutoConfigureWireMock(port=9999)</code>. For a random port, use a value of <code>0</code>. The stub
|
||
server port can be bound in the test application context with the "wiremock.server.port"
|
||
property. Using <code>@AutoConfigureWireMock</code> adds a bean of type <code>WiremockConfiguration</code> to
|
||
your test application context, where it is cached between methods and classes
|
||
having the same context. The same is true for Spring integration tests. Also, you can
|
||
inject a bean of type <code>WireMockServer</code> into your test.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-wiremock-registering-stubs"><a class="anchor" href="#features-wiremock-registering-stubs"></a><a class="link" href="#features-wiremock-registering-stubs">4.6.1. Registering Stubs Automatically</a></h4>
|
||
<div class="paragraph">
|
||
<p>If you use <code>@AutoConfigureWireMock</code>, it registers WireMock JSON stubs from the file
|
||
system or classpath (by default, from <code>file:src/test/resources/mappings</code>). You can
|
||
customize the locations byusing the <code>stubs</code> attribute in the annotation, which can be an
|
||
Ant-style resource pattern or a directory. In the case of a directory, <code><strong>*/</strong>.json</code> is
|
||
appended. The following code shows an example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>@RunWith(SpringRunner.class)
|
||
@SpringBootTest
|
||
@AutoConfigureWireMock(stubs="classpath:/stubs")
|
||
public class WiremockImportApplicationTests {
|
||
|
||
@Autowired
|
||
private Service service;
|
||
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||
}
|
||
|
||
}</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Actually, WireMock always loads mappings from <code>src/test/resources/mappings</code> <strong>as
|
||
well as</strong> the custom locations in the <code>stubs</code> attribute. To change this behavior, you can
|
||
also specify a files root, as described in the next section of this document.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you use Spring Cloud Contract’s default stub jars, your
|
||
stubs are stored in the <code>/META-INF/group-id/artifact-id/versions/mappings/</code> folder.
|
||
If you want to register all stubs from that location, from all embedded JARs, you can use
|
||
the following syntax:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AutoConfigureWireMock(port = 0, stubs = "classpath*:/META-INF/**/mappings/**/*.json")</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-wiremock-using-files"><a class="anchor" href="#features-wiremock-using-files"></a><a class="link" href="#features-wiremock-using-files">4.6.2. Using Files to Specify the Stub Bodies</a></h4>
|
||
<div class="paragraph">
|
||
<p>WireMock can read response bodies from files on the classpath or the file system. In the
|
||
case of the file system, you can see in the JSON DSL that the response has a <code>bodyFileName</code> instead of a
|
||
(literal) <code>body</code>. The files are resolved relative to a root directory (by default,
|
||
<code>src/test/resources/__files</code>). To customize this location, you can set the <code>files</code>
|
||
attribute in the <code>@AutoConfigureWireMock</code> annotation to the location of the parent
|
||
directory (in other words, <code>__files</code> is a subdirectory). You can use Spring resource
|
||
notation to refer to <code>file:…​</code> or <code>classpath:…​</code> locations. Generic URLs are not
|
||
supported. A list of values can be given — in which case, WireMock resolves the first file
|
||
that exists when it needs to find a response body.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
When you configure the <code>files</code> root, it also affects the
|
||
automatic loading of stubs, because they come from the root location
|
||
in a subdirectory called <code>mappings</code>. The value of <code>files</code> has no
|
||
effect on the stubs loaded explicitly from the <code>stubs</code> attribute.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-wiremock-junit-rule"><a class="anchor" href="#features-wiremock-junit-rule"></a><a class="link" href="#features-wiremock-junit-rule">4.6.3. Alternative: Using JUnit Rules</a></h4>
|
||
<div class="paragraph">
|
||
<p>For a more conventional WireMock experience, you can use JUnit <code>@Rules</code> to start and stop
|
||
the server. To do so, use the <code>WireMockSpring</code> convenience class to obtain an <code>Options</code>
|
||
instance, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
|
||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||
public class WiremockForDocsClassRuleTests {
|
||
|
||
// Start WireMock on some dynamic port
|
||
// for some reason `dynamicPort()` is not working properly
|
||
@ClassRule
|
||
public static WireMockClassRule wiremock = new WireMockClassRule(
|
||
WireMockSpring.options().dynamicPort());
|
||
|
||
// A service that calls out over HTTP to wiremock's port
|
||
@Autowired
|
||
private Service service;
|
||
|
||
@Before
|
||
public void setup() {
|
||
this.service.setBase("http://localhost:" + wiremock.port());
|
||
}
|
||
|
||
// Using the WireMock APIs in the normal way:
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
// Stubbing WireMock
|
||
wiremock.stubFor(get(urlEqualTo("/resource")).willReturn(aResponse()
|
||
.withHeader("Content-Type", "text/plain").withBody("Hello World!")));
|
||
// We're asserting if WireMock responded properly
|
||
assertThat(this.service.go()).isEqualTo("Hello World!");
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>@ClassRule</code> means that the server shuts down after all the methods in this class
|
||
have been run.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-wiremock-relaxed-ssl"><a class="anchor" href="#features-wiremock-relaxed-ssl"></a><a class="link" href="#features-wiremock-relaxed-ssl">4.6.4. Relaxed SSL Validation for Rest Template</a></h4>
|
||
<div class="paragraph">
|
||
<p>WireMock lets you stub a “secure” server with an <code>https</code> URL protocol. If your
|
||
application wants to contact that stub server in an integration test, it will find that
|
||
the SSL certificates are not valid (the usual problem with self-installed certificates).
|
||
The best option is often to re-configure the client to use <code>http</code>. If that is not an
|
||
option, you can ask Spring to configure an HTTP client that ignores SSL validation errors
|
||
(do so only for tests, of course).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To make this work with minimum fuss, you need to use the Spring Boot
|
||
<code>RestTemplateBuilder</code> in your application, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public RestTemplate restTemplate(RestTemplateBuilder builder) {
|
||
return builder.build();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You need <code>RestTemplateBuilder</code> because the builder is passed through callbacks to
|
||
initialize it, so the SSL validation can be set up in the client at that point. This
|
||
happens automatically in your test if you use the <code>@AutoConfigureWireMock</code>
|
||
annotation or the stub runner. If you use the JUnit <code>@Rule</code> approach, you need to add the
|
||
<code>@AutoConfigureHttpClient</code> annotation as well, as the following example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
|
||
@SpringBootTest("app.baseUrl=https://localhost:6443")
|
||
@AutoConfigureHttpClient
|
||
public class WiremockHttpsServerApplicationTests {
|
||
|
||
@ClassRule
|
||
public static WireMockClassRule wiremock = new WireMockClassRule(
|
||
WireMockSpring.options().httpsPort(6443));
|
||
...
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you use <code>spring-boot-starter-test</code>, you have the Apache HTTP client on the
|
||
classpath, and it is selected by the <code>RestTemplateBuilder</code> and configured to ignore SSL
|
||
errors. If you use the default <code>java.net</code> client, you do not need the annotation (but it
|
||
does no harm). There is currently no support for other clients, but it may be added
|
||
in future releases.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To disable the custom <code>RestTemplateBuilder</code>, set the <code>wiremock.rest-template-ssl-enabled</code>
|
||
property to <code>false</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="features-wiremock-spring-mvc-mocks"><a class="anchor" href="#features-wiremock-spring-mvc-mocks"></a><a class="link" href="#features-wiremock-spring-mvc-mocks">4.6.5. WireMock and Spring MVC Mocks</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into
|
||
a Spring <code>MockRestServiceServer</code>. The following code shows an example:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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)
|
||
public class WiremockForDocsMockServerApplicationTests {
|
||
|
||
@Autowired
|
||
private RestTemplate restTemplate;
|
||
|
||
@Autowired
|
||
private Service service;
|
||
|
||
@Test
|
||
public void contextLoads() throws Exception {
|
||
// will read stubs classpath
|
||
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
|
||
.baseUrl("https://example.org").stubs("classpath:/stubs/resource.json")
|
||
.build();
|
||
// We're asserting if WireMock responded properly
|
||
assertThat(this.service.go()).isEqualTo("Hello World");
|
||
server.verify();
|
||
}
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>baseUrl</code> value is prepended to all mock calls, and the <code>stubs()</code> method takes a stub
|
||
path resource pattern as an argument. In the preceding example, the stub defined at
|
||
<code>/stubs/resource.json</code> is loaded into the mock server. If the <code>RestTemplate</code> is asked to
|
||
visit <code><a href="https://example.org/" class="bare">example.org/</a></code>, it gets the responses as being declared at that URL. More
|
||
than one stub pattern can be specified, and each one can be a directory (for a recursive
|
||
list of all <code>.json</code>), a fixed filename (as in the preceding example), or an Ant-style
|
||
pattern. The JSON format is the normal WireMock format, which you can read about at the
|
||
<a href="https://wiremock.org/docs/stubbing/">WireMock website</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as
|
||
Spring Boot embedded servers, and Wiremock itself has “native” support for a particular
|
||
version of Jetty (currently 9.2). To use the native Jetty, you need to add the native
|
||
Wiremock dependencies and exclude the Spring Boot container (if there is one).</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="features-build-tools"><a class="anchor" href="#features-build-tools"></a><a class="link" href="#features-build-tools">4.7. Build Tools Integration</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can run test generation and stub execution in various ways. The most common ones are
|
||
as follows:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="maven-project.html">Maven</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="gradle-project.html">Gradle</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="docker-project.html">Docker</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="features-whats-next"><a class="anchor" href="#features-whats-next"></a><a class="link" href="#features-whats-next">4.8. What to Read Next</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want to learn more about any of the classes discussed in this section, you can browse the
|
||
<a href="https://github.com/spring-cloud/spring-cloud-contract/tree/${github-tag}">source code directly</a>. If you have specific questions, see the
|
||
<a href="#howto">how-to</a> section.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you are comfortable with Spring Cloud Contract’s core features, you can continue on and read
|
||
about
|
||
<a href="#advanced.adoc">Spring Cloud Contract’s advanced features</a>.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="howto"><a class="anchor" href="#howto"></a><a class="link" href="#howto">5. “How-to” Guides</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>This section provides answers to some common “how do I do that…​” questions
|
||
that often arise when using Spring Cloud Contract. Its coverage is not exhaustive, but it
|
||
does cover quite a lot.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you have a specific problem that we do not cover here, you might want to check out
|
||
<a href="https://stackoverflow.com/tags/spring-cloud-contract">stackoverflow.com</a> to see if someone has
|
||
already provided an answer. Stack Overflow is also a great place to ask new questions (please use
|
||
the <code>spring-cloud-contract</code> tag).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We are also more than happy to extend this section. If you want to add a “how-to”,
|
||
send us a <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/${github-tag}">pull request</a>.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="why-spring-cloud-contract"><a class="anchor" href="#why-spring-cloud-contract"></a><a class="link" href="#why-spring-cloud-contract">5.1. Why use Spring Cloud Contract?</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract works great in a polyglot environment. This project has a lot of
|
||
really interesting features. Quite a few of these features definitely make
|
||
Spring Cloud Contract Verifier stand out on the market of Consumer Driven Contract
|
||
(CDC) tooling. The most interesting features include the following:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Ability to do CDC with messaging.</p>
|
||
</li>
|
||
<li>
|
||
<p>Clear and easy to use, statically typed DSL.</p>
|
||
</li>
|
||
<li>
|
||
<p>Ability 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 and provides easy hooks to extend its functionality.</p>
|
||
</li>
|
||
<li>
|
||
<p>Ability to add support for any language & framework through Docker.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-not-write-contracts-in-groovy"><a class="anchor" href="#how-to-not-write-contracts-in-groovy"></a><a class="link" href="#how-to-not-write-contracts-in-groovy">5.2. How Can I Write Contracts in a Language Other than Groovy?</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can write a contract in YAML. See <a href="#contract-dsl">this section</a> for more information.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We are working on allowing more ways of describing the contracts. You can check the <a href="https://github.com/spring-cloud/spring-cloud-contract/issues/">github-issues</a> for more information.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-provide-dynamic-values"><a class="anchor" href="#how-to-provide-dynamic-values"></a><a class="link" href="#how-to-provide-dynamic-values">5.3. How Can I Provide Dynamic Values to a Contract?</a></h3>
|
||
<div class="paragraph">
|
||
<p>One of the biggest challenges related to stubs is their reusability. Only if they can be widely used can they serve their purpose.
|
||
The hard-coded values (such as dates and IDs) of request and response elements generally make that difficult.
|
||
Consider the following JSON request:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider the following JSON response:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Imagine the pain required to set the proper value of the <code>time</code> field (assume that this content is generated by the
|
||
database) by changing the clock in the system or by providing stub implementations of data providers. The same is related
|
||
to the field called <code>id</code>. You could create a stubbed implementation of UUID generator, but doing so makes little sense.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>So, as a consumer, you want to send a request that matches any form of a time or any UUID. That way, your system
|
||
works as usual, generating data without you having to stub out anything. 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 as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As far as the response goes, as a consumer, you need a concrete value on which you can operate.
|
||
Consequently, the following JSON is valid:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the previous sections, we generated tests from contracts. So, from the producer’s side, the situation looks
|
||
much different. We parse 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 cannot have any sort of matching. We need concrete values on which the
|
||
producer’s backend can work. Consequently, the following JSON would be valid:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>On the other hand, from the point of view of the validity of the contract, the response does not necessarily have to
|
||
contain concrete values for <code>time</code> or <code>id</code>. Suppose you generate those on the producer side. Again, you
|
||
have to do a lot of stubbing to ensure that you always return the same values. That is why, from the producer’s side
|
||
you might want the following response:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>How can you then provide a matcher for the consumer and a concrete value for the producer (and the opposite at some other time)?
|
||
Spring Cloud Contract lets you provide a dynamic value. That means that it can differ for both
|
||
sides of the communication.</p>
|
||
</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="admonitionblock important">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-important" title="Important"></i>
|
||
</td>
|
||
<td class="content">
|
||
Read the <a href="https://groovy-lang.org/json.html">Groovy docs related to JSON</a> to understand how to
|
||
properly structure the request and response bodies.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-do-stubs-versioning"><a class="anchor" href="#how-to-do-stubs-versioning"></a><a class="link" href="#how-to-do-stubs-versioning">5.4. How to Do Stubs versioning?</a></h3>
|
||
<div class="paragraph">
|
||
<p>This section covers version of the stubs, which you can handle in a number of different ways:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#how-to-api-versioning">API Versioning</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#how-to-jar-versioning">JAR versioning</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#how-to-dev-or-prod-stubs">Development or Production Stubs</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-api-versioning"><a class="anchor" href="#how-to-api-versioning"></a><a class="link" href="#how-to-api-versioning">5.4.1. API Versioning</a></h4>
|
||
<div class="paragraph">
|
||
<p>What does versioning really mean? If you refer to the API version, 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 the version through headers and URLs</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We do not try to answer the question of which approach is better. You should pick whatever
|
||
suits your needs and lets you generate business value.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Assume that you do version your API. In that case, you should provide as many contracts with as many versions as you support.
|
||
You can create a subfolder for every version or append it to the contract name — whatever suits you best.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-jar-versioning"><a class="anchor" href="#how-to-jar-versioning"></a><a class="link" href="#how-to-jar-versioning">5.4.2. 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>Assume that you do continuous delivery and deployment, which means that you generate a new version of
|
||
the jar each time you go through the pipeline and that the jar can go to production at any time. For example, your jar version
|
||
looks like the following (because it got built on the 20.10.2016 at 20:15:21) :</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In that case your, generated stub jar should look like the following:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</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. the following example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If the versioning, however, is fixed (for example, <code>1.0.4.RELEASE</code> or <code>2.1.1</code>), you have to set the concrete value of the jar
|
||
version. The following example shows how to do so for version 2.1.1:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-dev-or-prod-stubs"><a class="anchor" href="#how-to-dev-or-prod-stubs"></a><a class="link" href="#how-to-dev-or-prod-stubs">5.4.3. Development or Production Stubs</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can manipulate the classifier to run the tests against current the 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, you can run tests in one case with development stubs and one with production stubs.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example works for tests that use the development version of the stubs:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example works for tests that use the production version of stubs:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also pass those values also in properties from your deployment pipeline.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-common-repo-with-contracts"><a class="anchor" href="#how-to-common-repo-with-contracts"></a><a class="link" href="#how-to-common-repo-with-contracts">5.5. How Can I use a Common Repository with Contracts Instead of Storing Them with the Producer?</a></h3>
|
||
<div class="paragraph">
|
||
<p>Another way of storing contracts, rather than having them with the producer, is to keep
|
||
them in a common place. This situation can be related to security issues (where the
|
||
consumers cannot clone the producer’s code). Also if you keep contracts in a single place,
|
||
then you, as a producer, know how many consumers you have and which consumer you may break
|
||
with your local changes.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-repo-structure"><a class="anchor" href="#how-to-repo-structure"></a><a class="link" href="#how-to-repo-structure">5.5.1. Repo Structure</a></h4>
|
||
<div class="paragraph">
|
||
<p>Assume that we have a producer with coordinates of <code>com.example:server</code> and three
|
||
consumers: <code>client1</code>, <code>client2</code>, and <code>client3</code>. Then, in the repository with common
|
||
contracts, you could have the following setup (which you can check out
|
||
<a href="https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/contracts">here</a>).
|
||
The following listing shows such a structure:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see under the slash-delimited <code>groupid/artifact id</code> folder (<code>com/example/server</code>) you have
|
||
expectations of the three 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 repository.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a <code>pom.xml</code> inside the <code>server</code> folder:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><?xml version="1.0" encoding="UTF-8"?>
|
||
<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">
|
||
<modelVersion>4.0.0</modelVersion>
|
||
|
||
<groupId>com.example</groupId>
|
||
<artifactId>server</artifactId>
|
||
<version>0.0.1-SNAPSHOT</version>
|
||
|
||
<name>Server Stubs</name>
|
||
<description>POM used to install locally stubs for consumer side</description>
|
||
|
||
<parent>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-parent</artifactId>
|
||
<version>2.2.0.BUILD-SNAPSHOT</version>
|
||
<relativePath/>
|
||
</parent>
|
||
|
||
<properties>
|
||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||
<java.version>1.8</java.version>
|
||
<spring-cloud-contract.version>2.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version>
|
||
<spring-cloud-release.version>Hoxton.BUILD-SNAPSHOT</spring-cloud-release.version>
|
||
<excludeBuildFolders>true</excludeBuildFolders>
|
||
</properties>
|
||
|
||
<dependencyManagement>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-dependencies</artifactId>
|
||
<version>${spring-cloud-release.version}</version>
|
||
<type>pom</type>
|
||
<scope>import</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
</dependencyManagement>
|
||
|
||
<build>
|
||
<plugins>
|
||
<plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- By default it would search under src/test/resources/ -->
|
||
<contractsDirectory>${project.basedir}</contractsDirectory>
|
||
</configuration>
|
||
</plugin>
|
||
</plugins>
|
||
</build>
|
||
|
||
<repositories>
|
||
<repository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
<repository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</repository>
|
||
</repositories>
|
||
<pluginRepositories>
|
||
<pluginRepository>
|
||
<id>spring-snapshots</id>
|
||
<name>Spring Snapshots</name>
|
||
<url>https://repo.spring.io/snapshot</url>
|
||
<snapshots>
|
||
<enabled>true</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-milestones</id>
|
||
<name>Spring Milestones</name>
|
||
<url>https://repo.spring.io/milestone</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
<pluginRepository>
|
||
<id>spring-releases</id>
|
||
<name>Spring Releases</name>
|
||
<url>https://repo.spring.io/release</url>
|
||
<snapshots>
|
||
<enabled>false</enabled>
|
||
</snapshots>
|
||
</pluginRepository>
|
||
</pluginRepositories>
|
||
|
||
</project></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>There are no dependencies other than the Spring Cloud Contract Maven Plugin.
|
||
Those pom files are necessary for the consumer side to run <code>mvn clean install -DskipTests</code> to locally install
|
||
the stubs of the producer project.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>pom.xml</code> in the root folder can look like the following:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><?xml version="1.0" encoding="UTF-8"?>
|
||
<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">
|
||
<modelVersion>4.0.0</modelVersion>
|
||
|
||
<groupId>com.example.standalone</groupId>
|
||
<artifactId>contracts</artifactId>
|
||
<version>0.0.1-SNAPSHOT</version>
|
||
|
||
<name>Contracts</name>
|
||
<description>Contains all the Spring Cloud Contracts, well, contracts. JAR used by the
|
||
producers to generate tests and stubs
|
||
</description>
|
||
|
||
<properties>
|
||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||
</properties>
|
||
|
||
<build>
|
||
<plugins>
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-assembly-plugin</artifactId>
|
||
<executions>
|
||
<execution>
|
||
<id>contracts</id>
|
||
<phase>prepare-package</phase>
|
||
<goals>
|
||
<goal>single</goal>
|
||
</goals>
|
||
<configuration>
|
||
<attach>true</attach>
|
||
<descriptor>${basedir}/src/assembly/contracts.xml</descriptor>
|
||
<!-- If you want an explicit classifier remove the following line -->
|
||
<appendAssemblyId>false</appendAssemblyId>
|
||
</configuration>
|
||
</execution>
|
||
</executions>
|
||
</plugin>
|
||
</plugins>
|
||
</build>
|
||
|
||
</project></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>It uses the assembly plugin to build the JAR with all the contracts. The following example
|
||
shows such a setup:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><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">
|
||
<id>project</id>
|
||
<formats>
|
||
<format>jar</format>
|
||
</formats>
|
||
<includeBaseDirectory>false</includeBaseDirectory>
|
||
<fileSets>
|
||
<fileSet>
|
||
<directory>${project.basedir}</directory>
|
||
<outputDirectory>/</outputDirectory>
|
||
<useDefaultExcludes>true</useDefaultExcludes>
|
||
<excludes>
|
||
<exclude>**/${project.build.directory}/**</exclude>
|
||
<exclude>mvnw</exclude>
|
||
<exclude>mvnw.cmd</exclude>
|
||
<exclude>.mvn/**</exclude>
|
||
<exclude>src/**</exclude>
|
||
</excludes>
|
||
</fileSet>
|
||
</fileSets>
|
||
</assembly></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-workflow"><a class="anchor" href="#how-to-workflow"></a><a class="link" href="#how-to-workflow">5.5.2. Workflow</a></h4>
|
||
<div class="paragraph">
|
||
<p>The workflow assumes that Spring Cloud Contract is set up both on the consumer and on the
|
||
producer side. There is also the proper plugin setup in the common repository with
|
||
contracts. The CI jobs are set for a common repository to build an artifact of all
|
||
contracts and upload it to Nexus/Artifactory. The following image shows the UML for this
|
||
workflow:</p>
|
||
</div>
|
||
<div class="imageblock">
|
||
<div class="content">
|
||
<img src="./images/how-to-common-repo.png" alt="how to common repo" width="1588" height="1421">
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-workflow-consumer"><a class="anchor" href="#how-to-workflow-consumer"></a><a class="link" href="#how-to-workflow-consumer">5.5.3. Consumer</a></h4>
|
||
<div class="paragraph">
|
||
<p>When the consumer wants to work on the contracts offline, instead of cloning the producer
|
||
code, the consumer team clones the common repository, goes to the required producer’s
|
||
folder (for example, <code>com/example/server</code>) and runs <code>mvn clean install -DskipTests</code> to
|
||
locally install 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="how-to-workflow-producer"><a class="anchor" href="#how-to-workflow-producer"></a><a class="link" href="#how-to-workflow-producer">5.5.4. Producer</a></h4>
|
||
<div class="paragraph">
|
||
<p>As a producer, you can to alter the Spring Cloud Contract Verifier to provide the URL and
|
||
the dependency of the JAR that contains the contracts, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<configuration>
|
||
<contractsMode>REMOTE</contractsMode>
|
||
<contractsRepositoryUrl>
|
||
https://link/to/your/nexus/or/artifactory/or/sth
|
||
</contractsRepositoryUrl>
|
||
<contractDependency>
|
||
<groupId>com.example.standalone</groupId>
|
||
<artifactId>contracts</artifactId>
|
||
</contractDependency>
|
||
</configuration>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With this setup, the JAR with a groupid of <code>com.example.standalone</code> and artifactid
|
||
<code>contracts</code> is downloaded from <code><a href="https://link/to/your/nexus/or/artifactory/or/sth" class="bare">link/to/your/nexus/or/artifactory/or/sth</a></code>. It is
|
||
then unpacked in a local temporary folder, and the contracts present in
|
||
<code>com/example/server</code> are picked as the ones used to generate the tests and the stubs. Due
|
||
to this convention, the producer team can know which consumer teams will be broken when
|
||
some incompatible changes are made.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The rest of the flow looks the same.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-define-messaging-contracts-per-topic"><a class="anchor" href="#how-to-define-messaging-contracts-per-topic"></a><a class="link" href="#how-to-define-messaging-contracts-per-topic">5.5.5. How Can I Define Messaging Contracts per Topic Rather than per Producer?</a></h4>
|
||
<div class="paragraph">
|
||
<p>To avoid messaging contracts duplication in the common repository, when a few producers write messages to one topic,
|
||
we could create a structure in which the REST contracts are placed in a folder per producer and messaging
|
||
contracts are placed in the folder per topic.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="how-to-define-messaging-contracts-per-topic-maven"><a class="anchor" href="#how-to-define-messaging-contracts-per-topic-maven"></a><a class="link" href="#how-to-define-messaging-contracts-per-topic-maven">For Maven Projects</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 files by messaging topics we are interested in. The
|
||
<code>includedFiles</code> property of the Maven Spring Cloud Contract plugin
|
||
lets us do so. Also, <code>contractsPath</code> need to be specified, since the default path would be
|
||
the common repository <code>groupid/artifactid</code>. The following example shows a Maven
|
||
plugin for Spring Cloud Contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<configuration>
|
||
<contractsMode>REMOTE</contractsMode>
|
||
<contractsRepositoryUrl>https://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
|
||
<contractDependency>
|
||
<groupId>com.example</groupId>
|
||
<artifactId>common-repo-with-contracts</artifactId>
|
||
<version>+</version>
|
||
</contractDependency>
|
||
<contractsPath>/</contractsPath>
|
||
<baseClassMappings>
|
||
<baseClassMapping>
|
||
<contractPackageRegex>.*messaging.*</contractPackageRegex>
|
||
<baseClassFQN>com.example.services.MessagingBase</baseClassFQN>
|
||
</baseClassMapping>
|
||
<baseClassMapping>
|
||
<contractPackageRegex>.*rest.*</contractPackageRegex>
|
||
<baseClassFQN>com.example.services.TestBase</baseClassFQN>
|
||
</baseClassMapping>
|
||
</baseClassMappings>
|
||
<includedFiles>
|
||
<includedFile>**/${project.artifactId}/**</includedFile>
|
||
<includedFile>**/${first-topic}/**</includedFile>
|
||
<includedFile>**/${second-topic}/**</includedFile>
|
||
</includedFiles>
|
||
</configuration>
|
||
</plugin></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Many of the values in the preceding Maven plugin can be changed. We included it for
|
||
illustration purposes rather than trying to provide a “typical” example.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="how-to-define-messaging-contracts-per-topic-gradle"><a class="anchor" href="#how-to-define-messaging-contracts-per-topic-gradle"></a><a class="link" href="#how-to-define-messaging-contracts-per-topic-gradle">For Gradle Projects</a></h5>
|
||
<div class="paragraph">
|
||
<p>To work with a Gradle project:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Add a custom configuration for the common repository dependency, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Add the common repository dependency to your classpath, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Download the dependency to an appropriate folder, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Unzip the JAR, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Cleanup unused contracts, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Create task dependencies, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Configure the plugin by specifying the directory that contains the contracts, by setting
|
||
the <code>contractsDslDir</code> property, as follows:</p>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-use-git-as-storage"><a class="anchor" href="#how-to-use-git-as-storage"></a><a class="link" href="#how-to-use-git-as-storage">5.6. How Can I Use Git as the Storage for Contracts and Stubs?</a></h3>
|
||
<div class="paragraph">
|
||
<p>In the polyglot world, there are languages that do not use binary storages, as
|
||
Artifactory or Nexus do. Starting from Spring Cloud Contract version 2.0.0, we provide
|
||
mechanisms to store contracts and stubs in a SCM (Source Control Management) repository. Currently, the
|
||
only supported SCM is Git.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The repository would have to have the following setup
|
||
(which you can checkout from <a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/contracts_git/">here</a>):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Under the <code>META-INF</code> folder:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>We group applications by <code>groupId</code> (such as <code>com.example</code>).</p>
|
||
</li>
|
||
<li>
|
||
<p>Each application is represented by its <code>artifactId</code> (for example, <code>beer-api-producer-git</code>).</p>
|
||
</li>
|
||
<li>
|
||
<p>Next, each application is organized by its version (such as <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 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 <code>1.0.0.RELEASE</code>, <code>2.0.0.BUILD-SNAPSHOT</code>, and <code>2.0.0.RELEASE</code>, we assume
|
||
that the latest is <code>2.0.0.BUILD-SNAPSHOT</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p>If you have <code>1.0.0.RELEASE</code> and <code>2.0.0.RELEASE</code>, we 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 <code>1.0.0.RELEASE</code>, <code>2.0.0.BUILD-SNAPSHOT</code>, and <code>2.0.0.RELEASE</code> we 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 pick that folder.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Finally, there are two folders:</p>
|
||
</div>
|
||
<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 (such as <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>: The Maven or Gradle Spring Cloud Contract plugins push
|
||
the stub server mappings in this folder. On the consumer side, Stub Runner scans this folder
|
||
to start stub servers with stub definitions. The folder structure is a copy
|
||
of the one created in the <code>contracts</code> subfolder.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-protocol-convention"><a class="anchor" href="#how-to-protocol-convention"></a><a class="link" href="#how-to-protocol-convention">5.6.1. Protocol Convention</a></h4>
|
||
<div class="paragraph">
|
||
<p>To control the type and location of the source of contracts (whether
|
||
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 (by using a plugin) or stubs (from 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 have to prefix
|
||
the connection URL with <code>git://</code>. The following listing shows some examples:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-protocol-convention-producer"><a class="anchor" href="#how-to-protocol-convention-producer"></a><a class="link" href="#how-to-protocol-convention-producer">5.6.2. Producer</a></h4>
|
||
<div class="paragraph">
|
||
<p>For the producer, to use the SCM (Source Control Management) approach, we can reuse the
|
||
same mechanism we use for external contracts. We route Spring Cloud Contract
|
||
to use the SCM implementation from the URL that starts with
|
||
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 do not push stubs to the <code>origin</code> of your git
|
||
repository.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following listing includes the relevant parts both Maven and Gradle build files:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- Base class mappings etc. -->
|
||
|
||
<!-- We want to pick contracts from a Git repository -->
|
||
<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git</contractsRepositoryUrl>
|
||
|
||
<!-- We reuse the contract dependency section to set up the path
|
||
to the folder that contains the contract definitions. In our case the
|
||
path will be /groupId/artifactId/version/contracts -->
|
||
<contractDependency>
|
||
<groupId>${project.groupId}</groupId>
|
||
<artifactId>${project.artifactId}</artifactId>
|
||
<version>${project.version}</version>
|
||
</contractDependency>
|
||
|
||
<!-- The contracts mode can't be classpath -->
|
||
<contractsMode>REMOTE</contractsMode>
|
||
</configuration>
|
||
<executions>
|
||
<execution>
|
||
<phase>package</phase>
|
||
<goals>
|
||
<!-- By default we will not push the stubs back to SCM,
|
||
you have to explicitly add it as a goal -->
|
||
<goal>pushStubsToScm</goal>
|
||
</goals>
|
||
</execution>
|
||
</executions>
|
||
</plugin></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 {
|
||
// 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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With such a setup:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>A git project is cloned to a temporary directory</p>
|
||
</li>
|
||
<li>
|
||
<p>The SCM stub downloader goes to <code>META-INF/groupId/artifactId/version/contracts</code> folder
|
||
to find contracts. For example, 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 are generated from the contracts.</p>
|
||
</li>
|
||
<li>
|
||
<p>Stubs are created from the contracts.</p>
|
||
</li>
|
||
<li>
|
||
<p>Once the tests pass, the stubs are committed in the cloned repository.</p>
|
||
</li>
|
||
<li>
|
||
<p>Finally, a push is sent to that repo’s <code>origin</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-protocol-convention-producer-with-contracts-stored-locally"><a class="anchor" href="#how-to-protocol-convention-producer-with-contracts-stored-locally"></a><a class="link" href="#how-to-protocol-convention-producer-with-contracts-stored-locally">5.6.3. 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.
|
||
The following listing shows the setup required to achieve this with Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<!-- In the default configuration, we want to use the contracts stored locally -->
|
||
<configuration>
|
||
<baseClassMappings>
|
||
<baseClassMapping>
|
||
<contractPackageRegex>.*messaging.*</contractPackageRegex>
|
||
<baseClassFQN>com.example.BeerMessagingBase</baseClassFQN>
|
||
</baseClassMapping>
|
||
<baseClassMapping>
|
||
<contractPackageRegex>.*rest.*</contractPackageRegex>
|
||
<baseClassFQN>com.example.BeerRestBase</baseClassFQN>
|
||
</baseClassMapping>
|
||
</baseClassMappings>
|
||
<basePackageForTests>com.example</basePackageForTests>
|
||
</configuration>
|
||
<executions>
|
||
<execution>
|
||
<phase>package</phase>
|
||
<goals>
|
||
<!-- By default we will not push the stubs back to SCM,
|
||
you have to explicitly add it as a goal -->
|
||
<goal>pushStubsToScm</goal>
|
||
</goals>
|
||
<configuration>
|
||
<!-- We want to pick contracts from a Git repository -->
|
||
<contractsRepositoryUrl>git://file://${env.ROOT}/target/contract_empty_git/
|
||
</contractsRepositoryUrl>
|
||
<!-- Example of URL via git protocol -->
|
||
<!--<contractsRepositoryUrl>git://git@github.com:spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
|
||
<!-- Example of URL via http protocol -->
|
||
<!--<contractsRepositoryUrl>git://https://github.com/spring-cloud-samples/spring-cloud-contract-samples.git</contractsRepositoryUrl>-->
|
||
<!-- We reuse the contract dependency section to set up the path
|
||
to the folder that contains the contract definitions. In our case the
|
||
path will be /groupId/artifactId/version/contracts -->
|
||
<contractDependency>
|
||
<groupId>${project.groupId}</groupId>
|
||
<artifactId>${project.artifactId}</artifactId>
|
||
<version>${project.version}</version>
|
||
</contractDependency>
|
||
<!-- The mode can't be classpath -->
|
||
<contractsMode>LOCAL</contractsMode>
|
||
</configuration>
|
||
</execution>
|
||
</executions>
|
||
</plugin></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 {
|
||
// 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>
|
||
</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 are picked.</p>
|
||
</li>
|
||
<li>
|
||
<p>Tests are generated from the contracts.</p>
|
||
</li>
|
||
<li>
|
||
<p>Stubs are created from the contracts.</p>
|
||
</li>
|
||
<li>
|
||
<p>Once the tests pass:</p>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The git project is cloned to a temporary directory.</p>
|
||
</li>
|
||
<li>
|
||
<p>The stubs and contracts are committed in the cloned repository.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Finally, a push is done to that repository’s <code>origin</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-protocol-convention-contracts-producer-stubs-external"><a class="anchor" href="#how-to-protocol-convention-contracts-producer-stubs-external"></a><a class="link" href="#how-to-protocol-convention-contracts-producer-stubs-external">5.6.4. Keeping Contracts with the Producer and Stubs in an External Repository</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can also keep the contracts in the producer repository but keep the stubs in an external git repository.
|
||
This is most useful when you want to use the base consumer-producer collaboration flow but cannot
|
||
use an artifact repository to store the stubs.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To do so, 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 class="sect3">
|
||
<h4 id="how-to-protocol-convention-contracts-producer-stubs-external-consumer"><a class="anchor" href="#how-to-protocol-convention-contracts-producer-stubs-external-consumer"></a><a class="link" href="#how-to-protocol-convention-contracts-producer-stubs-external-consumer">5.6.5. 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, you can pass the URL of the
|
||
SCM repository, prefixed with the <code>git://</code> protocol. The following example shows how to do so:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With such a setup:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The git project is cloned to a temporary directory.</p>
|
||
</li>
|
||
<li>
|
||
<p>The SCM stub downloader goes to thje <code>META-INF/groupId/artifactId/version/</code> folder
|
||
to find stub definitions and contracts. For example, 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 are started and fed with mappings.</p>
|
||
</li>
|
||
<li>
|
||
<p>Messaging definitions are read and used in the messaging tests.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-use-pact-broker"><a class="anchor" href="#how-to-use-pact-broker"></a><a class="link" href="#how-to-use-pact-broker">5.7. How 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, you can fetch Pact files from the Pact Broker to generate
|
||
tests and stubs.</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 and then
|
||
shares the files with the Producer. Those expectations are generated
|
||
from the Consumer’s code and can break the Producer if the expectations
|
||
are not met.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-use-pact-broker-pact"><a class="anchor" href="#how-to-use-pact-broker-pact"></a><a class="link" href="#how-to-use-pact-broker-pact">5.7.1. How to Work with Pact</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract includes support for the <a href="https://docs.pact.io/">Pact</a> representation of
|
||
contracts up until version 4. Instead of using the DSL, you can use Pact files. In this section, we
|
||
show how to add Pact support for your project. Note, however, that not all functionality is supported.
|
||
Starting with version 3, you can combine multiple matchers 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 by using the <code>AND</code> 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 is skipped and the ISO format is used.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-use-pact-broker-pact-converter"><a class="anchor" href="#how-to-use-pact-broker-pact-converter"></a><a class="link" href="#how-to-use-pact-broker-pact-converter">5.7.2. Pact Converter</a></h4>
|
||
<div class="paragraph">
|
||
<p>In order to properly support the Spring Cloud Contract way of doing messaging
|
||
with Pact, you have to provide some additional meta data entries.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<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 the <code>sentTo</code> key equal to the destination to
|
||
which a message is to be sent (for example, <code>"metaData": { "sentTo": "activemq:output" }</code>).</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-use-pact-broker-pact-contract"><a class="anchor" href="#how-to-use-pact-broker-pact-contract"></a><a class="link" href="#how-to-use-pact-broker-pact-contract">5.7.3. Pact Contract</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract can read the Pact JSON definition. You can place the file in the
|
||
<code>src/test/resources/contracts</code> folder. The following example shows such a Pact contract:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-use-pact-broker-pact-for-producers"><a class="anchor" href="#how-to-use-pact-broker-pact-for-producers"></a><a class="link" href="#how-to-use-pact-broker-pact-for-producers">5.7.4. 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. The following listing shows how to do so for both
|
||
Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
|
||
</configuration>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
</dependency>
|
||
</dependencies>
|
||
</plugin></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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When you execute the build of your application, a test and stub is generated. The following
|
||
example shows a test and stub that came from this process:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">test</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">stub</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">{
|
||
"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>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-use-pact-broker-pact-consumers"><a class="anchor" href="#how-to-use-pact-broker-pact-consumers"></a><a class="link" href="#how-to-use-pact-broker-pact-consumers">5.7.5. 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. The following listing shows how to do so for both
|
||
Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">Maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></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>
|
||
<div class="sect3">
|
||
<h4 id="pact-stub-downloader"><a class="anchor" href="#pact-stub-downloader"></a><a class="link" href="#pact-stub-downloader">5.7.6. Communicating with the Pact Broker</a></h4>
|
||
<div class="paragraph">
|
||
<p>Whenever the <code>repositoryRoot</code> property starts with a Pact protocol
|
||
(starts with <code>pact://</code>), the stub downloader tries
|
||
to fetch the Pact contract definitions from the Pact Broker.
|
||
Whatever is set after <code>pact://</code> is parsed as the Pact Broker URL.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By setting environment variables, system properties, or properties set
|
||
inside the plugin or contracts repository configuration, you can
|
||
tweak the downloader’s behavior. The following table describes the
|
||
properties:</p>
|
||
</div>
|
||
<table class="tableblock frame-all grid-all stretch">
|
||
<caption class="title">Table 1. Pact 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">The URL of the 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">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">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">The tags that 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">The kind of authentication that 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">The username to use when connecting 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">The password to use when connecting 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 is a combination of <code>groupId:artifactId</code>. If <code>false</code>, only <code>artifactId</code> is used.</p></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-pact-consumer"><a class="anchor" href="#how-to-pact-consumer"></a><a class="link" href="#how-to-pact-consumer">5.7.7. Flow: Consumer Contract approach with Pact Broker | Consumer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>The consumer uses the Pact framework to generate Pact files. The
|
||
Pact files are sent to the Pact Broker. You can find an example of such a setup
|
||
<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="how-to-pact-producer"><a class="anchor" href="#how-to-pact-producer"></a><a class="link" href="#how-to-pact-producer">5.7.8. Flow: Consumer Contract Approach with Pact Broker on the Producer Side</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 with the URL that contains
|
||
the <code>pact://</code> protocol. You can pass the URL to the
|
||
Pact Broker. You can find an example of such a setup
|
||
<a href="https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/2.2.x/producer_pact">here</a>.
|
||
The following listing shows the configuration details for both Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-maven-plugin</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
<extensions>true</extensions>
|
||
<configuration>
|
||
<!-- Base class mappings etc. -->
|
||
|
||
<!-- We want to pick contracts from a Git repository -->
|
||
<contractsRepositoryUrl>pact://http://localhost:8085</contractsRepositoryUrl>
|
||
|
||
<!-- We reuse the contract dependency section to set up the path
|
||
to the folder that contains the contract definitions. In our case the
|
||
path will be /groupId/artifactId/version/contracts -->
|
||
<contractDependency>
|
||
<groupId>${project.groupId}</groupId>
|
||
<artifactId>${project.artifactId}</artifactId>
|
||
<!-- When + is passed, a latest tag will be applied when fetching pacts -->
|
||
<version>+</version>
|
||
</contractDependency>
|
||
|
||
<!-- The contracts mode can't be classpath -->
|
||
<contractsMode>REMOTE</contractsMode>
|
||
</configuration>
|
||
<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||
<version>${spring-cloud-contract.version}</version>
|
||
</dependency>
|
||
</dependencies>
|
||
</plugin></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 {
|
||
//...
|
||
}
|
||
|
||
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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With such a setup:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Pact files are downloaded from the Pact Broker.</p>
|
||
</li>
|
||
<li>
|
||
<p>Spring Cloud Contract converts 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="how-to-pact-consumer-producer-contract"><a class="anchor" href="#how-to-pact-consumer-producer-contract"></a><a class="link" href="#how-to-pact-consumer-producer-contract">5.7.9. Flow: Producer Contract approach with Pact on the Consumer Side</a></h4>
|
||
<div class="paragraph">
|
||
<p>In the scenario where you do not want to do the consumer contract approach
|
||
(for every single consumer, define the expectations) but you prefer
|
||
to do producer contracts (the producer provides the contracts and
|
||
publishes stubs), you can use Spring Cloud Contract with the
|
||
Stub Runner option. You can find an example of such a setup
|
||
<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>Remember to add the Stub Runner and Spring Cloud Contract Pact modules
|
||
as test dependencies.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following listing shows the configuration details for both Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependencyManagement>
|
||
<dependencies>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-dependencies</artifactId>
|
||
<version>${spring-cloud.version}</version>
|
||
<type>pom</type>
|
||
<scope>import</scope>
|
||
</dependency>
|
||
</dependencies>
|
||
</dependencyManagement>
|
||
|
||
<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
|
||
<dependencies>
|
||
<!-- ... -->
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
|
||
<scope>test</scope>
|
||
</dependency>
|
||
<dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-contract-pact</artifactId>
|
||
<scope>test</scope>
|
||
</dependency>
|
||
</dependencies></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">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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Next, you can pass the URL of the Pact Broker to <code>repositoryRoot</code>, prefixed
|
||
with <code>pact://</code> protocol (for example, <code>pact://http://localhost:8085</code>), as the following
|
||
example shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With such a setup:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Pact files are downloaded from the Pact Broker.</p>
|
||
</li>
|
||
<li>
|
||
<p>Spring Cloud Contract converts the Pact files into stub definitions.</p>
|
||
</li>
|
||
<li>
|
||
<p>The stub servers are started and fed with stubs.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-debug"><a class="anchor" href="#how-to-debug"></a><a class="link" href="#how-to-debug">5.8. 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. RestAssured
|
||
relies on the <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. To use it, add this to your application properties, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-debug-wiremock"><a class="anchor" href="#how-to-debug-wiremock"></a><a class="link" href="#how-to-debug-wiremock">5.9. How Can I Debug the Mapping, Request, or Response Being Sent by WireMock?</a></h3>
|
||
<div class="paragraph">
|
||
<p>Starting from version <code>1.2.0</code>, we turn on WireMock logging to
|
||
<code>info</code> and set the WireMock notifier to being verbose. Now you can
|
||
exactly know what request was received by the WireMock server and which
|
||
matching response definition was picked.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To turn off this feature, set WireMock logging to <code>ERROR</code>, as follows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<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>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-see-registered-stubs"><a class="anchor" href="#how-to-see-registered-stubs"></a><a class="link" href="#how-to-see-registered-stubs">5.10. How Can I See What Got Registered in the HTTP Server Stub?</a></h3>
|
||
<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 is attached.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-reference-text-from-file"><a class="anchor" href="#how-to-reference-text-from-file"></a><a class="link" href="#how-to-reference-text-from-file">5.11. How Can I Reference Text from File?</a></h3>
|
||
<div class="paragraph">
|
||
<p>In version 1.2.0, we added this ability. You can call a <code>file(…​)</code> method in the
|
||
DSL and provide a path relative to where the contract lies.
|
||
If you use YAML, you can use the <code>bodyFromFile</code> property.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-generate-pact-from-scc"><a class="anchor" href="#how-to-generate-pact-from-scc"></a><a class="link" href="#how-to-generate-pact-from-scc">5.12. How Can I Generate Pact, YAML, or X files from Spring Cloud Contract Contracts?</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Contract comes with a <code>ToFileContractsTransformer</code> class that lets you dump
|
||
contracts as files for the given <code>ContractConverter</code>. It contains a <code>static void main</code>
|
||
method that lets you execute the transformer as an executable. It takes the following
|
||
arguments:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>argument 1 : <code>FQN</code>: Fully qualified name of the <code>ContractConverter</code> (for example, <code>PactContractConverter</code>). <strong>REQUIRED</strong>.</p>
|
||
</li>
|
||
<li>
|
||
<p>argument 2 : <code>path</code>: Path where the dumped files should be stored. <strong>OPTIONAL</strong> — defaults to <code>target/converted-contracts</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p>argument 3 : <code>path</code>: Path were the contracts should be searched for. <strong>OPTIONAL</strong> — defaults to <code>src/test/resources/contracts</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>After executing the transformer, the Spring Cloud Contract files are processed and,
|
||
depending on the provided FQN of the <code>ContractTransformer</code>, the contracts are transformed
|
||
to the required format and dumped to the provided folder.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to configure Pact integration for both Maven and Gradle:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><plugin>
|
||
<groupId>org.codehaus.mojo</groupId>
|
||
<artifactId>exec-maven-plugin</artifactId>
|
||
<version>1.6.0</version>
|
||
<executions>
|
||
<execution>
|
||
<id>convert-dsl-to-pact</id>
|
||
<phase>process-test-classes</phase>
|
||
<configuration>
|
||
<classpathScope>test</classpathScope>
|
||
<mainClass>
|
||
org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer
|
||
</mainClass>
|
||
<arguments>
|
||
<argument>
|
||
org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter
|
||
</argument>
|
||
<argument>${project.basedir}/target/pacts</argument>
|
||
<argument>
|
||
${project.basedir}/src/test/resources/contracts
|
||
</argument>
|
||
</arguments>
|
||
</configuration>
|
||
<goals>
|
||
<goal>java</goal>
|
||
</goals>
|
||
</execution>
|
||
</executions>
|
||
</plugin></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">task convertContracts(type: JavaExec) {
|
||
main = "org.springframework.cloud.contract.verifier.util.ToFileContractsTransformer"
|
||
classpath = sourceSets.test.compileClasspath
|
||
args("org.springframework.cloud.contract.verifier.spec.pact.PactContractConverter",
|
||
"${project.rootDir}/build/pacts", "${project.rootDir}/src/test/resources/contracts")
|
||
}
|
||
|
||
test.dependsOn("convertContracts")</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-work-with-transitivie"><a class="anchor" href="#how-to-work-with-transitivie"></a><a class="link" href="#how-to-work-with-transitivie">5.13. How Can I Work with Transitive Dependencies?</a></h3>
|
||
<div class="paragraph">
|
||
<p>The Spring Cloud Contract plugins add the tasks that create the stubs jar for you. One
|
||
problem that arises is that, when reusing the stubs, you can mistakenly import all of
|
||
that stub’s dependencies. When building a Maven artifact, even though you have a couple
|
||
of different jars, all of them share one pom, as the following listing shows:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">├── producer-0.0.1.BUILD-20160903.075506-1-stubs.jar
|
||
├── producer-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
|
||
├── producer-0.0.1.BUILD-20160903.075655-2-stubs.jar
|
||
├── producer-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
|
||
├── producer-0.0.1.BUILD-SNAPSHOT.jar
|
||
├── producer-0.0.1.BUILD-SNAPSHOT.pom
|
||
├── producer-0.0.1.BUILD-SNAPSHOT-stubs.jar
|
||
├── ...
|
||
└── ...</code></pre>
|
||
</div>
|
||
</div>
|
||
</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="sect3">
|
||
<h4 id="how-to-work-with-transitivie-optional"><a class="anchor" href="#how-to-work-with-transitivie-optional"></a><a class="link" href="#how-to-work-with-transitivie-optional">5.13.1. How Can I Mark All Application Dependencies as Optional?</a></h4>
|
||
<div class="paragraph">
|
||
<p>If, in the <code>producer</code> application, you mark all of your dependencies as optional,
|
||
when you include the <code>producer</code> stubs in another application (or when that
|
||
dependency gets downloaded by Stub Runner) then, since all of the dependencies are
|
||
optional, they do not get downloaded.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-work-with-transitivie-separate"><a class="anchor" href="#how-to-work-with-transitivie-separate"></a><a class="link" href="#how-to-work-with-transitivie-separate">5.13.2. How can I Create a Separate <code>artifactid</code> for the Stubs?</a></h4>
|
||
<div class="paragraph">
|
||
<p>If you create a separate <code>artifactid</code>, you can set it up in whatever way you wish.
|
||
For example, you might decide to have no dependencies at all.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="how-to-work-with-transitivie-exclude"><a class="anchor" href="#how-to-work-with-transitivie-exclude"></a><a class="link" href="#how-to-work-with-transitivie-exclude">5.13.3. How can I Exclude Dependencies on the Consumer Side?</a></h4>
|
||
<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>
|
||
<div class="sect2">
|
||
<h3 id="contract-dsl-rest-docs"><a class="anchor" href="#contract-dsl-rest-docs"></a><a class="link" href="#contract-dsl-rest-docs">5.14. How can I Generate 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 by using Spring REST Docs,
|
||
you only need to make some minor changes to your setup if you are using MockMvc and RestAssuredMockMvc.
|
||
To do so, include the following dependencies (if you have not already done so):</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">maven</div>
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-starter-contract-verifier</artifactId>
|
||
<scope>test</scope>
|
||
</dependency>
|
||
<dependency>
|
||
<groupId>org.springframework.restdocs</groupId>
|
||
<artifactId>spring-restdocs-mockmvc</artifactId>
|
||
<optional>true</optional>
|
||
</dependency></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-starter-contract-verifier'
|
||
testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc'</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Next, you need to make some changes to your base class. The following examples use
|
||
<code>WebAppContext</code> and the standalone option with RestAssured:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock primary">
|
||
<div class="title">WebAppContext</div>
|
||
<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="listingblock secondary">
|
||
<div class="title">Standalone</div>
|
||
<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>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
You need not specify the output directory for the generated snippets (since version 1.2.0.RELEASE of Spring REST Docs).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-use-stubs-from-a-location"><a class="anchor" href="#how-to-use-stubs-from-a-location"></a><a class="link" href="#how-to-use-stubs-from-a-location">5.15. How can I Use Stubs from a Location</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want to fetch contracts or stubs from a given location without cloning a repo or fetching a JAR, just use the <code>stubs://</code> protocol when providing the repository root argument for Stub Runner or the Spring Cloud Contract plugin. You can read more about this in <a href="#features-stub-runner-stubs-protocol">this section</a> of the documentation.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-generate-stubs-at-runtime"><a class="anchor" href="#how-to-generate-stubs-at-runtime"></a><a class="link" href="#how-to-generate-stubs-at-runtime">5.16. How can I Generate Stubs at Runtime</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want to generate stubs at runtime for contracts, it’s enough to switch the <code>generateStubs</code> property in the <code>@AutoConfigureStubRunner</code> annotation, or call the <code>withGenerateStubs(true)</code> method on the JUnit Rule or Extension. You can read more about this in <a href="#features-stub-runner-generate-stubs-at-runtime">this section</a> of the documentation.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="how-to-use-the-failonnostubs-feature"><a class="anchor" href="#how-to-use-the-failonnostubs-feature"></a><a class="link" href="#how-to-use-the-failonnostubs-feature">5.17. How can I Make The Build Pass if There Are No Contracts or Stubs</a></h3>
|
||
<div class="paragraph">
|
||
<p>If you want Stub Runner not to fail if no stubs were found, it’s enough to switch the <code>generateStubs</code> property in the <code>@AutoConfigureStubRunner</code> annotation, or call the <code>withFailOnNoStubs(false)</code> method on the JUnit Rule or Extension. You can read more about this in <a href="#features-stub-runner-fail-on-no-stubs">this section</a> of the documentation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you want the plugins not to fail the build when no contracts were found, you can set the <code>failOnNoStubs</code> flag in Maven or call the <code>contractRepository { failOnNoStubs(false) }</code> Closure in Gradle.</p>
|
||
</div>
|
||
</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> |