Files
spring-cloud-contract/spring-cloud-contract.html
2016-07-15 14:34:53 +02:00

4085 lines
157 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.3">
<title>Spring Cloud Contract</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Remove comment around @import statement below when using as a custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
body{-webkit-font-smoothing:antialiased}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.spread{width:100%}
p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ul.no-bullet{list-style:none}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite:before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7;font-weight:bold}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
body{tab-size:4}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}
.clearfix:after,.float-group:after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menu{color:rgba(0,0,0,.8)}
b.button:before,b.button:after{position:relative;top:-1px;font-weight:400}
b.button:before{content:"[";padding:0 3px 0 2px}
b.button:after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}
#header:after,#content:after,#footnotes:after,#footer:after{clear:both}
#content{margin-top:1.25em}
#content:before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span:before{content:"\00a0\2013\00a0"}
#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark:before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber:after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media only screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}
@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
.sect1{padding-bottom:.625em}
@media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}
.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0}
.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}
@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}
.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]:before{display:block}
.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote:before{display:none}
.verseblock{margin:0 1em 1.25em 1em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 0 1.25em 0;display:block}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}
.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}
table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}
table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}
table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}
table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}
table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}
table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot{border-width:1px 0}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}
ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}
ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}
ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}
ul.inline>li>*{display:block}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist>table tr>td:first-of-type{padding:0 .75em;line-height:1}
.colist>table tr>td:last-of-type{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]:after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@media print{@page{margin:1.25cm .75cm}
*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]:after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
.sect1{padding-bottom:0!important}
.sect1+.sect1{border:0!important}
#header>h1:first-child{margin-top:1.25rem}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span:before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]:before{display:block}
#footer{background:none!important;padding:0 .9375em}
#footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
</style>
</head>
<body class="article">
<div id="header">
<h1>Spring Cloud Contract</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><em>Documentation Authors: Adam Dudczak, Marcin Grzejszczak, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła</em></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier">Spring Cloud Contract Verifier</h2>
<div class="sectionbody">
</div>
</div>
<div class="sect1">
<h2 id="_introduction">Introduction</h2>
<div class="sectionbody">
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
<a href="http://codearte.github.io/accurest">The documentation to the deprecated Accurest project in version 1.1.0 is available here.</a>
</td>
</tr>
</table>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<div class="title">Tip</div>
</td>
<td class="content">
The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski (<a href="http://codearte.io">codearte.io</a>)
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped
with <em>Contract Definition Language</em> (DSL). Contract definitions are used to produce following resources:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>JSON stub definitions to be used by Wiremock when doing integration testing on the client code (<em>client tests</em>).
Test code must still be written by hand, test data is produced by Spring Cloud Contract Verifier.</p>
</li>
<li>
<p>Messaging routes if you&#8217;re using one. We&#8217;re integrating with Spring Integration, Spring Cloud Stream and Apache Camel. You can however set your own integrations if you want to</p>
</li>
<li>
<p>Acceptance tests (in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (<em>server tests</em>).
Full test is generated by Spring Cloud Contract Verifier.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier moves TDD to the level of software architecture.</p>
</div>
<div class="sect2">
<h3 id="_why">Why?</h3>
<div class="paragraph">
<p>Let us assume that we have a system comprising of multiple microservices:</p>
</div>
<div class="imageblock">
<div class="content">
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/docs/src/main/asciidoc/images/Deps.png" alt="Microservices Architecture">
</div>
</div>
<div class="sect3">
<h4 id="_testing_issues">Testing issues</h4>
<div class="paragraph">
<p>If we wanted to test the application in top left corner if it can communicate with other services then we could do one of two things:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>deploy all microservices and perform end to end tests</p>
</li>
<li>
<p>mock other microservices in unit / integration tests</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Both have their advantages but also a lot of disadvantages. Let&#8217;s focus on the latter.</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 would have to deploy 6 microservices, a couple of databases etc.</p>
</li>
<li>
<p>the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime).</p>
</li>
<li>
<p>long to run</p>
</li>
<li>
<p>very late feedback</p>
</li>
<li>
<p>extremely hard to debug</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>Mock other microservices in unit / integration tests</strong></p>
</div>
<div class="paragraph">
<p>Advantages:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>very fast feedback</p>
</li>
<li>
<p>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 thus they might have nothing to do with the reality</p>
</li>
<li>
<p>you can go to production with passing tests and failing production</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need
to set up the whole world of microservices.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/docs/src/main/asciidoc/images/Stubs1.png" alt="Stubbed Services">
</div>
</div>
<div class="paragraph">
<p>If you work on stubs then the only applications you need are those that your application is using directly.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/docs/src/main/asciidoc/images/Stubs2.png" alt="Stubbed Services">
</div>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier gives you the certainty that the stubs that you&#8217;re using were created by the service that you&#8217;re calling. Also if you can use them it means that they were
tested against the producer&#8217;s side. In other words - you can trust those stubs.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_purposes">Purposes</h3>
<div class="paragraph">
<p>The main purposes of Spring Cloud Contract Verifier with Stub Runner are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>to ensure that WireMock / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do,</p>
</li>
<li>
<p>to promote ATDD method and Microservices architectural style,</p>
</li>
<li>
<p>to provide a way to publish changes in contracts that are immediately visible on both sides,</p>
</li>
<li>
<p>to generate boilerplate test code used on the server side.</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_client_side">Client Side</h3>
<div class="paragraph">
<p>During the tests you want to have a Wiremock instance / Messaging route up and running that simulates the service Y.
You would like to feed that instance with a proper stub definition. That stub definition would need
to be valid and should also be reusable on the server side.</p>
</div>
<div class="paragraph">
<p><em>Summing it up:</em> On this side, in the stub definition, you can use patterns for request stubbing and you need exact
values for responses.</p>
</div>
</div>
<div class="sect2">
<h3 id="_server_side">Server Side</h3>
<div class="paragraph">
<p>Being a service Y since you are developing your stub, you need to be sure that it&#8217;s actually resembling your
concrete implementation. You can&#8217;t have a situation where your stub acts in one way and your application on
production behaves in a different way.</p>
</div>
<div class="paragraph">
<p>That&#8217;s why from the provided stub acceptance tests will be generated that will ensure
that your application behaves in the same way as you define in your stub.</p>
</div>
<div class="paragraph">
<p><em>Summing it up:</em> On this side, in the stub definition, you need exact values as request and can use patterns/methods
for response verification.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_step_by_step_guide_to_cdc">Step by step guide to CDC</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let&#8217;s take an example of Fraud Detection and Loan Issuance process. Let&#8217;s assume that the Loan Issuance is a client to the
Fraud Detection server. Let&#8217;s assume that we have to write a new feature (if a client wants too borrow too much money then
we mark him as fraud). The current implementation grants loan to everybody.</p>
</div>
<div class="paragraph">
<p>Of course both client and server development teams need to communicate directly and discuss changes while
going through the process. CDC is all about communication.</p>
</div>
<div class="paragraph">
<p>The code is available under the <code>samples/samples-standalone/http-server</code> and <code>samples/samples-standalone/http-client</code> folders.</p>
</div>
<div class="paragraph">
<p>As a developer of the Loan Issuance service (a consumer to the Fraud Detection server):</p>
</div>
<div class="ulist">
<ul>
<li>
<p>start doing TDD by writing a test to your feature</p>
</li>
<li>
<p>at some point in time you need to send a request to the Fraud Detection service</p>
</li>
<li>
<p>you clone the Fraud Detection service repository locally</p>
</li>
<li>
<p>you define the contract locally in the repo of Fraud Detection service</p>
</li>
<li>
<p>provide the group id and artifact id for the Spring Cloud Contract Stub Runner to download stubs of your collaborators</p>
</li>
<li>
<p>also provide the offline work switch since you don&#8217;t want to work offline</p>
</li>
<li>
<p>when you need to install the stubs of the server side you execute e.g. <code>./mvnw clean install -DskipTests</code> in their repo</p>
</li>
<li>
<p>when you&#8217;re happy with the contract and your test passes publish a PR to the server side</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>As a developer of the Fraud Detection server (a server to the Loan Issuance service):</p>
</div>
<div class="ulist">
<ul>
<li>
<p>take over the PR (if you try to build it your app will break cause you have a missing implementation)</p>
</li>
<li>
<p>write the missing implementation</p>
</li>
<li>
<p>deploy your app with the stubs e.g. <code>./mvnw clean deploy</code> you&#8217;ll publish both the application fat jar and the stub jar</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>As a developer of the Loan Issuance service (a consumer to the Fraud Detection server):</p>
</div>
<div class="ulist">
<ul>
<li>
<p>since the server side work was done you can merge the branch to master</p>
</li>
<li>
<p>disable the offline work for Spring Cloud Contract Stub Runner</p>
</li>
<li>
<p>at this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Code examples:</p>
</div>
<div class="paragraph">
<p><strong>CLIENT</strong></p>
</div>
<div class="paragraph">
<p><strong>start doing TDD</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">def 'should be rejected due to abnormal loan amount'() {
given:
LoanApplication application =
new LoanApplication(client: new Client(pesel: '1234567890'), amount: 99_999)
when:
LoanApplicationResult loanApplication = sut.loanApplication(application)
then:
loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLICATION_REJECTED
loanApplication.rejectionReason == 'Amount too high'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>at some point in time you need to send a request to the Fraud Detection service</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ResponseEntity&lt;FraudServiceResponse&gt; response =
restTemplate.exchange("http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
new HttpEntity&lt;&gt;(request, httpHeaders),
FraudServiceResponse.class);</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>you define the contract locally in the repo of Fraud Detection service</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">package contracts
org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(client('FRAUD'), server(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
}""")
headers {
header('Content-Type': value(server(regex('application/vnd.fraud.v1.json.*')), client('application/vnd.fraud.v1+json')))
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>provide the group id and artifact id for the Spring Cloud Contract Stub Runner to download stubs of your collaborators</strong>
<strong>also provide the offline work switch since you don&#8217;t want to work offline</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubrunner:
work-offline: true
stubs.ids: 'com.example:http-server:+:stubs:8080'</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>SERVER</strong></p>
</div>
<div class="paragraph">
<p><strong>take over the PR (if you try to build it your app will break cause you have a missing implementation)</strong></p>
</div>
<div class="paragraph">
<p>the API</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@RequestMapping(
value = "/fraudcheck",
method = PUT,
consumes = FRAUD_SERVICE_JSON_VERSION_1,
produces = FRAUD_SERVICE_JSON_VERSION_1)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>the initial impl</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@RequestMapping(
value = "/fraudcheck",
method = PUT,
consumes = FRAUD_SERVICE_JSON_VERSION_1,
produces = FRAUD_SERVICE_JSON_VERSION_1)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>write the missing implementation</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@RequestMapping(
value = "/fraudcheck",
method = PUT,
consumes = FRAUD_SERVICE_JSON_VERSION_1,
produces = FRAUD_SERVICE_JSON_VERSION_1)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
if (amountGreaterThanThreshold(fraudCheck)) {
return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
}
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}</code></pre>
</div>
</div>
<div class="sect2">
<h3 id="_dependencies">Dependencies</h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier and Stub Runner are using the following libraries</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="http://wiremock.org/">WireMock</a></p>
</li>
<li>
<p><a href="https://github.com/jayway/JsonPath">Jayway JSONPath</a></p>
</li>
<li>
<p><a href="https://github.com/marcingrzejszczak/jsonassert">JSONAssert from Marcin Grzejszczak</a></p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_additional_links">Additional links</h3>
<div class="paragraph">
<p>Below you can find some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some can be outdated since the Spring Cloud Contract Verifier project
is under constant development.</p>
</div>
<div class="sect3">
<h4 id="_videos">Videos</h4>
<div class="paragraph">
<p><strong>Marcin Grzejszczak and Jakub Kubryński talking about Spring Cloud Contract Verifier</strong></p>
</div>
<div class="videoblock">
<div class="content">
<iframe src="https://www.youtube.com/embed/msRFcQM07-Y?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="paragraph">
<p><strong>Olga Maciaszek-Sharma talking about Accurest (Spring Cloud Contract Verifier predecessor)</strong></p>
</div>
<div class="videoblock">
<div class="content">
<iframe src="https://www.youtube.com/embed/daafmTYFoDU?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="paragraph">
<p><strong>Marcin Grzejszczak and Jakub Kubryński talking about Accurest (Spring Cloud Contract Verifier predecessor)</strong></p>
</div>
<div class="videoblock">
<div class="content">
<iframe src="https://player.vimeo.com/video/130779882" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_readings">Readings</h4>
<div class="ulist">
<ul>
<li>
<p><a href="http://www.slideshare.net/MarcinGrzejszczak/stick-to-the-rules-consumer-driven-contracts-201507-confitura">Slides from Marcin Grzejszczak&#8217;s talk about Accurest</a></p>
</li>
<li>
<p><a href="http://toomuchcoding.com/blog/categories/accurest/">Accurest related articles from Marcin Grzejszczak&#8217;s blog</a></p>
</li>
<li>
<p><a href="http://toomuchcoding.com/blog/categories/spring-cloud-contract/">Spring Cloud Contract related articles from Marcin Grzejszczak&#8217;s blog</a></p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_samples">Samples</h3>
<div class="paragraph">
<p>Here you can find some <a href="https://github.com/spring-cloud/spring-cloud-contract/tree/master/samples/">samples</a>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_why_use_spring_cloud_contract_verifier_and_not_x">Why use Spring Cloud Contract Verifier and not X ?</h3>
<div class="paragraph">
<p>For the time being Spring Cloud Contract Verifier is a JVM based tool. So it could be your first pick when you&#8217;re already creating
software for the JVM. This project has a lot of really interesting features but especially quite a few of them definitely make
Spring Cloud Contract Verifier stand out on the "market" of Consumer Driven Contract (CDC) tooling. Out of many the most interesting are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Possibility to do CDC with messaging</p>
</li>
<li>
<p>Clear and easy to use, statically typed DSL</p>
</li>
<li>
<p>Possibility to copy paste your current JSON file to the contract and only edit its elements</p>
</li>
<li>
<p>Automatic generation of tests from the defined Contract</p>
</li>
<li>
<p>Stub Runner functionality - the stubs are automatically downloaded at runtime from Nexus / Artifactory</p>
</li>
<li>
<p>Spring Cloud integration - no discovery service is needed for integration tests</p>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_contract_dsl">Contract DSL</h2>
<div class="sectionbody">
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<div class="title">Important</div>
</td>
<td class="content">
Remember that inside the contract file you have to provide the fully qualified name to
the <code>Contract</code> class and the <code>make</code> static import i.e. <code>org.springframework.cloud.spec.Contract.make { &#8230;&#8203; }</code>.
You can also provide an import to the <code>Contract</code> class <code>import org.springframework.cloud.spec.Contract</code> and then call
<code>Contract.make { &#8230;&#8203; }</code>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Contract DSL is written in Groovy, but don&#8217;t be alarmed if you didn&#8217;t use Groovy before. Knowledge of the language is not really needed as our DSL uses only
a tiny subset of it (namely literals, method calls and closures). What&#8217;s more the DSL is designed to be programmer-readable without any knowledge of the DSL itself -
it&#8217;s statically typed.</p>
</div>
<div class="paragraph">
<p>The Contract is present in the <code>spring-cloud-contract-spec</code> module of the Spring Cloud Contract Verifier repository.</p>
</div>
<div class="paragraph">
<p>Let&#8217;s look at full example of a contract definition.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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": "http://api.twitter.com/1/geo/id/01fbe706f872cb32.json"
}
}]
'''
}
response {
status 200
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Not all features of the DSL are used in example above. If you didn&#8217;t find what you are looking for, please check next paragraphs on this page.</p>
</div>
<div class="quoteblock">
<blockquote>
<div class="paragraph">
<p>You can easily compile Contracts to WireMock stubs mapping using standalone maven command: <code>mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert</code>.</p>
</div>
</blockquote>
</div>
<div class="sect2">
<h3 id="_limitations">Limitations</h3>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
Spring Cloud Contract Verifier doesn&#8217;t support XML properly. Please use JSON or help us implement this feature.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
Spring Cloud Contract Verifier supports equality check on text response. Regular expressions are not yet available.
</td>
</tr>
</table>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
The support for the verification of size of JSON arrays is experimental. If you want to turn it on please provide
the value of a system property <code>spring.cloud.contract.verifier.assert.size</code> equal to <code>true</code>. By default this feature is set to
<code>false</code>. You can also provide the <code>assertJsonSize</code> property in the plugin configuration.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_http_top_level_elements">HTTP Top-Level Elements</h3>
<div class="paragraph">
<p>Following methods can be called in the top-level closure of a contract definition. Request and response are mandatory, priority is optional.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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 {
//...
}
// 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 {
//...
}
// Contract priority, which can be used for overriding
// contracts (1 is highest). Priority is optional.
priority 1
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_request">Request</h3>
<div class="paragraph">
<p>HTTP protocol requires only <strong>method and address</strong> to be specified in a request. The same information is mandatory in request definition of the Contract.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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 {
//...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It is possible to specify whole <code>url</code> instead of just path, but <code>urlPath</code> is the recommended way as it makes the tests <strong>host-independent</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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 {
//...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Request may contain <strong>query parameters</strong>, which are specified in a closure nested in a call to <code>urlPath</code> or <code>url</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
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(stub(containing("[mf]")), server('mf'))
// `matching` function tests parameter
// against passed regular expression.
parameter 'offset': value(stub(matching("[0-9]+")), server(123))
// `notMatching` functions tests if parameter
// does not match passed regular expression.
parameter 'loginStartsWith': value(stub(notMatching(".{0,2}")), server(3))
}
}
//...
}
response {
//...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It may contain additional <strong>request headers</strong>&#8230;&#8203;</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
// Each header is added in form `'Header-Name' : 'Header-Value'`.
headers {
header 'Content-Type': 'application/json'
}
//...
}
response {
//...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>&#8230;&#8203;and a <strong>request body</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
// JSON and XML formats of request body are supported.
// Format will be determined from a header or body's content.
body '''{ "login" : "john", "name": "John The Contract" }'''
}
response {
//...
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Body&#8217;s format</strong> can also be specified explicitly by invoking one of format functions.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
// In this case body will be formatted as XML.
body equalToXml(
'''&lt;user&gt;&lt;login&gt;john&lt;/login&gt;&lt;name&gt;John The Contract&lt;/name&gt;&lt;/user&gt;'''
)
}
response {
//...
}
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_response">Response</h3>
<div class="paragraph">
<p>Minimal response must contain <strong>HTTP status code</strong>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
//...
}
response {
// Status code sent by the server
// in response to request specified above.
status 200
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Besides status response may contain <strong>headers</strong> and <strong>body</strong>, which are specified the same way as in the request (see previous paragraph).</p>
</div>
</div>
<div class="sect2">
<h3 id="_regular_expressions">Regular expressions</h3>
<div class="paragraph">
<p>You can use regular expressions to write your requests in Contract DSL. It is particularly useful when you want to indicate that a given response
should be provided for requests that follow a given pattern. Also, you can use it when you need to use patterns and not exact values both
for your test and your server side tests.</p>
</div>
<div class="paragraph">
<p>Please see the example below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method('GET')
url $(client(~/\/[0-9]{2}/), server('/12'))
}
response {
status 200
body(
id: value(
client('123'),
server(regex('[0-9]+'))
),
surname: $(
client('Kowalsky'),
server('Lewandowski')
),
name: 'Jan',
created: $(client('2014-02-02 12:23:43'), server(execute('currentDate(it)'))),
correlationId: value(client('5d1f9fef-e0dc-4f3d-a7e4-72d2220dd827'),
server(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 using a regular expression. If you do that then automatically we&#8217;ll
provide the generated string that matches the provided regular expression. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url '/foo'
body([
requestElement: value(client(regex('[0-9]{5}')))
])
}
response {
status 200
body([
responseElement: value(server(regex('[0-9]{7}')))
])
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this example for request and response the opposite side of the communication will have the respective data generated.</p>
</div>
</div>
<div class="sect2">
<h3 id="_passing_optional_parameters">Passing optional parameters</h3>
<div class="paragraph">
<p>It is possible to provide optional parameters in your contract. It&#8217;s only possible to have optional parameter for the:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><em>STUB</em> side of the Request</p>
</li>
<li>
<p><em>TEST</em> side of the Response</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
priority 1
request {
method 'POST'
url '/users/password'
headers {
header 'Content-Type': 'application/json'
}
body(
email: $(stub(optional(regex(email()))), test('abc@abc.com')),
callback_url: $(stub(regex(hostname())), test('http://partners.com'))
)
}
response {
status 404
headers {
header 'Content-Type': 'application/json'
}
body(
code: value(stub("123123"), test(optional("123123")))
)
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>By wrapping a part of the body with the <code>optional()</code> method you are in fact creating a regular expression that should be present 0 or more times.</p>
</div>
<div class="paragraph">
<p>That way for the example above the following test would be generated if you pick Spock:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">"""
given:
def request = given()
.header('Content-Type', 'application/json')
.body('''{"email":"abc@abc.com","callback_url":"http://partners.com"}''')
when:
def response = given().spec(request)
.post("/users/password")
then:
response.statusCode == 404
response.header('Content-Type') == 'application/json'
and:
DocumentContext parsedJson = JsonPath.parse(response.body.asString())
assertThatJson(parsedJson).field("code").matches("(123123)?")
"""</code></pre>
</div>
</div>
<div class="paragraph">
<p>and the following stub:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">'''
{
"request" : {
"url" : "/users/password",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.email =~ /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4})?/)]"
}, {
"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="sect2">
<h3 id="_executing_custom_methods_on_server_side">Executing custom methods on server side</h3>
<div class="paragraph">
<p>It is also possible to define a method call to be executed on the server side during the test. Such a method can be added to the class defined as "baseClassForTests"
in the configuration. Please see the examples below:</p>
</div>
<div class="sect3">
<h4 id="_contract_dsl_2">Contract DSL</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud.contract.spec.Contract.make {
request {
method 'PUT'
url $(client(regex('^/api/[0-9]{2}$')), server('/api/12'))
headers {
header 'Content-Type': 'application/json'
}
body '''\
[{
"text": "Gonna see you at Warsaw"
}]
'''
}
response {
body (
path: $(client('/api/12'), server(regex('^/api/[0-9]{2}$'))),
correlationId: $(client('1223456'), server(execute('isProperCorrelationId($it)')))
)
status 200
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_base_mock_spec">Base Mock Spec</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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>
</div>
<div class="sect2">
<h3 id="_jax_rs_support">JAX-RS support</h3>
<div class="paragraph">
<p>Starting with release 0.8.0 we support JAX-RS 2 Client API. Base class needs to define <code>protected WebTarget webTarget</code> and server initialization, right now the only option how to test JAX-RS API is to start a web server.</p>
</div>
<div class="paragraph">
<p>Request with a body needs to have a content type set otherwise <code>application/octet-stream</code> is going to be 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="highlight"><code class="language-groovy" data-lang="groovy">testMode == 'JAXRSCLIENT'</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of a test API generated:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
// 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()
.method("GET");
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>
<div class="sect2">
<h3 id="_messaging_top_level_elements">Messaging Top-Level Elements</h3>
<div class="paragraph">
<p>The DSL for messaging looks a little bit different than the one that focuses on HTTP.</p>
</div>
<div class="sect3">
<h4 id="_output_triggered_by_a_method">Output triggered by a method</h4>
<div class="paragraph">
<p>The output message can be triggered by calling a method (e.g. a Scheduler was started and a message was sent)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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="paragraph">
<p>In this case the output message will be sent to <code>output</code> if a method called <code>bookReturnedTriggered</code> will be executed. In the message <strong>publisher&#8217;s</strong> side
we will generate a test that will call that method to trigger the message. On the <strong>consumer</strong> side you can use the <code>some_label</code> to trigger the message.</p>
</div>
</div>
<div class="sect3">
<h4 id="_output_triggered_by_a_message">Output triggered by a message</h4>
<div class="paragraph">
<p>The output message can be triggered by receiving a message.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" 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="paragraph">
<p>In this case the output message will be sent to <code>output</code> if a proper message will be received on the <code>input</code> destination. In the message <strong>publisher&#8217;s</strong> side
we will generate a test that will send the input message to the defined destination. On the <strong>consumer</strong> side you can either send a message to the input
destination or use the <code>some_label</code> to trigger the message.</p>
</div>
</div>
<div class="sect3">
<h4 id="_consumer_producer">Consumer / Producer</h4>
<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 use them also in messaging but we&#8217;re providing also the <code>consumer</code> and <code>produer</code> methods
as presented below (note 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="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
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>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier_http">Spring Cloud Contract Verifier HTTP</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_gradle_project">Gradle Project</h3>
<div class="sect3">
<h4 id="_prerequisites">Prerequisites</h4>
<div class="paragraph">
<p>In order to use Spring Cloud Contract Verifier with WireMock you have to use gradle or maven plugin.</p>
</div>
<div class="sect4">
<h5 id="_add_gradle_plugin">Add gradle plugin</h5>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}'
}
}
apply plugin: 'groovy'
apply plugin: 'contract-verifier'
dependencies {
testCompile 'org.codehaus.groovy:groovy-all:2.4.6'
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'com.jayway.restassured:spring-mock-mvc:2.9.0' // needed if you're going to use Spring MockMvc
}</code></pre>
</div>
</div>
<div class="sect5">
<h6 id="_snapshot_versions">Snapshot versions</h6>
<div class="paragraph">
<p>Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">repositories {
(...)
//Required only for SNAPSHOT versions
maven { url "https://repo.spring.io/plugins-snapshot-local" }
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_add_maven_plugin">Add maven plugin</h5>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;goal&gt;generateStubs&lt;/goal&gt;
&lt;goal&gt;generateTests&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Read more: <a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/">spring-cloud-contract-maven-plugin</a></p>
</div>
</div>
<div class="sect4">
<h5 id="_add_stubs">Add stubs</h5>
<div class="paragraph">
<p>By default Spring Cloud Contract Verifier is looking for stubs in <code>src/test/resources/contracts</code> directory.</p>
</div>
<div class="paragraph">
<p>Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test.
We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
So with following structure</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier will create test class <code>defaultBasePackage.MyService</code> with two methods</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>shouldCreateUser()</code></p>
</li>
<li>
<p><code>shouldReturnUser()</code></p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_run_plugin">Run plugin</h4>
<div class="paragraph">
<p>Plugin registers itself to be invoked before <code>check</code> task. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke <code>generateContractTests</code> task.</p>
</div>
</div>
<div class="sect3">
<h4 id="_default_setup">Default setup</h4>
<div class="paragraph">
<p>Default Gradle Plugin setup creates the following Gradle part of the build (it&#8217;s a pseudocode)</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">contractVerifier {
targetFramework = 'JUNIT'
testMode = 'MockMvc'
generatedTestSourcesDir = project.file("${project.buildDir}/generated-test-sources/contracts")
contractsDslDir = "${project.rootDir}/src/test/resources/contracts"
basePackageForTests = 'org.springframework.cloud.verifier.tests'
stubsOutputDir = project.file("${project.buildDir}/stubs")
}
tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateWireMockClientStubs') {
baseName = project.name
classifier = contractVerifier.stubsSuffix
from contractVerifier.stubsOutputDir
}
project.artifacts {
archives task
}
tasks.create(type: Copy, name: 'copyContracts') {
from contractVerifier.contractsDslDir
into contractVerifier.stubsOutputDir
}
verifierStubsJar.dependsOn 'copyContracts'
publishing {
publications {
stubs(MavenPublication) {
artifactId project.name
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_configure_plugin">Configure plugin</h4>
<div class="paragraph">
<p>To change default configuration just add <code>contractVerifier</code> snippet to your Gradle config</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">contractVerifier {
testMode = 'MockMvc'
baseClassForTests = 'org.mycompany.tests'
generatedTestSourcesDir = project.file('src/generatedContract')
}</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_configuration_options">Configuration options</h5>
<div class="ulist">
<ul>
<li>
<p><strong>testMode</strong> - defines mode for acceptance tests. By default MockMvc which is based on Spring&#8217;s MockMvc. It can also be changed to <strong>JaxRsClient</strong> or to <strong>Explicit</strong> for real HTTP calls.</p>
</li>
<li>
<p><strong>imports</strong> - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []</p>
</li>
<li>
<p><strong>staticImports</strong> - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []</p>
</li>
<li>
<p><strong>basePackageForTests</strong> - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests</p>
</li>
<li>
<p><strong>baseClassForTests</strong> - base class for generated tests. By default <code>spock.lang.Specification</code> if using Spock tests.</p>
</li>
<li>
<p><strong>ruleClassForTests</strong> - specifies Rule which should be added to generated test classes.</p>
</li>
<li>
<p><strong>ignoredFiles</strong> - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []</p>
</li>
<li>
<p><strong>contractsDslDir</strong> - directory containing contracts written using the GroovyDSL. By default <code>$rootDir/src/test/resources/contracts</code></p>
</li>
<li>
<p><strong>generatedTestSourcesDir</strong> - test source directory where tests generated from Groovy DSL should be placed. By default <code>$buildDir/generated-test-sources/contractVerifier</code></p>
</li>
<li>
<p><strong>stubsOutputDir</strong> - dir where the generated WireMock stubs from Groovy DSL should be placed</p>
</li>
<li>
<p><strong>targetFramework</strong> - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework</p>
</li>
</ul>
</div>
</div>
<div class="sect4">
<h5 id="_base_class_for_tests">Base class for tests</h5>
<div class="paragraph">
<p>When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">abstract class BaseMockMvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
}
void isProperCorrelationId(Integer correlationId) {
assert correlationId == 123456
}
void isEmpty(String value) {
assert value == null
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In case of using <code>Explicit</code> mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of <code>JAXRSCLIENT</code> mode this base class
should also contain <code>protected WebTarget webTarget</code> field, right now the only option to test JAX-RS API is to start a web server.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_invoking_generated_tests">Invoking generated tests</h4>
<div class="paragraph">
<p>To ensure that provider side is complaint with defined contracts, you need to invoke:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">./gradlew generateContractTests test</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_spring_cloud_contract_verifier_on_consumer_side">Spring Cloud Contract Verifier on consumer side</h4>
<div class="paragraph">
<p>In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. If you don&#8217;t want to use Stub Runner then you need to copy contracts stored in
<code>src/test/resources/contracts</code> and generate WireMock json stubs using:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">./gradlew generateWireMockClientStubs</code></pre>
</div>
</div>
<div class="paragraph">
<p>Note that <code>stubsOutputDir</code> option has to be set for stub generation to work.</p>
</div>
<div class="paragraph">
<p>When present, json stubs can be used in consumer automated tests.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
class LoanApplicationServiceSpec extends Specification {
@ClassRule
@Shared
WireMockClassRule wireMockRule == new WireMockClassRule()
@Autowired
LoanApplicationService sut
def 'should successfully apply for loan'() {
given:
LoanApplication application =
new LoanApplication(client: new Client(pesel: '12345678901'), amount: 123.123)
when:
LoanApplicationResult loanApplication == sut.loanApplication(application)
then:
loanApplication.loanApplicationStatus === LoanApplicationStatus.LOAN_APPLIED
loanApplication.rejectionReason === null
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Underneath LoanApplication makes a call to FraudDetection service. This request is handled by Wiremock server configured using stubs generated by Spring Cloud Contract Verifier.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_in_your_maven_project">Using in your Maven project</h3>
<div class="sect3">
<h4 id="_add_maven_plugin_2">Add maven plugin</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud.verifier&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;goal&gt;generateStubs&lt;/goal&gt;
&lt;goal&gt;generateTests&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Read more: <a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/">spring-cloud-contract-maven-plugin</a></p>
</div>
</div>
<div class="sect3">
<h4 id="_add_stubs_2">Add stubs</h4>
<div class="paragraph">
<p>By default Spring Cloud Contract Verifier is looking for stubs in <code>src/test/resources/contracts</code> directory.
Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test.
We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name.
So with following structure</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">src/test/resources/contracts/myservice/shouldCreateUser.groovy
src/test/resources/contracts/myservice/shouldReturnUser.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier will create test class <code>defaultBasePackage.MyService</code> with two methods
- <code>shouldCreateUser()</code>
- <code>shouldReturnUser()</code></p>
</div>
</div>
<div class="sect3">
<h4 id="_run_plugin_2">Run plugin</h4>
<div class="paragraph">
<p>Plugin goal <code>generateTests</code> is assigned to be invoked in phase <code>generate-test-sources</code>. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke <code>generateTests</code> goal.</p>
</div>
</div>
<div class="sect3">
<h4 id="_configure_plugin_2">Configure plugin</h4>
<div class="paragraph">
<p>To change default configuration just add <code>configuration</code> section to plugin definition or <code>execution</code> definition.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud.verifier&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;goal&gt;generateStubs&lt;/goal&gt;
&lt;goal&gt;generateTests&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;configuration&gt;
&lt;basePackageForTests&gt;org.springframework.cloud.verifier.twitter.place&lt;/basePackageForTests&gt;
&lt;baseClassForTests&gt;org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec&lt;/baseClassForTests&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_important_configuration_options">Important configuration options</h5>
<div class="ulist">
<ul>
<li>
<p><strong>testMode</strong> - defines mode for acceptance tests. By default <code>MockMvc</code> which is based on Spring&#8217;s MockMvc. It can also be changed to <code>JaxRsClient</code> or to <code>Explicit</code> for real HTTP calls.</p>
</li>
<li>
<p><strong>basePackageForTests</strong> - specifies base package for all generated tests. By default set to <code>org.springframework.cloud.verifier.tests</code>.</p>
</li>
<li>
<p><strong>ruleClassForTests</strong> - specifies Rule which should be added to generated test classes.</p>
</li>
<li>
<p><strong>baseClassForTests</strong> - base class for generated tests. By default <code>spock.lang.Specification</code> if using Spock tests.</p>
</li>
<li>
<p><strong>contractsDir</strong> - directory containing contracts written using the GroovyDSL. By default <code>/src/test/resources/contracts</code>.</p>
</li>
<li>
<p><strong>testFramework</strong> - the target test framework to be used; currently Spock and JUnit are supported with Spock being the default framework</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For complete information take a look at <a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/plugin-info.html">Plugin Documentation</a></p>
</div>
</div>
<div class="sect4">
<h5 id="_base_class_for_tests_2">Base class for tests</h5>
<div class="literalblock">
<div class="content">
<pre>When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified.</pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">package org.mycompany.tests
import org.mycompany.ExampleSpringController
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc
import spock.lang.Specification
class MvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new ExampleSpringController())
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>In case of using <code>Explicit</code> mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of <code>JAXRSCLIENT</code> mode this base class should also contain <code>protected WebTarget webTarget</code> field, right now the only option to test JAX-RS API is to start a web server.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_invoking_generated_tests_2">Invoking generated tests</h4>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Maven Plugins generates verification code into directory <code>/generated-test-sources/contractVerifier</code> and attach this directory to <code>testCompile</code> goal.</p>
</div>
<div class="paragraph">
<p>For Groovy Spock code use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt;
&lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt;
&lt;version&gt;1.5&lt;/version&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;testCompile&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;configuration&gt;
&lt;testSources&gt;
&lt;testSource&gt;
&lt;directory&gt;${project.basedir}/src/test/groovy&lt;/directory&gt;
&lt;includes&gt;
&lt;include&gt;**/*.groovy&lt;/include&gt;
&lt;/includes&gt;
&lt;/testSource&gt;
&lt;testSource&gt;
&lt;directory&gt;${project.build.directory}/generated-test-sources/contractVerifier&lt;/directory&gt;
&lt;includes&gt;
&lt;include&gt;**/*.groovy&lt;/include&gt;
&lt;/includes&gt;
&lt;/testSource&gt;
&lt;/testSources&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>To ensure that provider side is complaint with defined contracts, you need to invoke <code>mvn generateTest test</code></p>
</div>
</div>
<div class="sect3">
<h4 id="_spring_cloud_contract_verifier_on_consumer_side_2">Spring Cloud Contract Verifier on consumer side</h4>
<div class="paragraph">
<p>In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. You need to copy contracts stored in <code>src/test/resources/contracts</code> and generate Wiremock json stubs using: <code>mvn generateStubs</code> command. By default generated WireMock mapping is stored in directory <code>target/mappings</code>. Your project should create from this generated mappings additional artifact with classifier <code>stubs</code> for easy deploy to maven repository.</p>
</div>
<div class="paragraph">
<p>Sample configuration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.cloud.verifier&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-contract-maven-plugin&lt;/artifactId&gt;
&lt;version&gt;${verifier-plugin.version}&lt;/version&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;goals&gt;
&lt;goal&gt;convert&lt;/goal&gt;
&lt;goal&gt;generateStubs&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>When present, json stubs can be used in consumer automated tests.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">@ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
class LoanApplicationServiceSpec extends Specification {
@ClassRule
@Shared
WireMockClassRule wireMockRule == new WireMockClassRule()
@Autowired
LoanApplicationService sut
def 'should successfully apply for loan'() {
given:
LoanApplication application =
new LoanApplication(client: new Client(pesel: '12345678901'), amount: 123.123)
when:
LoanApplicationResult loanApplication == sut.loanApplication(application)
then:
loanApplication.loanApplicationStatus === LoanApplicationStatus.LOAN_APPLIED
loanApplication.rejectionReason === null
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Underneath LoanApplication makes a call to FraudDetection service. This request is handled by Wiremock server configured using stubs generated by Spring Cloud Contract Verifier.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_scenarios">Scenarios</h3>
<div class="paragraph">
<p>It&#8217;s possible to handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to proper naming convention while creating your contracts. The convention requires to include order number followed by the underscore.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>my_contracts_dir\
scenario1\
1_login.groovy
2_showCart.groovy
3_logout.groovy</code></pre>
</div>
</div>
<div class="paragraph">
<p>Such tree will cause Spring Cloud Contract Verifier generating Wiremock&#8217;s scenario with name <code>scenario1</code> and three steps:
- login marked as <code>Started</code> pointing to:
- showCart marked as <code>Step1</code> pointing to:
- logout marked as <code>Step2</code> which will close the scenario.
More details about Wiremock scenarios can be found under <a href="http://wiremock.org/stateful-behaviour.html">http://wiremock.org/stateful-behaviour.html</a></p>
</div>
<div class="paragraph">
<p>Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_verifier_messaging">Spring Cloud Contract Verifier Messaging</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Contract Verifier allows you to verify your application that uses messaging as means of communication.
All of our integrations are working with Spring but you can also set one yourself.</p>
</div>
<div class="sect2">
<h3 id="_integrations">Integrations</h3>
<div class="paragraph">
<p>You can use one of the three 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>
</ul>
</div>
<div class="paragraph">
<p>If you&#8217;re using Spring Boot, the aforementioned test configurations will be appended automatically.</p>
</div>
<div class="paragraph">
<p>You have to provide as a dependency one of the Spring Cloud Contract Verifier Messaging modules. Example for Gradle:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">// for Apache Camel
testCompile "org.springframework.cloud:spring-cloud-contract-verifier-camel:${verifierVersion}"
// for Spring Integration
testCompile "org.springframework.cloud:spring-cloud-contract-verifier-integration:${verifierVersion}"
// for Spring Cloud Stream
testCompile "org.springframework.cloud:spring-cloud-contract-verifier-stream:${verifierVersion}"</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_manual_integration">Manual Integration</h3>
<div class="paragraph">
<p>The <code>spring-cloud-contract-verifier-messaging-core</code> module contains 3 main interfaces:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>ContractVerifierMessage</code> - describes a message received / sent to a channel / queue / topic etc.</p>
</li>
<li>
<p><code>ContractVerifierMessageBuilder</code> - describes how to build a message</p>
</li>
<li>
<p><code>ContractVerifierMessaging</code> - class that allows you to build, send and receive messages</p>
</li>
<li>
<p><code>ContractVerifierFilter</code> - interface to filter out the messages that do not follow the pattern from the DSL</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>In the generated test the <code>ContractVerifierMessaging</code> is injected via <code>@Inject</code> annotation thus you can use other injection
frameworks than Spring.</p>
</div>
<div class="paragraph">
<p>You have to provide as a dependency the <code>spring-cloud-contract-verifier-messaging-core</code> module. Example for Gradle:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">testCompile "org.springframework.cloud:spring-cloud-contract-verifier-messaging-core:${verifierVersion}"</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_publisher_side_test_generation">Publisher side test generation</h3>
<div class="paragraph">
<p>Having the <code>input</code> or <code>outputMessage</code> sections in your DSL will result in creation of tests on the publisher&#8217;s side. By default
JUnit tests will be created, however there is also a possibility to create Spock tests.</p>
</div>
<div class="paragraph">
<p>There are 3 main scenarios that we should take into consideration:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Scenario 1: there is no input message that produces an output one. The output message is triggered by a component
inside the application (e.g. 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="sect3">
<h4 id="_scenario_1_no_input_message">Scenario 1 (no input message)</h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">def contractDsl = Contract.make {
label 'some_label'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('activemq:output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following JUnit test will be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
// when:
bookReturnedTriggered();
// then:
ContractVerifierMessage response = contractVerifierMessaging.receiveMessage("activemq:output");
assertThat(response).isNotNull();
assertThat(response.getHeader("BOOK-NAME")).isEqualTo("foo");
// and:
DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
'''</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
when:
bookReturnedTriggered()
then:
def response = contractVerifierMessaging.receiveMessage('activemq:output')
assert response != null
response.getHeader('BOOK-NAME') == 'foo'
and:
DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
'''</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_scenario_2_output_triggered_by_input">Scenario 2 (output triggered by input)</h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">def contractDsl = Contract.make {
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="paragraph">
<p>The following JUnit test will be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
// given:
ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
"{\\"bookName\\":\\"foo\\"}"
, headers()
.header("sample", "header"));
// when:
contractVerifierMessaging.send(inputMessage, "jms:input");
// then:
ContractVerifierMessage response = contractVerifierMessaging.receiveMessage("jms:output");
assertThat(response).isNotNull();
assertThat(response.getHeader("BOOK-NAME")).isEqualTo("foo");
// and:
DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
'''</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">"""\
given:
def inputMessage = contractVerifierMessaging.create(
'''{"bookName":"foo"}''',
['sample': 'header']
)
when:
contractVerifierMessaging.send(inputMessage, 'jms:input')
then:
def response = contractVerifierMessaging.receiveMessage('jms:output')
assert response !- null
response.getHeader('BOOK-NAME') == 'foo'
and:
DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
"""</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_scenario_3_no_output_message">Scenario 3 (no output message)</h4>
<div class="paragraph">
<p>For the given contract:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">def contractDsl = Contract.make {
label 'some_label'
input {
messageFrom('jms:delete')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
assertThat('bookWasDeleted()')
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The following JUnit test will be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
// given:
ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
"{\\"bookName\\":\\"foo\\"}"
, headers()
.header("sample", "header"));
// when:
contractVerifierMessaging.send(inputMessage, "jms:delete");
// then:
bookWasDeleted();
'''</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the following Spock test would be created:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">'''
given:
def inputMessage = contractVerifierMessaging.create(
\'\'\'{"bookName":"foo"}\'\'\',
['sample': 'header']
)
when:
contractVerifierMessaging.send(inputMessage, 'jms:delete')
then:
noExceptionThrown()
bookWasDeleted()
'''</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_consumer_stub_side_generation">Consumer Stub Side generation</h3>
<div class="paragraph">
<p>Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it&#8217;s parsed on the consumer side
and proper stubbed routes are created.</p>
</div>
<div class="paragraph">
<p>For more infromation please consult the Stub Runner Messaging sections.</p>
</div>
<div class="sect3">
<h4 id="_gradle_setup">Gradle Setup</h4>
<div class="paragraph">
<p>Example of Spring Cloud Contract Verifier Gradle setup:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
// Automatically added by plugin:
// copyContracts - copies contracts to the output folder from which JAR will be created
// verifierStubsJar - JAR with a provided stub suffix
// the presented publication is also added by the plugin but you can modify it as you wish
publishing {
publications {
stubs(MavenPublication) {
artifactId "${project.name}-stubs"
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_maven_setup">Maven Setup</h4>
<div class="paragraph">
<p>Example of Maven can be found in the <a href="https://github.com/spring-cloud/spring-cloud-contract/">Spring Cloud Contract Verifier README</a></p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_stub_runner">Spring Cloud Contract Stub Runner</h2>
<div class="sectionbody">
<div class="paragraph">
<p>One of the issues that you could have encountered while using Spring Cloud Contract Verifier was to pass the generated WireMock JSON stubs from the server side to the client side (or various clients).
The same takes place in terms of client side generation for messaging.</p>
</div>
<div class="paragraph">
<p>Copying the JSON files / setting the client side for messaging manually is out of the question.</p>
</div>
<div class="sect2">
<h3 id="_snapshot_versions_2">Snapshot versions</h3>
<div class="paragraph">
<p>Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">repositories {
(...)
//Required only for SNAPSHOT versions
maven { url "https://repo.spring.io/libs-snapshot-local" }
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_publishing_stubs_as_jars">Publishing stubs as JARs</h3>
<div class="paragraph">
<p>The easiest approach would be to centralize the way stubs are kept. For example you can keep them as JARs in a Maven repository.</p>
</div>
<div class="sect3">
<h4 id="_gradle">Gradle</h4>
<div class="paragraph">
<p>Example of Spring Cloud Contract Verifier Gradle setup:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ext {
contractsDir = file("mappings")
stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
}
// Automatically added by plugin:
// copyContracts - copies contracts to the output folder from which JAR will be created
// verifierStubsJar - JAR with a provided stub suffix
// the presented publication is also added by the plugin but you can modify it as you wish
publishing {
publications {
stubs(MavenPublication) {
artifactId "${project.name}-stubs"
artifact verifierStubsJar
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_maven">Maven</h4>
<div class="paragraph">
<p>Example of Maven can be found in the <a href="https://github.com/spring-cloud/spring-cloud-contract/">Spring Cloud Contract Verifier README</a></p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_modules">Modules</h3>
<div class="paragraph">
<p>Spring Cloud Contract Stub Runner comes with a new structure of modules</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code>└── spring-cloud-contract-stub-runner
├── spring-cloud-contract-stub-runner
├── spring-cloud-contract-stub-runner-boot
├── spring-cloud-contract-stub-runner-junit
├── spring-cloud-contract-stub-runner-spring
└── spring-cloud-contract-stub-runner-spring-cloud</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_core">Stub Runner Core</h3>
<div class="paragraph">
<p>Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of
<a href="http://martinfowler.com/articles/consumerDrivenContracts.html">Consumer Driven Contracts</a>.</p>
</div>
<div class="paragraph">
<p>Stub Runner allows you to automatically download the stubs of the provided dependencies, start WireMock servers for them and feed them with proper stub definitions.
For messaging, special stub routes are defined.</p>
</div>
<div class="sect3">
<h4 id="_running_stubs">Running stubs</h4>
<div class="sect4">
<h5 id="_running_using_main_app">Running using main app</h5>
<div class="paragraph">
<p>You can set the following options to the main class:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">-maxp (--maxPort) N : Maximum port value to be assigned to the
Wiremock instance. Defaults to 15000
(default: 15000)
-minp (--minPort) N : Minimal port value to be assigned to the
Wiremock instance. Defaults to 10000
(default: 10000)
-s (--stubs) VAL : Comma separated list of Ivy representation of
jars with stubs. Eg. groupid:artifactid1,group
id2:artifactid2:version:classifier
-sr (--stubRepositoryRoot) VAL : Location of a Jar containing server where you
keep your stubs (e.g. http://nexus.net/content
/repositories/repository)
-ss (--stubsSuffix) VAL : Suffix for the jar containing stubs (e.g.
'stubs' if the stub jar would have a 'stubs'
classifier for stubs: foobar-stubs ).
Defaults to 'stubs' (default: stubs)
-wo (--workOffline) : Switch to work offline. Defaults to 'false'
(default: false)</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_http_stubs">HTTP Stubs</h5>
<div class="paragraph">
<p>Stubs are defined in JSON documents, whose syntax is defined in <a href="http://wiremock.org/stubbing.html">WireMock documentation</a></p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-javascript" data-lang="javascript">{
"request": {
"method": "GET",
"url": "/ping"
},
"response": {
"status": 200,
"body": "pong",
"headers": {
"Content-Type": "text/plain"
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_viewing_registered_mappings">Viewing registered mappings</h5>
<div class="paragraph">
<p>Every stubbed collaborator exposes list of defined mappings under <code>__/admin/</code> endpoint.</p>
</div>
</div>
<div class="sect4">
<h5 id="_messaging_stubs">Messaging Stubs</h5>
<div class="paragraph">
<p>Depending on the provided Stub Runner dependency and the DSL the messaging routes are automatically set up.</p>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_boot">Stub Runner Boot</h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner Boot is a Spring Boot application that exposes REST endpoints to
trigger the messaging labels and to access started WireMock servers.</p>
</div>
<div class="paragraph">
<p>One of the usecases is to run some smoke (end to end) tests on a deployed application. You can read
more about this in the <a href="http://toomuchcoding.com/blog/2015/09/27/microservice-deployment/">"Microservice Deployment" article at Too Much Coding blog.</a></p>
</div>
<div class="sect3">
<h4 id="_how_to_use_it">How to use it?</h4>
<div class="paragraph">
<p>Just add the</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">compile "org.springframework.cloud:stub-runner-boot:${verifierVersion}"</code></pre>
</div>
</div>
<div class="paragraph">
<p>and a messaging implementation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">// for Apache Camel
compile "org.springframework.cloud:spring-cloud-contract-stub-runner-camel:${verifierVersion}"
// for Spring Integration
compile "org.springframework.cloud:spring-cloud-contract-stub-runner-integration:${verifierVersion}"
// for Spring Cloud Stream
compile "org.springframework.cloud:spring-cloud-contract-stub-runner-stream:${verifierVersion}"</code></pre>
</div>
</div>
<div class="paragraph">
<p>Build a fat-jar and you&#8217;re ready to go!</p>
</div>
<div class="paragraph">
<p>For the properties check the <strong>Stub Runner Spring</strong> section.</p>
</div>
</div>
<div class="sect3">
<h4 id="_endpoints">Endpoints</h4>
<div class="sect4">
<h5 id="_http">HTTP</h5>
<div class="ulist">
<ul>
<li>
<p>GET <code>/stubs</code> - returns a list of all running stubs in <code>ivy:integer</code> notation</p>
</li>
<li>
<p>GET <code>/stubs/{ivy}</code> - returns a port for the given <code>ivy</code> notation (when calling the endpoint <code>ivy</code> can also be <code>artifactId</code> only)</p>
</li>
</ul>
</div>
</div>
<div class="sect4">
<h5 id="_messaging">Messaging</h5>
<div class="paragraph">
<p>For Messaging</p>
</div>
<div class="ulist">
<ul>
<li>
<p>GET <code>/triggers</code> - returns a list of all running labels in <code>ivy : [ label1, label2 &#8230;&#8203;]</code> notation</p>
</li>
<li>
<p>POST <code>/triggers/{label}</code> - executes a trigger with <code>label</code></p>
</li>
<li>
<p>POST <code>/triggers/{ivy}/{label}</code> - executes a trigger with <code>label</code> for the given <code>ivy</code> notation (when calling the endpoint <code>ivy</code> can also be <code>artifactId</code> only)</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_example">Example</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">@ContextConfiguration(classes = [StubRunnerBootSpec, StubRunnerBoot], loader = SpringBootContextLoader)
@EnableBinding
@Configuration
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
response.body.as(Integer) &gt; 0
where:
stubId &lt;&lt; ['org.springframework.cloud.contract.verifier.stubs:bootService:+:stubs',
'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs',
'org.springframework.cloud.contract.verifier.stubs:bootService:+',
'org.springframework.cloud.contract.verifier.stubs:bootService',
'bootService']
}
def 'should return 404 when missing stub was called'() {
when:
def response = RestAssuredMockMvc.get("/stubs/a:b:c:d")
then:
response.statusCode == 404
}
def 'should return a list of messaging labels that can be triggered when version and classifier are passed'() {
when:
String response = RestAssuredMockMvc.get('/triggers').body.asString()
then:
def root = new JsonSlurper().parseText(response)
root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book","return_book_1","return_book_2"])
}
def 'should trigger a messaging label'() {
given:
StubRunning stubRunning = Mock()
RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
when:
def response = RestAssuredMockMvc.post("/triggers/delete_book")
then:
response.statusCode == 200
and:
1 * stubRunning.trigger('delete_book')
}
def 'should trigger a messaging label for a stub with [#stubId] ivy notation'() {
given:
StubRunning stubRunning = Mock()
RestAssuredMockMvc.standaloneSetup(new HttpStubsController(stubRunning), new TriggerController(stubRunning))
when:
def response = RestAssuredMockMvc.post("/triggers/$stubId/delete_book")
then:
response.statusCode == 200
and:
1 * stubRunning.trigger(stubId, 'delete_book')
where:
stubId &lt;&lt; ['org.springframework.cloud.contract.verifier.stubs:bootService:stubs', 'org.springframework.cloud.contract.verifier.stubs:bootService', 'bootService']
}
def 'should return when trigger is missing'() {
when:
def response = RestAssuredMockMvc.post("/triggers/missing_label")
then:
response.statusCode == 404
def root = new JsonSlurper().parseText(response.body.asString())
root.'org.springframework.cloud.contract.verifier.stubs:bootService:0.0.1-SNAPSHOT:stubs'?.containsAll(["delete_book","return_book_1","return_book_2"])
}
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_jetty">Stub Runner Jetty</h3>
<div class="paragraph">
<p>Convenience module that pulls together the dependencies needed to run the Stub Runner with WireMock, but without Spring Boot.</p>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_junit_rule">Stub Runner JUnit Rule</h3>
<div class="paragraph">
<p>Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@ClassRule public static StubRunnerRule rule = new StubRunnerRule()
.repoRoot(repoRoot())
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer");</code></pre>
</div>
</div>
<div class="paragraph">
<p>After that rule gets executed Stub Runner connects to your Maven repository and for the given list of dependencies tries to:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>download them</p>
</li>
<li>
<p>cache them locally</p>
</li>
<li>
<p>unzip them to a temporary folder</p>
</li>
<li>
<p>start a WireMock server for each Maven dependency on a random port from the provided range of ports / provided port</p>
</li>
<li>
<p>feed the WireMock server with all JSON files that are valid WireMock definitions</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Stub Runner uses <a href="https://wiki.eclipse.org/Aether">Eclipse Aether</a> mechanism to download the Maven dependencies.
Check their <a href="https://wiki.eclipse.org/Aether">docs</a> for more information.</p>
</div>
<div class="paragraph">
<p>Since the <code>StubRunnerRule</code> implements the <code>StubFinder</code> it allows you to find the started stubs:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">/*
* Copyright 2013-2016 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.stubrunner
import org.springframework.cloud.contract.spec.Contract
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
* @return URL of a running stub or null if not found
*/
URL findStubUrl(String groupId, String artifactId)
/**
* For the given Ivy notation {@code groupId:artifactId} 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 null if not found
*/
URL findStubUrl(String ivyNotation)
/**
* Returns all running stubs
*/
RunningStubs findAllRunningStubs()
/**
* Returns the list of Contracts
*/
Map&lt;StubConfiguration, Collection&lt;Contract&gt;&gt; getContracts()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of usage in Spock tests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">@ClassRule @Shared StubRunnerRule rule = new StubRunnerRule()
.repoRoot(StubRunnerRuleSpec.getResource("/m2repo/repository").toURI().toString())
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer")
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'
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Example of usage in JUnit tests:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" 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:
BDDAssertions.then(rule.findAllRunningStubs().isPresent("loanIssuance")).isTrue();
BDDAssertions.then(rule.findAllRunningStubs().isPresent("org.springframework.cloud.contract.verifier.stubs", "fraudDetectionServer")).isTrue();
BDDAssertions.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="paragraph">
<p>Check the <strong>Common properties for JUnit and Spring</strong> for more information on how to apply global configuration of Stub Runner.</p>
</div>
<div class="sect3">
<h4 id="_providing_fixed_ports">Providing fixed ports</h4>
<div class="paragraph">
<p>You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of
JUnit rule.</p>
</div>
</div>
<div class="sect3">
<h4 id="_fluent_api">Fluent API</h4>
<div class="paragraph">
<p>When using the <code>StubRunnerRule</code> you can add a stub to download and then pass the port for the last downloaded stub.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">@ClassRule public static StubRunnerRule rule = new StubRunnerRule()
.repoRoot(repoRoot())
.downloadStub("org.springframework.cloud.contract.verifier.stubs", "loanIssuance")
.withPort(12345)
.downloadStub("org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer:12346");</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can see that for this example the following test is valid:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" 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 class="sect2">
<h3 id="_stub_runner_spring">Stub Runner Spring</h3>
<div class="paragraph">
<p>Sets up Spring configuration of the Stub Runner project.</p>
</div>
<div class="paragraph">
<p>By providing a list of stubs inside your configuration file the Stub Runner automatically downloads
and registers in WireMock the selected stubs.</p>
</div>
<div class="paragraph">
<p>If you want to find the URL of your stubbed dependency you can autowire the <code>StubFinder</code> interface and use
its methods as presented below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">@ContextConfiguration(classes = Config, loader = SpringBootContextLoader)
@AutoConfigureStubRunner
class StubRunnerConfigurationSpec extends Specification {
@Autowired StubFinder stubFinder
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('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'
}
@Configuration
@EnableAutoConfiguration
static class Config {}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>for the following configuration file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yml" data-lang="yml">stubrunner.stubs.repository.root: classpath:m2repo/repository/
stubrunner.stubs.ids: org.springframework.cloud.contract.verifier.stubs:loanIssuance,org.springframework.cloud.contract.verifier.stubs:fraudDetectionServer</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_spring_cloud">Stub Runner Spring Cloud</h3>
<div class="paragraph">
<p>Registers the stubs in the provided Service Discovery. It&#8217;s enough to add the jar</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">org.springframework.cloud:stub-runner-spring-cloud</code></pre>
</div>
</div>
<div class="paragraph">
<p>and the Stub Runner autoconfiguration should be picked up.</p>
</div>
<div class="sect3">
<h4 id="_stubbing_service_discovery">Stubbing Service Discovery</h4>
<div class="paragraph">
<p>The most important feature of <code>Stub Runner Spring Cloud</code> is the fact that it&#8217;s stubbing</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>DiscoveryClient</code></p>
</li>
<li>
<p><code>Ribbon</code> <code>ServerList</code></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>that means that regardles of the fact whether you&#8217;re using Zookeeper, Consul, Eureka or anything else, you don&#8217;t need that in your tests.
We&#8217;re starting WireMock instances of your dependencies and we&#8217;re telling your application whenever you&#8217;re using <code>Feign</code>, load balanced <code>RestTemplate</code>
or <code>DiscoveryClient</code> directly, to call those stubbed servers instead of calling the real Service Discovery tool.</p>
</div>
</div>
<div class="sect3">
<h4 id="_additional_configuration">Additional Configuration</h4>
<div class="paragraph">
<p>You can match the artifactId of the stub with the name of your app by using the <code>stubrunner.stubs.idsToServiceIds:</code> map.
You can disable Stub Runner Ribbon support by providing: <code>stubrunner.cloud.ribbon.enabled</code> equal to <code>false</code>
You can disable Stub Runner support by providing: <code>stubrunner.cloud.enabled</code> equal to <code>false</code></p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_common_properties_for_junit_and_spring">Common properties for JUnit and Spring</h3>
<div class="paragraph">
<p>Some of the properties that are repetitive can be set using system properties or property sources (for Spring). Here are their names with their default values:</p>
</div>
<table class="tableblock frame-topbot grid-all spread">
<colgroup>
<col style="width: 33%;">
<col style="width: 33%;">
<col style="width: 33%;">
</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.port.range.min</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">Minimal 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.port.range.max</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">Minimal 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.stubs.repository.root</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Comma separated list of Maven repo urls. If blank then will call the local maven repo</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.stubs.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.work-offline</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">If true then will not contact any remote repositories to download stubs</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">stubrunner.stubs.ids</p></td>
<td class="tableblock halign-left valign-top"></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Comma separated list of Ivy notation of stubs to download</p></td>
</tr>
</tbody>
</table>
<div class="sect3">
<h4 id="_stub_runner_stubs_ids">Stub runner stubs ids</h4>
<div class="paragraph">
<p>You can provide the stubs to download via the <code>stubrunner.stubs.ids</code> system property. They follow the following pattern:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-java" data-lang="java">groupId:artifactId:version:classifier:port</code></pre>
</div>
</div>
<div class="paragraph">
<p><code>version</code>, <code>classifier</code> and <code>port</code> are optional.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>If you don&#8217;t provide the <code>port</code> then a random one will be picked</p>
</li>
<li>
<p>If you don&#8217;t provide the <code>classifier</code> then the default one will be taken.</p>
</li>
<li>
<p>If you don&#8217;t provide the <code>version</code> then the <code>+</code> will be passed and the latest one will be downloaded</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Where <code>port</code> means the port of the WireMock server.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_stub_runner_for_messaging">Stub Runner for Messaging</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Spring Integration</p>
</li>
<li>
<p>Spring Cloud Stream</p>
</li>
<li>
<p>Apache Camel</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>It also provides points of entry to integrate with any other solution on the market.</p>
</div>
<div class="sect2">
<h3 id="_stub_triggering">Stub triggering</h3>
<div class="paragraph">
<p>To trigger a message it&#8217;s enough to use the <code>StubTrigger</code> interface:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">/*
* Copyright 2013-2016 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.stubrunner
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.
*
* @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.
*
* @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()
/**
* Returns a mapping of ivy notation of a dependency to all the labels it has.
*
* Feature related to messaging.
*/
Map&lt;String, Collection&lt;String&gt;&gt; labels()
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>For convenience the <code>StubFinder</code> interface extends <code>StubTrigger</code> so it&#8217;s enough to use only one 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="sect3">
<h4 id="_trigger_by_label">Trigger by label</h4>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="sect4">
<h5 id="_trigger_by_group_and_artifact_ids">Trigger by group and artifact ids</h5>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:camelService', 'return_book_1')</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_trigger_by_artifact_ids">Trigger by artifact ids</h5>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('camelService', 'return_book_1')</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_trigger_all_messages">Trigger all messages</h5>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger()</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_camel">Stub Runner Camel</h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;s messaging module gives you an easy way to integrate with Apache Camel.
For the provided artifacts it will automatically download the stubs and register the required
routes.</p>
</div>
<div class="sect3">
<h4 id="_adding_it_to_the_project">Adding it to the project</h4>
<div class="paragraph">
<p>To use it you have to add the following dependency to your project (example for Gradle):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">testCompile "org.springframework.cloud:stub-runner-camel:${verifierVersion}"</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_examples">Examples</h4>
<div class="sect4">
<h5 id="_stubs_structure">Stubs structure</h5>
<div class="paragraph">
<p>Let us assume that we have the following Maven repository with a deployed stubs for the
<code>camelService</code> application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── camelService
├── 0.0.1-SNAPSHOT
│   ├── camelService-0.0.1-SNAPSHOT.pom
│   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s consider the following contracts (let' number it with <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_1'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('jms:output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and number <strong>2</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('jms:input')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('jms:output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_1_no_input_message_2">Scenario 1 (no input message)</h5>
<div class="paragraph">
<p>So as to trigger a message via the <code>return_book_1</code> label we&#8217;ll use the <code>StubTigger</code> interface as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>jms:output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
receivedMessage.in.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_2_output_triggered_by_input_2">Scenario 2 (output triggered by input)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>jms:output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">camelContext.createProducerTemplate().sendBodyAndHeaders('jms:input', new BookReturned('foo'), [sample: 'header'])</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>jms:output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Exchange receivedMessage = camelContext.createConsumerTemplate().receive('jms:output', 5000)</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertThatBodyContainsBookNameFoo(receivedMessage.in.body)
receivedMessage.in.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_3_input_with_no_output">Scenario 3 (input with no output)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>jms:output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">camelContext.createProducerTemplate().sendBodyAndHeaders('jms:delete', new BookReturned('foo'), [sample: 'header'])</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_integration">Stub Runner Integration</h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;s messaging module gives you an easy way to integrate with Spring Integration.
For the provided artifacts it will automatically download the stubs and register the required
routes.</p>
</div>
<div class="sect3">
<h4 id="_adding_it_to_the_project_2">Adding it to the project</h4>
<div class="paragraph">
<p>To use it you have to add the following dependency to your project (example for Gradle):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">testCompile "org.springframework.cloud:stub-runner-integration:${verifierVersion}"</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_examples_2">Examples</h4>
<div class="sect4">
<h5 id="_stubs_structure_2">Stubs structure</h5>
<div class="paragraph">
<p>Let us assume that we have the following Maven repository with a deployed stubs for the
<code>integrationService</code> application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── integrationService
├── 0.0.1-SNAPSHOT
│   ├── integrationService-0.0.1-SNAPSHOT.pom
│   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s consider the following contracts (let' number it with <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_1'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('output')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and number <strong>2</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('input')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('output')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and the following Spring Integration Route:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-xml" data-lang="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!--
~ Copyright 2013-2016 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
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
--&gt;
&lt;beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd"&gt;
&lt;!-- REQUIRED FOR TESTING --&gt;
&lt;bridge input-channel="output"
output-channel="outputTest"/&gt;
&lt;channel id="outputTest"&gt;
&lt;queue/&gt;
&lt;/channel&gt;
&lt;/beans:beans&gt;</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_1_no_input_message_3">Scenario 1 (no input message)</h5>
<div class="paragraph">
<p>So as to trigger a message via the <code>return_book_1</code> label we&#8217;ll use the <code>StubTigger</code> interface as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ContractVerifierMessage receivedMessage = messaging.receiveMessage('outputTest')</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_2_output_triggered_by_input_3">Scenario 2 (output triggered by input)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'input')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>output</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ContractVerifierMessage receivedMessage = messaging.receiveMessage('outputTest')</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_3_input_with_no_output_2">Scenario 3 (input with no output)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>input</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_stub_runner_stream">Stub Runner Stream</h3>
<div class="paragraph">
<p>Spring Cloud Contract Verifier Stub Runner&#8217;s messaging module gives you an easy way to integrate with Spring Stream.
For the provided artifacts it will automatically download the stubs and register the required
routes.</p>
</div>
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<div class="title">Warning</div>
</td>
<td class="content">
In Stub Runner&#8217;s integration with Stream the <code>messageFrom</code> or <code>sentTo</code> Strings are resolved
first as a <code>destination</code> of a channel, and then if there is no such <code>destination</code> it&#8217;s resolved as a
channel name.
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_adding_it_to_the_project_3">Adding it to the project</h4>
<div class="paragraph">
<p>To use it you have to add the following dependency to your project (example for Gradle):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">testCompile "org.springframework.cloud:stub-runner-stream:${verifierVersion}"</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_examples_3">Examples</h4>
<div class="sect4">
<h5 id="_stubs_structure_3">Stubs structure</h5>
<div class="paragraph">
<p>Let us assume that we have the following Maven repository with a deployed stubs for the
<code>streamService</code> application.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── streamService
├── 0.0.1-SNAPSHOT
│   ├── streamService-0.0.1-SNAPSHOT.pom
│   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
│   └── maven-metadata-local.xml
└── maven-metadata-local.xml</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the stubs contain the following structure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-bash" data-lang="bash">├── META-INF
│   └── MANIFEST.MF
└── repository
├── accurest
│   ├── bookDeleted.groovy
│   ├── bookReturned1.groovy
│   └── bookReturned2.groovy
└── mappings</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let&#8217;s consider the following contracts (let' number it with <strong>1</strong>):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_1'
input {
triggeredBy('bookReturnedTriggered()')
}
outputMessage {
sentTo('returnBook')
body('''{ "bookName" : "foo" }''')
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and number <strong>2</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">Contract.make {
label 'return_book_2'
input {
messageFrom('bookStorage')
messageBody([
bookName: 'foo'
])
messageHeaders {
header('sample', 'header')
}
}
outputMessage {
sentTo('returnBook')
body([
bookName: 'foo'
])
headers {
header('BOOK-NAME', 'foo')
}
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>and the following Spring configuration:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-yaml" data-lang="yaml">stubrunner.stubs.repository.root: classpath:m2repo/repository/
stubrunner.stubs.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
spring:
cloud:
stream:
bindings:
output:
destination: returnBook
input:
destination: bookStorage</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_1_no_input_message_4">Scenario 1 (no input message)</h5>
<div class="paragraph">
<p>So as to trigger a message via the <code>return_book_1</code> label we&#8217;ll use the <code>StubTrigger</code> interface as follows</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">stubFinder.trigger('return_book_1')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to a channel whose <code>destination</code> is <code>returnBook</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ContractVerifierMessage receivedMessage = messaging.receiveMessage('returnBook')</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_2_output_triggered_by_input_4">Scenario 2 (output triggered by input)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>bookStorage</code> <code>destination</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'bookStorage')</code></pre>
</div>
</div>
<div class="paragraph">
<p>Next we&#8217;ll want to listen to the output of the message sent to <code>returnBook</code></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">ContractVerifierMessage receivedMessage = messaging.receiveMessage('returnBook')</code></pre>
</div>
</div>
<div class="paragraph">
<p>And the received message would pass the following assertions</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">receivedMessage != null
assertJsons(receivedMessage.payload)
receivedMessage.headers.get('BOOK-NAME') == 'foo'</code></pre>
</div>
</div>
</div>
<div class="sect4">
<h5 id="_scenario_3_input_with_no_output_3">Scenario 3 (input with no output)</h5>
<div class="paragraph">
<p>Since the route is set for you it&#8217;s enough to just send a message to the <code>output</code> destination.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlight"><code class="language-groovy" data-lang="groovy">messaging.send(new BookReturned('foo'), [sample: 'header'], 'delete')</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_links">Links</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Here you can find interesting links related to Spring Cloud Contract Verifier:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://github.com/spring-cloud/spring-cloud-contract/">Spring Cloud Contract Verifier Github Repository</a></p>
</li>
<li>
<p><a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html">Spring Cloud Contract Verifier Documentation</a></p>
</li>
<li>
<p><a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated">Accurest Legacy Documentation</a></p>
</li>
<li>
<p><a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner">Spring Cloud Contract Stub Runner Documentation</a></p>
</li>
<li>
<p><a href="https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging">Spring Cloud Contract Stub Runner Messaging Documentation</a></p>
</li>
<li>
<p><a href="https://gitter.im/spring-cloud/spring-cloud-contract">Spring Cloud Contract Verifier Gitter</a></p>
</li>
<li>
<p><a href="https://github.com/spring-cloud/spring-cloud-contract">Spring Cloud Contract Verifier Maven Plugin</a></p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_spring_cloud_contract_wiremock">Spring Cloud Contract WireMock</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Modules giving you the possibility to use <a href="http://wiremock.org">WireMock</a> with different servers. Check out the
<a href="https://github.com/spring-cloud/spring-cloud-contract/tree/master/samples">samples</a> for more information.</p>
</div>
<div class="paragraph">
<p>Currently we support Jetty, Native WireMock server, Tomcat and Undertow.</p>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2016-07-15 14:27:23 CEST
</div>
</div>
</body>
</html>