diff --git a/spring-cloud-contract.html b/spring-cloud-contract.html index 13d98eedcd..73efbc04ca 100644 --- a/spring-cloud-contract.html +++ b/spring-cloud-contract.html @@ -104,9 +104,10 @@ $(addBlockSwitches);
  • 2.1.1. Why?
  • 2.1.2. Purposes
  • 2.1.3. How
  • -
  • 2.1.4. Dependencies
  • -
  • 2.1.5. Additional links
  • -
  • 2.1.6. Samples
  • +
  • 2.1.4. Step by step guide to CDC
  • +
  • 2.1.5. Dependencies
  • +
  • 2.1.6. Additional links
  • +
  • 2.1.7. Samples
  • 2.2. FAQ @@ -115,101 +116,129 @@ $(addBlockSwitches);
  • 2.2.2. What is this value(consumer(), producer()) ?
  • 2.2.3. How to do Stubs versioning?
  • 2.2.4. Common repo with contracts
  • +
  • 2.2.5. Can I have multiple base classes for tests?
  • +
  • 2.2.6. How can I debug the request/response being sent by the generated tests client?
  • +
  • 2.2.7. How can I debug the mapping/request/response being sent by WireMock?
  • +
  • 2.2.8. How can I see what got registered in the HTTP server stub?
  • +
  • 2.2.9. Can I reference the request from the response?
  • +
  • 2.2.10. Can I reference text from file?
  • -
  • 2.3. Stub Runner Core +
  • 2.3. Spring Cloud Contract Verifier HTTP
  • -
  • 2.4. Stub Runner JUnit Rule +
  • 2.4. Spring Cloud Contract Verifier Messaging
  • -
  • 2.5. Stub Runner Spring Cloud +
  • 2.5. Spring Cloud Contract Stub Runner
  • -
  • 2.6. Stub Runner Boot Application +
  • 2.6. Stub Runner Core
  • -
  • 2.7. Stubs Per Consumer
  • -
  • 2.8. Common +
  • 2.7. Stub Runner JUnit Rule
  • -
  • 2.9. Stub Runner for Messaging +
  • 2.8. Stub Runner Spring Cloud
  • -
  • 2.10. Stub Runner Camel +
  • 2.9. Stub Runner Boot Application
  • -
  • 2.11. Stub Runner Integration +
  • 2.10. Stubs Per Consumer
  • +
  • 2.11. Common
  • -
  • 2.12. Stub Runner Stream +
  • 2.12. Stub Runner for Messaging
  • -
  • 2.13. Stub Runner Spring AMQP +
  • 2.13. Stub Runner Camel
  • -
  • 2.14. Contract DSL +
  • 2.14. Stub Runner Integration
  • -
  • 2.15. Customization +
  • 2.15. Stub Runner Stream
  • -
  • 2.16. Pluggable architecture +
  • 2.16. Stub Runner Spring AMQP
  • -
  • 2.17. Links
  • +
  • 2.17. Contract DSL + +
  • +
  • 2.18. Customization + +
  • +
  • 2.19. Pluggable architecture + +
  • +
  • 2.20. Links
  • 3. Spring Cloud Contract WireMock @@ -461,176 +490,385 @@ Contract tests are used to test contracts between applications and not to simula
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]
    +
    package contracts
     
    -===== Client Side
    +org.springframework.cloud.contract.spec.Contract.make {
    +	request { // (1)
    +		method 'PUT' // (2)
    +		url '/fraudcheck' // (3)
    +		body([ // (4)
    +			   "client.id": $(regex('[0-9]{10}')),
    +			   loanAmount: 99999
    +		])
    +		headers { // (5)
    +			contentType('application/json')
    +		}
    +	}
    +	response { // (6)
    +		status 200 // (7)
    +		body([ // (8)
    +			   fraudCheckStatus: "FRAUD",
    +			   "rejection.reason": "Amount too high"
    +		])
    +		headers { // (9)
    +			contentType('application/json')
    +		}
    +	}
    +}
     
    -Spring Cloud Contract will generate stubs, which you can use during client side testing.
    +/*
    +From the Consumer perspective, when shooting a request in the integration test:
    +
    +(1) - If the consumer sends a request
    +(2) - With the "PUT" method
    +(3) - to the URL "/fraudcheck"
    +(4) - with the JSON body that
    + * has a field `clientId` that matches a regular expression `[0-9]{10}`
    + * has a field `loanAmount` that is equal to `99999`
    +(5) - with header `Content-Type` equal to `application/json`
    +(6) - then the response will be sent with
    +(7) - status equal `200`
    +(8) - and JSON body equal to
    + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
    +(9) - with header `Content-Type` equal to `application/json`
    +
    +From the Producer perspective, in the autogenerated producer-side test:
    +
    +(1) - A request will be sent to the producer
    +(2) - With the "PUT" method
    +(3) - to the URL "/fraudcheck"
    +(4) - with the JSON body that
    + * has a field `clientId` that will have a generated value that matches a regular expression `[0-9]{10}`
    + * has a field `loanAmount` that is equal to `99999`
    +(5) - with header `Content-Type` equal to `application/json`
    +(6) - then the test will assert if the response has been sent with
    +(7) - status equal `200`
    +(8) - and JSON body equal to
    + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" }
    +(9) - with header `Content-Type` matching `application/json.*`
    + */
    +
    +
    + +
    +
    Client Side
    +
    +

    Spring Cloud Contract will generate stubs, which you can use during client side testing. You will 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. - -At some point in time you need to send a request to the Fraud Detection service. - -[source,groovy,indent=0] -

    +You would like to feed that instance with a proper stub definition.

    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]

    +

    At some point in time you need to send a request to the Fraud Detection service.

    -
    Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.
    -
    -[source,groovy,indent=0]
    +
    ResponseEntity<FraudServiceResponse> response =
    +		restTemplate.exchange("http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
    +				new HttpEntity<>(request, httpHeaders),
    +				FraudServiceResponse.class);
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]

    +

    Annotate your test class with @AutoConfigureStubRunner. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators.

    -
    After that, during the tests Spring Cloud Contract will automatically find the stubs (simulating the real service) in Maven repository and expose them on configured (or random) port.
    -
    -===== Server Side
    -
    -Being a service Y since you are developing your stub, you need to be sure that it's actually resembling your
    -concrete implementation. You can't have a situation where your stub acts in one way and your application on
    -production behaves in a different way.
    -
    -That'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.
    -
    -The autogenerated test would look like this:
    -
    -[source,java,indent=0]
    +
    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, workOffline = true)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {
    -

    @Test +

    After that, during the tests Spring Cloud Contract will automatically find the stubs (simulating the real service) in Maven repository and expose them on configured (or random) port.

    +
    + +
    +
    Server Side
    +
    +

    Being a service Y since you are developing your stub, you need to be sure that it’s actually resembling your +concrete implementation. You can’t have a situation where your stub acts in one way and your application on +production behaves in a different way.

    +
    +
    +

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

    +
    +
    +

    The autogenerated test would look like this:

    +
    +
    +
    +
    @Test
     public void validate_shouldMarkClientAsFraud() throws Exception {
         // given:
             MockMvcRequestSpecification request = given()
                     .header("Content-Type", "application/vnd.fraud.v1+json")
    -                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    -
    -
    -
    -
    // when:
    -    ResponseOptions response = given().spec(request)
    -            .put("/fraudcheck");
    -
    -
    -
    -
    -
        // then:
    +                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
    +
    +    // when:
    +        ResponseOptions response = given().spec(request)
    +                .put("/fraudcheck");
    +
    +    // then:
             assertThat(response.statusCode()).isEqualTo(200);
             assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
         // and:
             DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
             assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
             assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
    -}
    +}
    +
    +
    +
    +

    2.1.4. Step by step guide to CDC

    +
    +

    Let’s take an example of Fraud Detection and Loan Issuance process. The business scenario is such that we want to issue loans to people but don’t want them to steal the money from us. The current implementation of our system grants loans to everybody.

    +
    +
    +

    Let’s assume that the Loan Issuance is a client to the +Fraud Detection server. In the current sprint we are required to develop a new feature - if a client wants to borrow too much money then we mark him as fraud.

    +
    +
    +

    Technical remark - Fraud Detection will have artifact id http-server, Loan Issuance http-client and both have group id com.example.

    +
    +
    +

    Social remark - both client and server development teams need to communicate directly and discuss changes while +going through the process. CDC is all about communication.

    +
    + +
    + + + + + +
    + + +In this case the ownership of the contracts lays on the producer side. It means that physically +all the contract are present in the producer’s repository +
    +
    +
    +
    Technical note
    +
    +

    If using the SNAPSHOT / Milestone / Release Candidate versions please add the following section to your

    +
    +
    +
    Maven
    +
    +
    <repositories>
    +	<repository>
    +		<id>spring-snapshots</id>
    +		<name>Spring Snapshots</name>
    +		<url>https://repo.spring.io/snapshot</url>
    +		<snapshots>
    +			<enabled>true</enabled>
    +		</snapshots>
    +	</repository>
    +	<repository>
    +		<id>spring-milestones</id>
    +		<name>Spring Milestones</name>
    +		<url>https://repo.spring.io/milestone</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</repository>
    +	<repository>
    +		<id>spring-releases</id>
    +		<name>Spring Releases</name>
    +		<url>https://repo.spring.io/release</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</repository>
    +</repositories>
    +<pluginRepositories>
    +	<pluginRepository>
    +		<id>spring-snapshots</id>
    +		<name>Spring Snapshots</name>
    +		<url>https://repo.spring.io/snapshot</url>
    +		<snapshots>
    +			<enabled>true</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +	<pluginRepository>
    +		<id>spring-milestones</id>
    +		<name>Spring Milestones</name>
    +		<url>https://repo.spring.io/milestone</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +	<pluginRepository>
    +		<id>spring-releases</id>
    +		<name>Spring Releases</name>
    +		<url>https://repo.spring.io/release</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +</pluginRepositories>
    +
    +
    +
    +
    Gradle
    +
    +
    repositories {
    +	mavenCentral()
    +	mavenLocal()
    +	maven { url "http://repo.spring.io/snapshot" }
    +	maven { url "http://repo.spring.io/milestone" }
    +	maven { url "http://repo.spring.io/release" }
    +}
    +
    +
    +
    +
    +
    Consumer side (Loan Issuance)
    +
    +

    As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

    +
    +
    +

    start doing TDD by writing a test to your feature

    +
    -
    ==== Step by step guide to CDC
    -
    -Let's take an example of Fraud Detection and Loan Issuance process. The business scenario is such that we want to issue loans to people but don't want them to steal the money from us. The current implementation of our system grants loans to everybody.
    -
    -Let's assume that the `Loan Issuance` is a client to the
    -`Fraud Detection` server. In the current sprint we are required to develop a new feature - if a client wants to borrow too much money then we mark him as fraud.
    -
    -Technical remark - Fraud Detection will have artifact id `http-server`, Loan Issuance `http-client` and both have group id `com.example`.
    -
    -Social remark - both client and server development teams need to communicate directly and discuss changes while
    -going through the process. CDC is all about communication.
    -
    -The https://github.com/spring-cloud/spring-cloud-contract/tree/1.0.x/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/1.0.x/samples/standalone/dsl/http-client[the client side code here].
    -
    -TIP: In this case the ownership of the contracts lays on the producer side. It means that physically
    -all the contract are present in the producer's repository
    -
    -===== Technical note
    -
    -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the following section to your
    -
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    +
    @Test
    +public void shouldBeRejectedDueToAbnormalLoanAmount() {
    +	// given:
    +	LoanApplication application = new LoanApplication(new Client("1234567890"),
    +			99999);
    +	// when:
    +	LoanApplicationResult loanApplication = service.loanApplication(application);
    +	// then:
    +	assertThat(loanApplication.getLoanApplicationStatus())
    +			.isEqualTo(LoanApplicationStatus.LOAN_APPLICATION_REJECTED);
    +	assertThat(loanApplication.getRejectionReason()).isEqualTo("Amount too high");
    +}
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/pom.xml[tags=repos,indent=0]

    +

    We’ve just written a test of our new feature. If a loan application for a big amount is received we should reject that loan application with some description.

    +
    +
    +

    write the missing implementation

    +
    +
    +

    At some point in time you need to send a request to the Fraud Detection service. Let’s assume that we’d like to send the request containing the id of the client and the amount he wants to borrow from us. We’d like to send it to the /fraudcheck url via the PUT method.

    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    +
    ResponseEntity<FraudServiceResponse> response =
    +		restTemplate.exchange("http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
    +				new HttpEntity<>(request, httpHeaders),
    +				FraudServiceResponse.class);
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/build.gradle[tags=deps_repos,indent=0]

    +

    For simplicity we’ve hardcoded the port of the Fraud Detection service at 8080 and our application is running on 8090.

    +
    +
    +

    If we’d start the written test it would obviously break since we have no service running on port 8080.

    +
    +
    +

    clone the Fraud Detection service repository locally

    +
    +
    +

    We’ll start playing around with the server side contract. That’s why we need to first clone it.

    -
    ===== Consumer side (Loan Issuance)
    -
    -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):
    -
    -*start doing TDD by writing a test to your feature*
    -
    -[source,groovy,indent=0]
    +
    git clone https://your-git-server.com/server-side.git local-http-server-repo
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0]

    +

    define the contract locally in the repo of Fraud Detection service

    +
    +
    +

    As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That’s why we write the following contract.

    +
    +
    + + + + + +
    + + +We’re placing the contract under src/test/resources/contracts/fraud folder. The fraud folder +is important cause we’ll reference that folder in the producer’s test base class name. +
    -
    We've just written a test of our new feature. If a loan application for a big amount is received we should reject that loan application with some description.
    +
    package contracts
     
    -*write the missing implementation*
    +org.springframework.cloud.contract.spec.Contract.make {
    +	request { // (1)
    +		method 'PUT' // (2)
    +		url '/fraudcheck' // (3)
    +		body([ // (4)
    +			   "client.id": $(regex('[0-9]{10}')),
    +			   loanAmount: 99999
    +		])
    +		headers { // (5)
    +			contentType('application/json')
    +		}
    +	}
    +	response { // (6)
    +		status 200 // (7)
    +		body([ // (8)
    +			   fraudCheckStatus: "FRAUD",
    +			   "rejection.reason": "Amount too high"
    +		])
    +		headers { // (9)
    +			contentType('application/json')
    +		}
    +	}
    +}
     
    -At some point in time you need to send a request to the Fraud Detection service. Let's assume that we'd like to send the request containing the id of the client and the amount he wants to borrow from us. We'd like to send it to the `/fraudcheck` url via the `PUT` method.
    +/*
    +From the Consumer perspective, when shooting a request in the integration test:
     
    -[source,groovy,indent=0]
    +(1) - If the consumer sends a request +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `clientId` that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the response will be sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` equal to `application/json` + +From the Producer perspective, in the autogenerated producer-side test: + +(1) - A request will be sent to the producer +(2) - With the "PUT" method +(3) - to the URL "/fraudcheck" +(4) - with the JSON body that + * has a field `clientId` that will have a generated value that matches a regular expression `[0-9]{10}` + * has a field `loanAmount` that is equal to `99999` +(5) - with header `Content-Type` equal to `application/json` +(6) - then the test will assert if the response has been sent with +(7) - status equal `200` +(8) - and JSON body equal to + { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } +(9) - with header `Content-Type` matching `application/json.*` + */
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0]

    -
    -
    -
    -
    For simplicity we've hardcoded the port of the Fraud Detection service at `8080` and our application is running on `8090`.
    -
    -If we'd start the written test it would obviously break since we have no service running on port `8080`.
    -
    -*clone the Fraud Detection service repository locally*
    -
    -We'll start playing around with the server side contract. That's why we need to first clone it.
    -
    -[source,bash,indent=0]
    -
    -
    -
    -

    git clone https://your-git-server.com/server-side.git local-http-server-repo

    -
    -
    -
    -
    *define the contract locally in the repo of Fraud Detection service*
    -
    -As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract.
    -
    -IMPORTANT: We're placing the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder
    -is important cause we'll reference that folder in the producer's test base class name.
    -
    -[source,groovy,indent=0]
    -
    -
    -
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[]

    -
    -

    The Contract is written using a statically typed Groovy DSL. You might be wondering what are those value(client(…​), server(…​)) parts. By using this notation Spring Cloud Contract allows you to define parts of a JSON / URL / etc. which are dynamic. In case of an identifier or a timestamp you @@ -703,7 +941,17 @@ It’s really important that you understand the map notation to set up contr

    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0]
    +
    <dependencyManagement>
    +	<dependencies>
    +		<dependency>
    +			<groupId>org.springframework.cloud</groupId>
    +			<artifactId>spring-cloud-dependencies</artifactId>
    +			<version>${spring-cloud-dependencies.version}</version>
    +			<type>pom</type>
    +			<scope>import</scope>
    +		</dependency>
    +	</dependencies>
    +</dependencyManagement>
    @@ -711,7 +959,15 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
    +
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +	<configuration>
    +		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
    +	</configuration>
    +</plugin>
    @@ -777,7 +1033,17 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0]
    +
    <dependencyManagement>
    +	<dependencies>
    +		<dependency>
    +			<groupId>org.springframework.cloud</groupId>
    +			<artifactId>spring-cloud-dependencies</artifactId>
    +			<version>${spring-cloud-dependencies.version}</version>
    +			<type>pom</type>
    +			<scope>import</scope>
    +		</dependency>
    +	</dependencies>
    +</dependencyManagement>
    @@ -785,7 +1051,11 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0]
    +
    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>
    @@ -793,7 +1063,11 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0]
    +
    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, workOffline = true)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {
    @@ -836,8 +1110,9 @@ It’s really important that you understand the map notation to set up contr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0]
    -Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0]
    +
    @RequestMapping(value = "/fraudcheck", method = PUT)
    +public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
    +return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
     }
    @@ -855,7 +1130,11 @@ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0]
    +
    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
    +	<scope>test</scope>
    +</dependency>
    @@ -863,7 +1142,15 @@ git pull https://your-git-server.com/server-side-fork.git contract-change-pr
    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0]
    +
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +	<configuration>
    +		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
    +	</configuration>
    +</plugin>
    -

    Results :

    -
    -
    -

    Tests in error: - ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed…​

    +

    Now, if you run the ./mvnw clean install you would get sth like this:

    -
    That's because you have a new contract from which a test was generated and it failed since you haven't implemented the feature. The autogenerated test would look like this:
    +
    Results :
     
    -[source,java,indent=0]
    +Tests in error: + ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
    -

    @Test +

    That’s because you have a new contract from which a test was generated and it failed since you haven’t implemented the feature. The autogenerated test would look like this:

    +
    +
    +
    +
    @Test
     public void validate_shouldMarkClientAsFraud() throws Exception {
         // given:
             MockMvcRequestSpecification request = given()
                     .header("Content-Type", "application/vnd.fraud.v1+json")
    -                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");

    -
    -
    -
    -
    // when:
    -    ResponseOptions response = given().spec(request)
    -            .put("/fraudcheck");
    -
    -
    -
    -
    -
        // then:
    +                .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}");
    +
    +    // when:
    +        ResponseOptions response = given().spec(request)
    +                .put("/fraudcheck");
    +
    +    // then:
             assertThat(response.statusCode()).isEqualTo(200);
             assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*");
         // and:
             DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
             assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}");
             assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high");
    -}
    -
    -
    -
    -
    -
    As you can see all the `producer()` parts of the Contract that were present in the `value(consumer(...), producer(...))` blocks got injected into the test.
    -
    -What's important here to note is that on the producer side we also are doing TDD. We have expectations in form of a test. This test is shooting a request to our own application to an URL, headers and body defined in the contract. It also is expecting very precisely defined values in the response. In other words you have is your `red` part of `red`, `green` and `refactor`. Time to convert the `red` into the `green`.
    -
    -*write the missing implementation*
    -
    -Now since we now what is the expected input and expected output let's write the missing implementation.
    -
    -[source,java,indent=0]
    +}
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=server_api,indent=0] -Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=new_impl,indent=0] -Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java[tags=initial_impl,indent=0] -}

    +

    As you can see all the producer() parts of the Contract that were present in the value(consumer(…​), producer(…​)) blocks got injected into the test.

    +
    +
    +

    What’s important here to note is that on the producer side we also are doing TDD. We have expectations in form of a test. This test is shooting a request to our own application to an URL, headers and body defined in the contract. It also is expecting very precisely defined values in the response. In other words you have is your red part of red, green and refactor. Time to convert the red into the green.

    +
    +
    +

    write the missing implementation

    +
    +
    +

    Now since we now what is the expected input and expected output let’s write the missing implementation.

    -
    If we execute `./mvnw clean install` again the tests will pass. Since the `Spring Cloud Contract Verifier` plugin adds the tests to the `generated-test-sources` you can actually run those tests from your IDE.
    -
    -*deploy your app*
    -
    -Once you've finished your work it's time to deploy your change. First merge the branch
    -
    -[source,bash,indent=0]
    +
    @RequestMapping(value = "/fraudcheck", method = PUT)
    +public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
    +if (amountGreaterThanThreshold(fraudCheck)) {
    +	return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
    +}
    +return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
    +}
    -

    git checkout master +

    If we execute ./mvnw clean install again the tests will pass. Since the Spring Cloud Contract Verifier plugin adds the tests to the generated-test-sources you can actually run those tests from your IDE.

    +
    +
    +

    deploy your app

    +
    +
    +

    Once you’ve finished your work it’s time to deploy your change. First merge the branch

    +
    +
    +
    +
    git checkout master
     git merge --no-ff contract-change-pr
    -git push origin master

    -
    -
    -
    -
    Then we assume that your CI would run sth like `./mvnw clean deploy` which would publish both the application and the stub artifcats.
    -
    -===== Consumer side (Loan Issuance) final step
    -
    -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):
    -
    -*merge branch to master*
    -
    -[source,bash,indent=0]
    +git push origin master
    -

    git checkout master -git merge --no-ff contract-change-pr

    +

    Then we assume that your CI would run sth like ./mvnw clean deploy which would publish both the application and the stub artifcats.

    +
    +
    +
    +
    Consumer side (Loan Issuance) final step
    +
    +

    As a developer of the Loan Issuance service (a consumer of the Fraud Detection server):

    +
    +
    +

    merge branch to master

    -
    *work online*
    -
    -Now you can disable the offline work for Spring Cloud Contract Stub Runner and provide where the repository with your stubs is placed. At this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory.
    -You can switch off the value of the `workOffline` parameter in your annotation. Below you can see an
    -example of achieving the same by changing the properties.
    -
    -[source,yaml,indent=0]
    +
    git checkout master
    +git merge --no-ff contract-change-pr
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/1.0.x/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[]

    +

    work online

    +
    +
    +

    Now you can disable the offline work for Spring Cloud Contract Stub Runner and provide where the repository with your stubs is placed. At this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory. +You can switch off the value of the workOffline parameter in your annotation. Below you can see an +example of achieving the same by changing the properties.

    +
    +
    +
    +
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: http://repo.spring.io/libs-snapshot
    +

    And that’s it!

    @@ -1008,7 +1321,7 @@ example of achieving the same by changing the properties.
    -

    2.1.4. Dependencies

    +

    2.1.5. Dependencies

    The best way to add the dependencies is to just use the proper starter dependency.

    @@ -1018,7 +1331,7 @@ example of achieving the same by changing the properties.
    - +

    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.

    @@ -1055,7 +1368,7 @@ is under constant development.

    -

    2.1.6. Samples

    +

    2.1.7. Samples

    Here you can find some samples.

    @@ -1416,129 +1729,346 @@ one to one to the contents of the repo.

    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/contracts/com/example/server/pom.xml[indent=0]
    +
    <?xml version="1.0" encoding="UTF-8"?>
    +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    +	<modelVersion>4.0.0</modelVersion>
     
    -As you can see there are no dependencies other than the Spring Cloud Contract Maven Plugin.
    -Those poms are necessary for the consumer side to run `mvn clean install -DskipTests` to locally install
    - stubs of the producer project.
    +	<groupId>com.example</groupId>
    +	<artifactId>server</artifactId>
    +	<version>0.0.1-SNAPSHOT</version>
     
    -The `pom.xml` in the root folder can look like this:
    +	<name>Server Stubs</name>
    +	<description>POM used to install locally stubs for consumer side</description>
     
    -[source,xml,indent=0]
    + <parent> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-parent</artifactId> + <version>1.5.4.RELEASE</version> + <relativePath /> + </parent> + + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <java.version>1.8</java.version> + <spring-cloud-contract.version>1.2.0.BUILD-SNAPSHOT</spring-cloud-contract.version> + <spring-cloud-dependencies.version>Edgware.BUILD-SNAPSHOT</spring-cloud-dependencies.version> + <excludeBuildFolders>true</excludeBuildFolders> + </properties> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-dependencies</artifactId> + <version>${spring-cloud-dependencies.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + + <build> + <plugins> + <plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> + <configuration> + <!-- By default it would search under src/test/resources/ --> + <contractsDirectory>${project.basedir}</contractsDirectory> + </configuration> + </plugin> + </plugins> + </build> + + <repositories> + <repository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </repository> + <repository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + <repository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </repository> + </repositories> + <pluginRepositories> + <pluginRepository> + <id>spring-snapshots</id> + <name>Spring Snapshots</name> + <url>https://repo.spring.io/snapshot</url> + <snapshots> + <enabled>true</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-milestones</id> + <name>Spring Milestones</name> + <url>https://repo.spring.io/milestone</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + <pluginRepository> + <id>spring-releases</id> + <name>Spring Releases</name> + <url>https://repo.spring.io/release</url> + <snapshots> + <enabled>false</enabled> + </snapshots> + </pluginRepository> + </pluginRepositories> + +</project>
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/contracts/pom.xml[indent=0]

    +

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

    +
    +
    +

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

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

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

    -
    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/samples/standalone/contracts/src/assembly/contracts.xml[indent=0]
    -
    -===== Workflow
    -
    -The workflow would look similar to the one presented in the `Step by step guide to CDC`. The only difference
    - is that the producer doesn't own the contracts anymore. So the consumer and the producer have to work on
    - common contracts in a common repository.
    -
    -====== Consumer
    -
    -When the *consumer* wants to work on the contracts offline, instead of cloning the producer code, the
    -consumer team clones the common repository, goes to the required producer's folder (e.g. `com/example/server`)
    -and runs `mvn clean install -DskipTests` to install locally the stubs converted from the contracts.
    -
    -TIP: You need to have http://maven.apache.org/download.cgi[Maven installed locally]
    -
    -====== Producer
    -
    -As a *producer* it's enough to alter the Spring Cloud Contract Verifier to provide the URL and the dependency
    -of the JAR containing the contracts:
    -
    -[source,xml,indent=0]
    +
    <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
    +		  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +		  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    +	<id>project</id>
    +	<formats>
    +		<format>jar</format>
    +	</formats>
    +	<includeBaseDirectory>false</includeBaseDirectory>
    +	<fileSets>
    +		<fileSet>
    +			<directory>${project.basedir}</directory>
    +			<outputDirectory>/</outputDirectory>
    +			<useDefaultExcludes>true</useDefaultExcludes>
    +			<excludes>
    +				<exclude>**/${project.build.directory}/**</exclude>
    +				<exclude>mvnw</exclude>
    +				<exclude>mvnw.cmd</exclude>
    +				<exclude>.mvn/**</exclude>
    +				<exclude>src/**</exclude>
    +			</excludes>
    +		</fileSet>
    +	</fileSets>
    +</assembly>
    +
    +
    +
    Workflow
    -

    Unresolved directive in verifier/introduction.adoc - include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/master/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/test/projects/basic-remote-contracts/pom-with-repo.xml[tags=remote_config,indent=0]

    +

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

    +
    +
    +
    Consumer
    +
    +

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

    +
    +
    + + + + + +
    + + +You need to have Maven installed locally +
    +
    +
    +
    +
    Producer
    +
    +

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

    -
    With this setup the JAR with groupid `com.example.standalone` and artifactid `contracts` will be downloaded
    -from `http://link/to/your/nexus/or/artifactory/or/sth`. It will be then unpacked in a local temporary folder
    -and contracts present under the `com/example/server` will be picked as the ones used to generate the
    +
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<configuration>
    +		<contractsRepositoryUrl>http://link/to/your/nexus/or/artifactory/or/sth</contractsRepositoryUrl>
    +		<contractDependency>
    +			<groupId>com.example.standalone</groupId>
    +			<artifactId>contracts</artifactId>
    +		</contractDependency>
    +	</configuration>
    +</plugin>
    +
    +
    +
    +

    With this setup the JAR with groupid com.example.standalone and artifactid contracts will be downloaded +from http://link/to/your/nexus/or/artifactory/or/sth. It will be then unpacked in a local temporary folder +and contracts present under the com/example/server will be picked as the ones used to generate the tests and the stubs. Due to this convention the producer team will know which consumer teams will be broken -when some incompatible changes are done. - -The rest of the flow looks the same. - -==== Can I have multiple base classes for tests? - -Yes! Check out the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_different_base_classes_for_contracts[Different base classes for contracts] sections -of either Gradle or Maven plugins. - -==== How can I debug the request/response being sent by the generated tests client? - -The generated tests all boil down to RestAssured in some form or fashion which relies on https://hc.apache.org/httpcomponents-client-ga/[Apache HttpClient]. HttpClient has a facility called https://hc.apache.org/httpcomponents-client-ga/logging.html#Wire_Logging[wire logging] which logs the entire request and response to HttpClient. Spring Boot has a logging https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html[common application property] for doing this sort of thing, just add this to your application properties -[source,properties,indent=0] -

    +when some incompatible changes are done.

    -

    logging.level.org.apache.http.wire=DEBUG

    +

    The rest of the flow looks the same.

    +
    +
    +
    +
    +
    +

    2.2.5. Can I have multiple base classes for tests?

    +
    +

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

    +
    +
    +
    +

    2.2.6. How can I debug the request/response being sent by the generated tests client?

    +
    +

    The generated tests all boil down to RestAssured in some form or fashion which relies on Apache HttpClient. HttpClient has a facility called wire logging which logs the entire request and response to HttpClient. Spring Boot has a logging common application property for doing this sort of thing, just add this to your application properties

    -
    ==== How can I debug the mapping/request/response being sent by WireMock?
    -
    -Starting from version `1.2.0` we turn on WireMock logging to
    +
    logging.level.org.apache.http.wire=DEBUG
    +
    +
    +
    +
    +

    2.2.7. How can I debug the mapping/request/response being sent by WireMock?

    +
    +

    Starting from version 1.2.0 we turn on WireMock logging to info and the WireMock notifier to being verbose. Now you will exactly know what request was received by WireMock server and which -matching response definition was picked. - -To turn off this feature just bump WireMock logging to `ERROR` - -[source,properties,indent=0] -

    +matching response definition was picked.

    -

    logging.level.com.github.tomakehurst.wiremock=ERROR

    +

    To turn off this feature just bump WireMock logging to ERROR

    -
    ==== How can I see what got registered in the HTTP server stub?
    -
    -You can use the `mappingsOutputFolder` property on `@AutoConfigureStubRunner` or `StubRunnerRule`
    -to dump all mappings per artifact id. Also the port at which the given stub server was
    -started will be attached.
    -
    -==== Can I reference the request from the response?
    -
    -Yes! With version 1.1.0 we've added such a possibility. On the HTTP stub server side we're providing support
    -for this for WireMock. In case of other HTTP server stubs you'll have to implement the approach yourself.
    -
    -==== Can I reference text from file?
    -
    -Yes! With version 1.2.0 we've added such a possibility. It's enough to call `file(...)` method in the
    -DSL and provide a path relative to where the contract lays.
    -
    -=== Spring Cloud Contract Verifier HTTP
    -
    -==== Gradle Project
    -
    -===== Prerequisites
    -
    -In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin.
    -
    -WARNING: If you want to use Spock in your projects you have to add separately
    -the `spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock docs for more information]
    -
    -====== Add gradle plugin with dependencies
    -
    -[source,groovy,indent=0]
    +
    logging.level.com.github.tomakehurst.wiremock=ERROR
    + +
    +

    2.2.8. How can I see what got registered in the HTTP server stub?

    -

    buildscript { +

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

    +
    +
    +
    +

    2.2.9. Can I reference the request from the response?

    +
    +

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

    +
    +
    +
    +

    2.2.10. Can I reference text from file?

    +
    +

    Yes! With version 1.2.0 we’ve added such a possibility. It’s enough to call file(…​) method in the +DSL and provide a path relative to where the contract lays.

    +
    +
    + +
    +

    2.3. Spring Cloud Contract Verifier HTTP

    +
    +

    2.3.1. Gradle Project

    +
    +
    Prerequisites
    +
    +

    In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin.

    +
    +
    + + + + + +
    + + +If you want to use Spock in your projects you have to add separately +the spock-core and spock-spring modules. Check Spock docs for more information +
    +
    +
    +
    Add gradle plugin with dependencies
    +
    +
    +
    buildscript {
     	repositories {
     		mavenCentral()
     	}
    @@ -1546,40 +2076,36 @@ the `spock-core` and `spock-spring` modules. Check http://spockframework.github.
     	    classpath "org.springframework.boot:spring-boot-gradle-plugin:${springboot_version}"
     		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:${verifier_version}"
     	}
    -}

    -
    -
    -

    apply plugin: 'groovy' -apply plugin: 'spring-cloud-contract'

    -
    -
    -

    dependencyManagement { +} + +apply plugin: 'groovy' +apply plugin: 'spring-cloud-contract' + +dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-contract-dependencies:${verifier_version}" } -}

    -
    -
    -

    dependencies { +} + +dependencies { testCompile 'org.codehaus.groovy:groovy-all:2.4.6' // example with adding Spock core and Spock Spring testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' testCompile 'org.spockframework:spock-spring:1.0-groovy-2.4' testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier' -}

    +}
    +
    +
    +
    +
    +
    Gradle and Rest Assured 2.0
    +
    +

    By default Rest Assured 3.x is added to the classpath. However in order to give the users the +opportunity to use Rest Assured 2.x it’s enough to add it to the plugins classpath.

    -
    ====== Gradle and Rest Assured 2.0
    -
    -By default Rest Assured 3.x is added to the classpath. However in order to give the users the
    -opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath.
    -
    -[source,groovy,indent=0]
    -
    -
    -
    -

    buildscript { +

    buildscript {
     	repositories {
     		mavenCentral()
     	}
    @@ -1589,30 +2115,29 @@ opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpa
     		classpath "com.jayway.restassured:rest-assured:2.5.0"
     		classpath "com.jayway.restassured:spring-mock-mvc:2.5.0"
     	}
    -}

    -
    -
    -

    depenendencies { +} + +depenendencies { // all dependencies // you can exclude rest-assured from spring-cloud-contract-verifier testCompile "com.jayway.restassured:rest-assured:2.5.0" testCompile "com.jayway.restassured:spring-mock-mvc:2.5.0" -}

    -
    -
    -
    -
    That way the plugin will automatically see that Rest Assured 2.x is present on the classpath
    -and will modify the imports accordingly.
    -
    -====== Snapshot versions for Gradle
    -
    -Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:
    -
    -[source,groovy,indent=0]
    +}
    -

    buildscript { +

    That way the plugin will automatically see that Rest Assured 2.x is present on the classpath +and will modify the imports accordingly.

    +
    +
    +
    +
    Snapshot versions for Gradle
    +
    +

    Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:

    +
    +
    +
    +
    buildscript {
     	repositories {
     		mavenCentral()
     		mavenLocal()
    @@ -1620,55 +2145,63 @@ Add the additional snapshot repository to your build.gradle to use snapshot vers
     		maven { url "http://repo.spring.io/milestone" }
     		maven { url "http://repo.spring.io/release" }
     	}
    -}

    +}
    -
    -
    -
    ====== Add stubs
    -
    -By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory.
    -
    -Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test.
    +
    +
    +
    +
    Add stubs
    +
    +

    By default Spring Cloud Contract Verifier is looking for stubs in src/test/resources/contracts 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 - -[source,groovy,indent=0] -

    -
    -
    -

    src/test/resources/contracts/myservice/shouldCreateUser.groovy -src/test/resources/contracts/myservice/shouldReturnUser.groovy

    +So with following structure

    -
    Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
    -
    - - `shouldCreateUser()`
    - - `shouldReturnUser()`
    -
    -===== Run plugin
    -
    -Plugin registers itself to be invoked before `check` 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 `generateContractTests` task.
    -
    -===== Default setup
    -
    -Default Gradle Plugin setup creates the following Gradle part of the build (it's a pseudocode)
    -
    -[source,groovy,indent=0]
    +
    src/test/resources/contracts/myservice/shouldCreateUser.groovy
    +src/test/resources/contracts/myservice/shouldReturnUser.groovy
    -

    contracts { +

    Spring Cloud Contract Verifier will create test class defaultBasePackage.MyService with two methods

    +
    +
    +
      +
    • +

      shouldCreateUser()

      +
    • +
    • +

      shouldReturnUser()

      +
    • +
    +
    +
    +
    +
    +
    Run plugin
    +
    +

    Plugin registers itself to be invoked before check 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 generateContractTests task.

    +
    +
    +
    +
    Default setup
    +
    +

    Default Gradle Plugin setup creates the following Gradle part of the build (it’s a pseudocode)

    +
    +
    +
    +
    contracts {
         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")

    -
    -
    -
    -
        // the following properties are used when you want to provide where the JAR with contract lays
    +    stubsOutputDir = project.file("${project.buildDir}/stubs")
    +
    +    // the following properties are used when you want to provide where the JAR with contract lays
         contractDependency {
             stringNotation = ''
         }
    @@ -1677,214 +2210,239 @@ Default Gradle Plugin setup creates the following Gradle part of the build (it's
         contractRepository {
             cacheDownloadedContracts(true)
         }
    -}
    -
    -
    -
    -

    tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { +} + +tasks.create(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') { baseName = project.name classifier = contracts.stubsSuffix from contractVerifier.stubsOutputDir -}

    -
    -
    -

    project.artifacts { +} + +project.artifacts { archives task -}

    -
    -
    -

    tasks.create(type: Copy, name: 'copyContracts') { +} + +tasks.create(type: Copy, name: 'copyContracts') { from contracts.contractsDslDir into contracts.stubsOutputDir -}

    -
    -
    -

    verifierStubsJar.dependsOn 'copyContracts'

    -
    -
    -

    publishing { +} + +verifierStubsJar.dependsOn 'copyContracts' + +publishing { publications { stubs(MavenPublication) { artifactId project.name artifact verifierStubsJar } } -}

    +}
    +
    +
    +
    +
    +
    Configure plugin
    +
    +

    To change default configuration just add contracts snippet to your Gradle config

    -
    ===== Configure plugin
    -
    -To change default configuration just add `contracts` snippet to your Gradle config
    -
    -[source,groovy,indent=0]
    -
    -
    -
    -

    contracts { +

    contracts {
     	testMode = 'MockMvc'
     	baseClassForTests = 'org.mycompany.tests'
     	generatedTestSourcesDir = project.file('src/generatedContract')
    -}

    +}
    +
    +
    +
    +
    Configuration options
    +
    +
      +
    • +

      testMode - defines mode for acceptance tests. By default MockMvc which is based on Spring’s MockMvc. It can also be changed to JaxRsClient or to Explicit for real HTTP calls.

      +
    • +
    • +

      imports - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []

      +
    • +
    • +

      staticImports - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []

      +
    • +
    • +

      basePackageForTests - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests

      +
    • +
    • +

      baseClassForTests - base class for all generated tests. By default spock.lang.Specification if using Spock tests.

      +
    • +
    • +

      packageWithBaseClasses - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over baseClassForTests.

      +
    • +
    • +

      baseClassMappings - explicitly map contract package to a FQN of a base class. Takes precedence over packageWithBaseClasses and baseClassForTests.

      +
    • +
    • +

      ruleClassForTests - specifies Rule which should be added to generated test classes.

      +
    • +
    • +

      ignoredFiles - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []

      +
    • +
    • +

      contractsDslDir - directory containing contracts written using the GroovyDSL. By default $rootDir/src/test/resources/contracts

      +
    • +
    • +

      generatedTestSourcesDir - test source directory where tests generated from Groovy DSL should be placed. By default $buildDir/generated-test-sources/contractVerifier

      +
    • +
    • +

      stubsOutputDir - dir where the generated WireMock stubs from Groovy DSL should be placed

      +
    • +
    • +

      targetFramework - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework

      +
    • +
    +
    +
    +

    The following properties are used when you want to provide where the JAR with contract lays

    +
    +
    +
      +
    • +

      contractDependency - the Dependency that provides groupid:artifactid:version:classifier coordinates. You can use the contractDependency closure to set it up

      +
    • +
    • +

      contractsPath - if contract deps are downloaded will default to groupid/artifactid where groupid will be slash separated. Otherwise will scan contracts under provided directory

      +
    • +
    • +

      contractsWorkOffline - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo)

      +
    • +
    +
    +
    +
    +
    Single base class for all tests
    +
    +

    When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified.

    -
    ====== Configuration options
    +
    abstract class BaseMockMvcSpec extends Specification {
     
    - - **testMode** - defines mode for acceptance tests. By default MockMvc which is based on Spring's MockMvc. It can also be changed to **JaxRsClient** or to **Explicit** for real HTTP calls.
    - - **imports** - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array []
    - - **staticImports** - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array []
    - - **basePackageForTests** - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests
    - - **baseClassForTests** - base class for all generated tests. By default `spock.lang.Specification` if using Spock tests.
    - - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over **baseClassForTests**.
    - - **baseClassMappings** - explicitly map contract package to a FQN of a base class. Takes precedence over **packageWithBaseClasses** and **baseClassForTests**.
    - - **ruleClassForTests** - specifies Rule which should be added to generated test classes.
    - - **ignoredFiles** - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array []
    - - **contractsDslDir** - directory containing contracts written using the GroovyDSL. By default `$rootDir/src/test/resources/contracts`
    - - **generatedTestSourcesDir** - test source directory where tests generated from Groovy DSL should be placed. By default `$buildDir/generated-test-sources/contractVerifier`
    - - **stubsOutputDir** - dir where the generated WireMock stubs from Groovy DSL should be placed
    - - **targetFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
    +	def setup() {
    +		RestAssuredMockMvc.standaloneSetup(new PairIdController())
    +	}
     
    -The following properties are used when you want to provide where the JAR with contract lays
    +	void isProperCorrelationId(Integer correlationId) {
    +		assert correlationId == 123456
    +	}
     
    - - **contractDependency** - the Dependency that provides `groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` closure to set it up
    - - **contractsPath** - if contract deps are downloaded will default to `groupid/artifactid` where `groupid` will be slash separated. Otherwise will scan contracts under provided directory
    - - **contractsWorkOffline** - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo)
    +	void isEmpty(String value) {
    +		assert value == null
    +	}
     
    -====== Single base class for all tests
    -
    -When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified.
    -
    -[source,groovy,indent=0]
    +}
    -

    abstract class BaseMockMvcSpec extends Specification {

    -
    -
    -
    -
    def setup() {
    -	RestAssuredMockMvc.standaloneSetup(new PairIdController())
    -}
    +

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

    -
    -
    -
    void isProperCorrelationId(Integer correlationId) {
    -	assert correlationId == 123456
    -}
    -
    -
    -
    -
    -
    void isEmpty(String value) {
    -	assert value == null
    -}
    +
    +
    Different base classes for contracts
    +
    +

    If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get +extended by the autogenerated tests. You have two options:

    +
    +
      +
    • +

      follow a convention by providing the packageWithBaseClasses

      +
    • +
    • +

      provide explicit mapping via baseClassMappings

      +
    • +
    -

    }

    +

    Convention

    +
    +
    +

    The convention is such that if you have a contract under e.g. src/test/resources/contract/foo/bar/baz/ and provide the value of the packageWithBaseClasses property +to com.example.base then we will assume that there is a BarBazBase class under com.example.base package. In other words we take last two parts of package +if they exist and form a class with a Base suffix. Takes precedence over baseClassForTests. Example of usage in the contracts closure:

    -
    In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class
    -should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server.
    -
    -====== Different base classes for contracts
    -
    -If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get
    -extended by the autogenerated tests. You have two options:
    -
    - - follow a convention by providing the `packageWithBaseClasses`
    - - provide explicit mapping via `baseClassMappings`
    -
    -*Convention*
    -
    -The convention is such that if you have a contract under e.g. `src/test/resources/contract/foo/bar/baz/` and provide the value of the `packageWithBaseClasses` property
    -to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. In other words we take last two parts of package
    -if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage in the `contracts` closure:
    -
    -[source,groovy,indent=0]
    +
    packageWithBaseClasses = 'com.example.base'
    -

    packageWithBaseClasses = 'com.example.base'

    +

    Mapping

    +
    +
    +

    You can manually map a regular expression of the contract’s package to fully qualified name of the base class for the matched contract. +Let’s take a look at the following example:

    -
    *Mapping*
    -
    -You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract.
    -Let's take a look at the following example:
    -
    -[source,groovy,indent=0]
    -
    -
    -
    -

    baseClassForTests = "com.example.FooBase" +

    baseClassForTests = "com.example.FooBase"
     baseClassMappings {
    -	baseClassMapping('./com/.', 'com.example.ComBase')
    -	baseClassMapping('./bar/.':'com.example.BarBase')
    -}

    -
    -
    -
    -
    Let's assume that you have contracts under
    - - `src/test/resources/contract/com/`
    - - `src/test/resources/contract/foo/`
    -
    -By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide
    -the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
    -will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
    -
    -===== Invoking generated tests
    -
    -To ensure that provider side is complaint with defined contracts, you need to invoke:
    -
    -[source,bash,indent=0]
    -
    -
    -
    -
    /gradlew generateContractTests test
    -
    -
    ===== Spring Cloud Contract Verifier on consumer side
    -
    -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't want to use Stub Runner then you need to copy contracts stored in
    -`src/test/resources/contracts` and generate WireMock json stubs using:
    -
    -[source,bash,indent=0]
    -
    -
    -
    -
    /gradlew generateClientStubs
    -
    -
    Note that `stubsOutputDir` option has to be set for stub generation to work.
    -
    -When present, json stubs can be used in consumer automated tests.
    -
    -[source,groovy,indent=0]
    + baseClassMapping('.*/com/.*', 'com.example.ComBase') + baseClassMapping('.*/bar/.*':'com.example.BarBase') +}
    -

    @ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application) -class LoanApplicationServiceSpec extends Specification {

    +

    Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

    -
    +
    +

    By providing the baseClassForTests we have a fallback in case mapping didn’t succeed (you could also provide +the packageWithBaseClasses as fallback). That way the tests generated from src/test/resources/contract/com/ contracts +will be extending the com.example.ComBase whereas the rest of tests will extend com.example.FooBase.

    +
    +
    +
    +
    +
    Invoking generated tests
    +
    +

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

    +
    +
    -
    @ClassRule
    -@Shared
    -WireMockClassRule wireMockRule == new WireMockClassRule()
    +
    ./gradlew generateContractTests test
    -
    +
    +
    +
    Spring Cloud Contract Verifier on consumer side
    +
    +

    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’t want to use Stub Runner then you need to copy contracts stored in +src/test/resources/contracts and generate WireMock json stubs using:

    +
    +
    -
    @Autowired
    -LoanApplicationService sut
    +
    ./gradlew generateClientStubs
    -
    +
    +

    Note that stubsOutputDir option has to be set for stub generation to work.

    +
    +
    +

    When present, json stubs can be used in consumer automated tests.

    +
    +
    -
     def 'should successfully apply for loan'() {
    +
    @ContextConfiguration(loader == SpringApplicationContextLoader, classes == Application)
    +class LoanApplicationServiceSpec extends Specification {
    +
    + @ClassRule
    + @Shared
    + WireMockClassRule wireMockRule == new WireMockClassRule()
    +
    + @Autowired
    + LoanApplicationService sut
    +
    + def 'should successfully apply for loan'() {
        given:
      	LoanApplication application =
     			new LoanApplication(client: new Client(clientPesel: '12345678901'), amount: 123.123)
    @@ -1894,24 +2452,24 @@ LoanApplicationService sut
    loanApplication.loanApplicationStatus == LoanApplicationStatus.LOAN_APPLIED loanApplication.rejectionReason == null } -}
    -
    -
    -
    -
    -
    Underneath LoanApplication makes a call to FraudDetection service. This request is handled by WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
    -
    -==== Using in your Maven project
    -
    -===== Add maven plugin
    -
    -Add the Spring Cloud Contract BOM
    -
    -[source,xml,indent=0]
    +}
    -

    <dependencyManagement> +

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

    +
    +
    +
    +
    +

    2.3.2. Using in your Maven project

    +
    +
    Add maven plugin
    +
    +

    Add the Spring Cloud Contract BOM

    +
    +
    +
    +
    <dependencyManagement>
     	<dependencies>
     		<dependency>
     			<groupId>org.springframework.cloud</groupId>
    @@ -1921,17 +2479,15 @@ Add the Spring Cloud Contract BOM
     			<scope>import</scope>
     		</dependency>
     	</dependencies>
    -</dependencyManagement>

    -
    -
    -
    -
    Next, the `Spring Cloud Contract Verifier` Maven plugin
    -
    -[source,xml,indent=0]
    +</dependencyManagement>
    -

    <plugin> +

    Next, the Spring Cloud Contract Verifier Maven plugin

    +
    +
    +
    +
    <plugin>
     	<groupId>org.springframework.cloud</groupId>
     	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
     	<version>${spring-cloud-contract.version}</version>
    @@ -1939,22 +2495,21 @@ Add the Spring Cloud Contract BOM
     	<configuration>
     		<packageWithBaseClasses>com.example.fraud</packageWithBaseClasses>
     	</configuration>
    -</plugin>

    -
    -
    -
    -
    You can read more in the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin Docs]
    -
    -====== Maven and Rest Assured 2.0
    -
    -By default Rest Assured 3.x is added to the classpath. However in order to give the users the
    -opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath.
    -
    -[source,groovy,indent=0]
    +</plugin>
    -

    <plugin> +

    You can read more in the Spring Cloud Contract Maven Plugin Docs

    +
    +
    +
    Maven and Rest Assured 2.0
    +
    +

    By default Rest Assured 3.x is added to the classpath. However in order to give the users the +opportunity to use Rest Assured 2.x it’s enough to add it to the plugins classpath.

    +
    +
    +
    +
    <plugin>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-contract-maven-plugin</artifactId>
         <version>${spring-cloud-contract.version}</version>
    @@ -1981,12 +2536,11 @@ opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpa
                <scope>compile</scope>
             </dependency>
         </dependencies>
    -</plugin>

    -
    -
    -

    <dependencies> - <!-- all dependencies -→ - <!-- you can exclude rest-assured from spring-cloud-contract-verifier -→ +</plugin> + +<dependencies> + <!-- all dependencies --> + <!-- you can exclude rest-assured from spring-cloud-contract-verifier --> <dependency> <groupId>com.jayway.restassured</groupId> <artifactId>rest-assured</artifactId> @@ -1999,26 +2553,26 @@ opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpa <version>2.5.0</version> <scope>test</scope> </dependency> -</dependencies>

    -
    -
    -
    -
    That way the plugin will automatically see that Rest Assured 3.x is present on the classpath
    -and will modify the imports accordingly.
    -
    -====== Snapshot versions for Maven
    -
    -For Snapshot / Milestone versions you have to add the following section to your `pom.xml`
    -
    -[source,xml,indent=0]
    +</dependencies>
    -

    <repositories> +

    That way the plugin will automatically see that Rest Assured 3.x is present on the classpath +and will modify the imports accordingly.

    +
    +
    +
    +
    Snapshot versions for Maven
    +
    +

    For Snapshot / Milestone versions you have to add the following section to your pom.xml

    +
    +
    +
    +
    <repositories>
     	<repository>
     		<id>spring-snapshots</id>
     		<name>Spring Snapshots</name>
    -		<url>https://repo.spring.io/snapshot</url>;
    +		<url>https://repo.spring.io/snapshot</url>
     		<snapshots>
     			<enabled>true</enabled>
     		</snapshots>
    @@ -2026,7 +2580,7 @@ For Snapshot / Milestone versions you have to add the following section to your
     	<repository>
     		<id>spring-milestones</id>
     		<name>Spring Milestones</name>
    -		<url>https://repo.spring.io/milestone</url>;
    +		<url>https://repo.spring.io/milestone</url>
     		<snapshots>
     			<enabled>false</enabled>
     		</snapshots>
    @@ -2034,7 +2588,7 @@ For Snapshot / Milestone versions you have to add the following section to your
     	<repository>
     		<id>spring-releases</id>
     		<name>Spring Releases</name>
    -		<url>https://repo.spring.io/release</url>;
    +		<url>https://repo.spring.io/release</url>
     		<snapshots>
     			<enabled>false</enabled>
     		</snapshots>
    @@ -2044,7 +2598,7 @@ For Snapshot / Milestone versions you have to add the following section to your
     	<pluginRepository>
     		<id>spring-snapshots</id>
     		<name>Spring Snapshots</name>
    -		<url>https://repo.spring.io/snapshot</url>;
    +		<url>https://repo.spring.io/snapshot</url>
     		<snapshots>
     			<enabled>true</enabled>
     		</snapshots>
    @@ -2052,7 +2606,7 @@ For Snapshot / Milestone versions you have to add the following section to your
     	<pluginRepository>
     		<id>spring-milestones</id>
     		<name>Spring Milestones</name>
    -		<url>https://repo.spring.io/milestone</url>;
    +		<url>https://repo.spring.io/milestone</url>
     		<snapshots>
     			<enabled>false</enabled>
     		</snapshots>
    @@ -2060,48 +2614,50 @@ For Snapshot / Milestone versions you have to add the following section to your
     	<pluginRepository>
     		<id>spring-releases</id>
     		<name>Spring Releases</name>
    -		<url>https://repo.spring.io/release</url>;
    +		<url>https://repo.spring.io/release</url>
     		<snapshots>
     			<enabled>false</enabled>
     		</snapshots>
     	</pluginRepository>
    -</pluginRepositories>

    +</pluginRepositories>
    -
    -
    -
    ===== Add stubs
    -
    -By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory.
    +
    +
    +
    +
    +
    Add stubs
    +
    +

    By default Spring Cloud Contract Verifier is looking for stubs in src/test/resources/contracts 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 - -[source,groovy,indent=0] -

    -
    -
    -

    src/test/resources/contracts/myservice/shouldCreateUser.groovy -src/test/resources/contracts/myservice/shouldReturnUser.groovy

    +So with following structure

    -
    Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods
    - - `shouldCreateUser()`
    - - `shouldReturnUser()`
    -
    -===== Run plugin
    -
    -Plugin goal `generateTests` is assigned to be invoked in phase `generate-test-sources`. 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 `generateTests` goal.
    -
    -===== Configure plugin
    -
    -To change default configuration just add `configuration` section to plugin definition or `execution` definition.
    -
    -[source,xml,indent=0]
    +
    src/test/resources/contracts/myservice/shouldCreateUser.groovy
    +src/test/resources/contracts/myservice/shouldReturnUser.groovy
    -

    <plugin> +

    Spring Cloud Contract Verifier will create test class defaultBasePackage.MyService with two methods + - shouldCreateUser() + - shouldReturnUser()

    +
    +
    +
    +
    Run plugin
    +
    +

    Plugin goal generateTests is assigned to be invoked in phase generate-test-sources. 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 generateTests goal.

    +
    +
    +
    +
    Configure plugin
    +
    +

    To change default configuration just add configuration section to plugin definition or execution definition.

    +
    +
    +
    +
    <plugin>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-contract-maven-plugin</artifactId>
         <executions>
    @@ -2117,143 +2673,198 @@ To change default configuration just add `configuration` section to plugin defin
             <basePackageForTests>org.springframework.cloud.verifier.twitter.place</basePackageForTests>
             <baseClassForTests>org.springframework.cloud.verifier.twitter.place.BaseMockMvcSpec</baseClassForTests>
         </configuration>
    -</plugin>

    +</plugin>
    +
    +
    +
    +
    Important configuration options
    +
    +
      +
    • +

      testMode - defines mode for acceptance tests. By default MockMvc which is based on Spring’s MockMvc. It can also be changed to JaxRsClient or to Explicit for real HTTP calls.

      +
    • +
    • +

      basePackageForTests - specifies base package for all generated tests. By default set to org.springframework.cloud.verifier.tests.

      +
    • +
    • +

      ruleClassForTests - specifies Rule which should be added to generated test classes.

      +
    • +
    • +

      baseClassForTests - base class for generated tests. By default spock.lang.Specification if using Spock tests.

      +
    • +
    • +

      contractsDirectory - directory containing contracts written using the GroovyDSL. By default /src/test/resources/contracts.

      +
    • +
    • +

      testFramework - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework

      +
    • +
    • +

      packageWithBaseClasses - instead of providing a fixed value for base class you can provide a package where all the base classes lay. +The convention is such that if you have a contract under src/test/resources/contract/foo/bar/baz/ and provide the value of this property +to com.example.base then we will assume that there is a BarBazBase class under com.example.base package. Takes precedence +over baseClassForTests

      +
    • +
    • +

      baseClassMappings - list of base class mappings that where you have to provide contractPackageRegex which is checked +against the package in which the contract lays and baseClassFQN that maps to fully qualified name of the base class for the matched +contract. If you have a contract under src/test/resources/contract/foo/bar/baz/ and map the property .*com.example.base.BaseClass then +the test class generated from these contracts will extend com.example.base.BaseClass. Takes precedence over packageWithBaseClasses + and baseClassForTests.

      +
    • +
    +
    +
    +

    If you want to download your contract definitions from a Maven repository you can use

    +
    +
    +
      +
    • +

      contractDependency - the contract dependency that contains all the packaged contracts

      +
    • +
    • +

      contractsPath - path to concrete contracts in the JAR with packaged contracts. Defaults to groupid/artifactid where gropuid is slash separated.

      +
    • +
    • +

      contractsWorkOffline - if the dependencies should be downloaded or local Maven only should be reused

      +
    • +
    • +

      contractsRepositoryUrl - DEPRECATED PROPERTY - please use the contractRepository closure - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones

      +
    • +
    • +

      contractRepository - closure where you can define properties related to repository with contracts

      +
      +
        +
      • +

        username - username to be used to connect to the repo

        +
      • +
      • +

        password - username to be used to connect to the repo

        +
      • +
      • +

        proxyHost - proxy host to be used to connect to the repo

        +
      • +
      • +

        proxyPort - proxy port to be used to connect to the repo

        +
      • +
      • +

        cacheDownloadedContracts - if you want to reuse download JARs that contain contract definitions. +We cache only non-snapshot, explicitly provided versions (e.g. + or 1.0.0.BUILD-SNAPSHOT won’t get cached). +By default this feature is turned on.

        +
      • +
      +
      +
    • +
    +
    +
    +
    +
    Single base class for all tests
    +
    +

    When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. +In this class you need to point to endpoint which should be verified.

    -
    ====== Important configuration options
    +
    package org.mycompany.tests
     
    - - **testMode** - defines mode for acceptance tests. By default `MockMvc` which is based on Spring's MockMvc. It can also be changed to `JaxRsClient` or to `Explicit` for real HTTP calls.
    - - **basePackageForTests** - specifies base package for all generated tests. By default set to `org.springframework.cloud.verifier.tests`.
    - - **ruleClassForTests** - specifies Rule which should be added to generated test classes.
    - - **baseClassForTests** - base class for generated tests. By default `spock.lang.Specification` if using Spock tests.
    - - **contractsDirectory** - directory containing contracts written using the GroovyDSL. By default `/src/test/resources/contracts`.
    - - **testFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework
    - - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay.
    -  The convention is such that if you have a contract under `src/test/resources/contract/foo/bar/baz/` and provide the value of this property
    -  to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. Takes precedence
    -  over **baseClassForTests**
    - - **baseClassMappings** - list of base class mappings that where you have to provide `contractPackageRegex` which is checked
    - against the package in which the contract lays and `baseClassFQN` that maps to fully qualified name of the base class for the matched
    - contract. If you have a contract under `src/test/resources/contract/foo/bar/baz/` and map the property `.*` -> `com.example.base.BaseClass` then
    - the test class generated from these contracts will extend `com.example.base.BaseClass`. Takes precedence over **packageWithBaseClasses**
    -  and **baseClassForTests**.
    -
    -If you want to download your contract definitions from a Maven repository you can use
    -
    - - **contractDependency** - the contract dependency that contains all the packaged contracts
    - - **contractsPath** - path to concrete contracts in the JAR with packaged contracts. Defaults to `groupid/artifactid` where `gropuid` is slash separated.
    - - **contractsWorkOffline** - if the dependencies should be downloaded or local Maven only should be reused
    - - **contractsRepositoryUrl** - *DEPRECATED PROPERTY - please use the `contractRepository` closure* - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones
    - - **contractRepository** - closure where you can define properties related to repository with contracts
    -    * **username** - username to be used to connect to the repo
    -    * **password** - username to be used to connect to the repo
    -    * **proxyHost** - proxy host to be used to connect to the repo
    -    * **proxyPort** - proxy port to be used to connect to the repo
    -    * **cacheDownloadedContracts** - if you want to reuse download JARs that contain contract definitions.
    - We cache only non-snapshot, explicitly provided versions (e.g. `+` or `1.0.0.BUILD-SNAPSHOT` won't get cached).
    - By default this feature is turned on.
    -
    -====== Single base class for all tests
    -
    -When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests.
    -In this class you need to point to endpoint which should be verified.
    -
    -[source,groovy,indent=0]
    -
    -
    -
    -

    package org.mycompany.tests

    -
    -
    -

    import org.mycompany.ExampleSpringController +import org.mycompany.ExampleSpringController import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc -import spock.lang.Specification

    -
    -
    -

    class MvcSpec extends Specification { +import spock.lang.Specification + +class MvcSpec extends Specification { def setup() { RestAssuredMockMvc.standaloneSetup(new ExampleSpringController()) } -}

    -
    -
    -
    -
    In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server.
    -
    -====== Different base classes for contracts
    -
    -If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get
    -extended by the autogenerated tests. You have two options:
    -
    - - follow a convention by providing the `packageWithBaseClasses`
    - - provide explicit mapping via `baseClassMappings`
    -
    -*Convention*
    -
    -The convention is such that if you have a contract under e.g. `src/test/resources/contract/hello/v1/` and provide the value of the `packageWithBaseClasses` property
    -to `hello` then we will assume that there is a `HelloV1Base` class under `hello` package. In other words we take last two parts of package
    -if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage:
    -
    -[source,xml,indent=0]
    +}
    -

    <plugin> +

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

    +
    +
    +
    +
    Different base classes for contracts
    +
    +

    If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get +extended by the autogenerated tests. You have two options:

    +
    +
    +
      +
    • +

      follow a convention by providing the packageWithBaseClasses

      +
    • +
    • +

      provide explicit mapping via baseClassMappings

      +
    • +
    +
    +
    +

    Convention

    +
    +
    +

    The convention is such that if you have a contract under e.g. src/test/resources/contract/hello/v1/ and provide the value of the packageWithBaseClasses property +to hello then we will assume that there is a HelloV1Base class under hello package. In other words we take last two parts of package +if they exist and form a class with a Base suffix. Takes precedence over baseClassForTests. Example of usage:

    +
    +
    +
    +
    <plugin>
     	<groupId>org.springframework.cloud</groupId>
     	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
     	<configuration>
     		<packageWithBaseClasses>hello</packageWithBaseClasses>
     	</configuration>
    -</plugin>

    -
    -
    -
    -
    *Mapping*
    -
    -You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract.
    -You have to provide a list `baseClassMappings` of `baseClassMapping` that takes a `contractPackageRegex` to `baseClassFQN` mapping.
    -Let's take a look at the following example:
    -
    -[source,xml,indent=0]
    +</plugin>
    -

    <plugin> +

    Mapping

    +
    +
    +

    You can manually map a regular expression of the contract’s package to fully qualified name of the base class for the matched contract. +You have to provide a list baseClassMappings of baseClassMapping that takes a contractPackageRegex to baseClassFQN mapping. +Let’s take a look at the following example:

    +
    +
    +
    +
    <plugin>
     	<groupId>org.springframework.cloud</groupId>
     	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
     	<configuration>
     		<baseClassForTests>com.example.FooBase</baseClassForTests>
     		<baseClassMappings>
     			<baseClassMapping>
    -				<contractPackageRegex>.com.</contractPackageRegex>
    +				<contractPackageRegex>.*com.*</contractPackageRegex>
     				<baseClassFQN>com.example.TestBase</baseClassFQN>
     			</baseClassMapping>
     		</baseClassMappings>
     	</configuration>
    -</plugin>

    -
    -
    -
    -
    Let's assume that you have contracts under
    - - `src/test/resources/contract/com/`
    - - `src/test/resources/contract/foo/`
    -
    -By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide
    -the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts
    -will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`.
    -
    -===== Invoking generated tests
    -
    -Spring Cloud Contract Maven Plugin generates verification code into directory `/generated-test-sources/contractVerifier` and attach this directory to `testCompile` goal.
    -
    -For Groovy Spock code use:
    -
    -[source,xml,indent=0]
    +</plugin>
    -

    <plugin> +

    Let’s assume that you have contracts under + - src/test/resources/contract/com/ + - src/test/resources/contract/foo/

    +
    +
    +

    By providing the baseClassForTests we have a fallback in case mapping didn’t succeed (you could also provide +the packageWithBaseClasses as fallback). That way the tests generated from src/test/resources/contract/com/ contracts +will be extending the com.example.ComBase whereas the rest of tests will extend com.example.FooBase.

    +
    +
    +
    +
    +
    Invoking generated tests
    +
    +

    Spring Cloud Contract Maven Plugin generates verification code into directory /generated-test-sources/contractVerifier and attach this directory to testCompile goal.

    +
    +
    +

    For Groovy Spock code use:

    +
    +
    +
    +
    <plugin>
     	<groupId>org.codehaus.gmavenplus</groupId>
     	<artifactId>gmavenplus-plugin</artifactId>
     	<version>1.5</version>
    @@ -2269,60 +2880,60 @@ For Groovy Spock code use:
     			<testSource>
     				<directory>${project.basedir}/src/test/groovy</directory>
     				<includes>
    -					<include>/.groovy</include>
    +					<include>**/*.groovy</include>
     				</includes>
     			</testSource>
     			<testSource>
     				<directory>${project.build.directory}/generated-test-sources/contractVerifier</directory>
     				<includes>
    -					<include>/.groovy</include>
    +					<include>**/*.groovy</include>
     				</includes>
     			</testSource>
     		</testSources>
     	</configuration>
    -</plugin>

    +</plugin>
    +
    +
    +
    +

    To ensure that provider side is complaint with defined contracts, you need to invoke mvn generateTest test

    +
    +
    +
    +
    FAQ with Maven Plugin
    +
    +
    Maven Plugin and STS
    +
    +

    In case you see the following exception while using STS

    +
    +
    +
    +STS Exception +
    +
    +
    +

    when you click on the marker you should see sth like this

    -
    To ensure that provider side is complaint with defined contracts, you need to invoke `mvn generateTest test`
    -
    -===== FAQ with Maven Plugin
    -
    -====== Maven Plugin and STS
    -
    -In case you see the following exception while using STS
    -
    -image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/1.0.x/docs/src/main/asciidoc/images/sts_exception.png[STS Exception]
    -
    -when you click on the marker you should see sth like this
    -
    -[source,bash]
    -
    -
    -
    -
    -
     plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
    +
     plugin:1.1.0.M1:convert:default-convert:process-test-resources) org.apache.maven.plugin.PluginExecutionException: Execution default-convert of goal org.springframework.cloud:spring-
      cloud-contract-maven-plugin:1.1.0.M1:convert failed. at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145) at
      org.eclipse.m2e.core.internal.embedder.MavenImpl.execute(MavenImpl.java:331) at org.eclipse.m2e.core.internal.embedder.MavenImpl$11.call(MavenImpl.java:1362) at
     ...
      org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.lang.NullPointerException at
      org.eclipse.m2e.core.internal.builder.plexusbuildapi.EclipseIncrementalBuildContext.hasDelta(EclipseIncrementalBuildContext.java:53) at
    - org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
    -
    -
    -
    -
    -
    In order to fix this issue just provide the following section in your `pom.xml`
    -
    -[source,xml]
    + org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at
    -

    <build> +

    In order to fix this issue just provide the following section in your pom.xml

    +
    +
    +
    +
    <build>
         <pluginManagement>
             <plugins>
    -            <!--This plugin’s configuration is used to store Eclipse m2e settings
    -                only. It has no influence on the Maven build itself. -→
    +            <!--This plugin's configuration is used to store Eclipse m2e settings
    +                only. It has no influence on the Maven build itself. -->
                 <plugin>
                     <groupId>org.eclipse.m2e</groupId>
                     <artifactId>lifecycle-mapping</artifactId>
    @@ -2349,29 +2960,30 @@ when you click on the marker you should see sth like this
                 </plugin>
             </plugins>
         </pluginManagement>
    -</build>

    +</build>
    -
    -
    -
    ===== Spring Cloud Contract Verifier on consumer side
    -
    -You can actually use the Spring Cloud Contract Verifier also for the consumer side!
    +
    +
    +
    +
    +
    Spring Cloud Contract Verifier on consumer side
    +
    +

    You can actually use the Spring Cloud Contract Verifier also for the consumer side! You can use the plugin so that it only converts the contracts and generates the stubs. To achieve that you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. You need to copy contracts stored in -`src/test/resources/contracts` and generate WireMock json stubs using: -`mvn generateStubs` command. By default generated WireMock mapping is -stored in directory `target/mappings`. Your project should create from -this generated mappings additional artifact with classifier `stubs` for -easy deploy to maven repository. - -Sample configuration: - -[source,xml,indent=0] -

    +src/test/resources/contracts and generate WireMock json stubs using: +mvn generateStubs command. By default generated WireMock mapping is +stored in directory target/mappings. Your project should create from +this generated mappings additional artifact with classifier stubs for +easy deploy to maven repository.

    -

    <plugin> +

    Sample configuration:

    +
    +
    +
    +
    <plugin>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-contract-maven-plugin</artifactId>
         <version>${verifier-plugin.version}</version>
    @@ -2383,30 +2995,23 @@ Sample configuration:
                 </goals>
             </execution>
         </executions>
    -</plugin>

    -
    -
    -
    -
    When present, json stubs can be used in consumer automated tests.
    -
    -[source,groovy,indent=0]
    +</plugin>
    -

    @RunWith(SpringTestRunner.class) +

    When present, json stubs can be used in consumer automated tests.

    +
    +
    +
    +
    @RunWith(SpringTestRunner.class)
     @SpringBootTest
     @AutoConfigureStubRunner
    -public class LoanApplicationServiceTests {

    -
    -
    -
    -
    @Autowired
    -LoanApplicationService service;
    -
    -
    -
    -
    -
      @Test
    +public class LoanApplicationServiceTests {
    +
    +  @Autowired
    +  LoanApplicationService service;
    +
    +  @Test
       public void shouldSuccessfullyApplyForLoan() {
         //given:
      	LoanApplication application =
    @@ -2417,182 +3022,258 @@ LoanApplicationService service;
    assertThat(loanApplication.loanApplicationStatus).isEqualTo(LoanApplicationStatus.LOAN_APPLIED); assertThat(loanApplication.rejectionReason).isNull(); } -} -
    -
    -
    -
    -
    Underneath `LoanApplication` makes a call to the `FraudDetection` service. This request is handled by
    -a WireMock server configured using stubs generated by Spring Cloud Contract Verifier.
    -
    -==== Scenarios
    -
    -It'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.
    -
    -[source,indent=0]
    +}
    -

    my_contracts_dir\ +

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

    +
    +
    +
    +
    +

    2.3.3. Scenarios

    +
    +

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

    +
    +
    +
    +
    my_contracts_dir\
       scenario1\
         1_login.groovy
         2_showCart.groovy
    -    3_logout.groovy

    -
    -
    -
    -
    Such tree will cause Spring Cloud Contract Verifier generating WireMock's scenario with name `scenario1` and three steps:
    -
    - - login marked as `Started` pointing to:
    - - showCart marked as `Step1` pointing to:
    - - logout marked as `Step2` which will close the scenario.
    -
    -More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html]
    -
    -Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.
    -
    -==== Stubs and transitive dependencies
    -
    -The Maven and Gradle plugin that we're created are adding the tasks that create the stubs jar for you. What can be problematic
    -is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact
    -even though you have a couple of different jars, all of them share one pom:
    -
    -[source,bash,indent=0]
    + 3_logout.groovy
    -

    ├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar +

    Such tree will cause Spring Cloud Contract Verifier generating WireMock’s scenario with name scenario1 and three steps:

    +
    +
    +
      +
    • +

      login marked as Started pointing to:

      +
    • +
    • +

      showCart marked as Step1 pointing to:

      +
    • +
    • +

      logout marked as Step2 which will close the scenario.

      +
    • +
    +
    +
    +

    More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html

    +
    +
    +

    Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution.

    +
    +
    +
    +

    2.3.4. Stubs and transitive dependencies

    +
    +

    The Maven and Gradle plugin that we’re created are adding the tasks that create the stubs jar for you. What can be problematic +is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact +even though you have a couple of different jars, all of them share one pom:

    +
    +
    +
    +
    ├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar
     ├── github-webhook-0.0.1.BUILD-20160903.075506-1-stubs.jar.sha1
     ├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar
     ├── github-webhook-0.0.1.BUILD-20160903.075655-2-stubs.jar.sha1
     ├── github-webhook-0.0.1.BUILD-SNAPSHOT.jar
     ├── github-webhook-0.0.1.BUILD-SNAPSHOT.pom
     ├── github-webhook-0.0.1.BUILD-SNAPSHOT-stubs.jar
    -├── …​
    -└── …​

    -
    -
    -
    -
    There are three possibilities of working with those dependencies so as not to have any issues with transitive dependencies.
    -
    -*Mark all application dependencies as optional*
    -
    -If in the `github-webhook` application we would mark all of our dependencies as optional, when you include the
    -`github-webhook` stubs in another application (or when that dependency gets downloaded by Stub Runner) then, since
    -all of the depenencies are optional, they will not get downloaded.
    -
    -*Create a separate artifactid for stubs*
    -
    -If you create a separate artifactid then you can set it up in whatever way you wish. For example by having no dependencies at all.
    -
    -*Exclude dependencies on the consumer side*
    -
    -As a consumer, if you add the stub dependency to your classpath you can explicitly exclude the unwanted dependencies.
    -
    -=== Spring Cloud Contract Verifier Messaging
    -
    -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 create one yourself and use it.
    -
    -==== Integrations
    -
    -You can use one of the four integration configurations:
    -
    -- Apache Camel
    -- Spring Integration
    -- Spring Cloud Stream
    -- Spring AMQP
    -
    -Since we're using Spring Boot then if you have added one of the aforementioned libraries
    -to the classpath then automatically all the messaging configuration will be set up.
    -
    -IMPORTANT: Remember to put `@AutoConfigureMessageVerifier` on the base class of your
    -generated tests. Otherwise messaging part of Spring Cloud Contract Verifier will not work.
    -
    -IMPORTANT: If you want to use Spring Cloud Stream remember to add a
    -`org.springframework.cloud:spring-cloud-stream-test-support` dependency.
    -
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    +├── ... +└── ...
    -

    <dependency> +

    There are three possibilities of working with those dependencies so as not to have any issues with transitive dependencies.

    +
    +
    +

    Mark all application dependencies as optional

    +
    +
    +

    If in the github-webhook application we would mark all of our dependencies as optional, when you include the +github-webhook stubs in another application (or when that dependency gets downloaded by Stub Runner) then, since +all of the depenencies are optional, they will not get downloaded.

    +
    +
    +

    Create a separate artifactid for stubs

    +
    +
    +

    If you create a separate artifactid then you can set it up in whatever way you wish. For example by having no dependencies at all.

    +
    +
    +

    Exclude dependencies on the consumer side

    +
    +
    +

    As a consumer, if you add the stub dependency to your classpath you can explicitly exclude the unwanted dependencies.

    +
    +
    +
    +
    +

    2.4. Spring Cloud Contract Verifier Messaging

    +
    +

    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 create one yourself and use it.

    +
    +
    +

    2.4.1. Integrations

    +
    +

    You can use one of the four integration configurations:

    +
    +
    +
      +
    • +

      Apache Camel

      +
    • +
    • +

      Spring Integration

      +
    • +
    • +

      Spring Cloud Stream

      +
    • +
    • +

      Spring AMQP

      +
    • +
    +
    +
    +

    Since we’re using Spring Boot then if you have added one of the aforementioned libraries +to the classpath then automatically all the messaging configuration will be set up.

    +
    +
    + + + + + +
    + + +Remember to put @AutoConfigureMessageVerifier on the base class of your +generated tests. Otherwise messaging part of Spring Cloud Contract Verifier will not work. +
    +
    +
    + + + + + +
    + + +If you want to use Spring Cloud Stream remember to add a +org.springframework.cloud:spring-cloud-stream-test-support dependency. +
    +
    +
    +
    Maven
    +
    +
    <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-stream-test-support</artifactId>
         <scope>test</scope>
    -</dependency>

    +</dependency>
    -
    +
    +
    +
    Gradle
    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    +
    testCompile "org.springframework.cloud:spring-cloud-stream-test-support"
    +
    +
    +

    2.4.2. Manual Integration Testing

    -

    testCompile "org.springframework.cloud:spring-cloud-stream-test-support"

    -
    -
    -
    -
    ==== Manual Integration Testing
    -
    -The main interface used by the tests is the `org.springframework.cloud.contract.verifier.messaging.MessageVerifier`.
    +

    The main interface used by the tests is the org.springframework.cloud.contract.verifier.messaging.MessageVerifier. It defines how to send and receive messages. You can create your own implementation to achieve the -same goal. - -In the a test you can inject a `ContractVerifierMessageExchange` to send and receive messages that follow the contract. -Then add `@AutoConfigureMessageVerifier` to your test, e.g. - -[source,java,indent=0]

    -
    +same goal.

    -

    @RunWith(SpringTestRunner.class) +

    In the a test you can inject a ContractVerifierMessageExchange to send and receive messages that follow the contract. +Then add @AutoConfigureMessageVerifier to your test, e.g.

    +
    +
    +
    +
    @RunWith(SpringTestRunner.class)
     @SpringBootTest
     @AutoConfigureMessageVerifier
    -public static class MessagingContractTests {

    -
    -
    -
    -
      @Autowired
    +public static class MessagingContractTests {
    +
    +  @Autowired
       private MessageVerifier verifier;
       ...
    -}
    +}
    +
    + + + + + +
    + + +If your tests require stubs as well, then +@AutoConfigureStubRunner includes the messaging configuration, so +you only need the one annotation. +
    +
    +
    +
    +

    2.4.3. Publisher side test generation

    +
    +

    Having the input or outputMessage sections in your DSL will result in creation of tests on the publisher’s side. By default +JUnit tests will be created, however there is also a possibility to create Spock tests.

    +
    +
    +

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

    +
    +
    +
      +
    • +

      Scenario 1: there is no input message that produces an output one. The output message is triggered by a component +inside the application (e.g. scheduler)

      +
    • +
    • +

      Scenario 2: the input message triggers an output message

      +
    • +
    • +

      Scenario 3: the input message is consumed and there is no output message

      +
    • +
    +
    +
    + + + + + +
    + + +The destination passed to messageFrom or sentTo can have different meanings for different + messaging implementations. For Stream and Integration it’s first resolved as a destination of a channel, and then if + there is no such destination it’s resolved as a channel name. For Camel that’s a certain component (e.x. jms). +
    +
    +
    +

    Example for Camel:

    +
    +
    +
    Scenario 1 (no input message)
    +
    +

    For the given contract:

    +
    -
    NOTE: If your tests require stubs as well, then
    -`@AutoConfigureStubRunner` includes the messaging configuration, so
    -you only need the one annotation.
    -
    -==== Publisher side test generation
    -
    -Having the `input` or `outputMessage` sections in your DSL will result in creation of tests on the publisher's side. By default
    -JUnit tests will be created, however there is also a possibility to create Spock tests.
    -
    -There are 3 main scenarios that we should take into consideration:
    -
    -- Scenario 1: there is no input message that produces an output one. The output message is triggered by a component
    -inside the application (e.g. scheduler)
    -- Scenario 2: the input message triggers an output message
    -- Scenario 3: the input message is consumed and there is no output message
    -
    -IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different meanings for different
    - messaging implementations. For *Stream* and *Integration* it's first resolved as a `destination` of a channel, and then if
    - there is no such `destination` it's resolved as a channel name. For *Camel* that's a certain component (e.x. `jms`).
    -
    -Example for Camel:
    -
    -===== Scenario 1 (no input message)
    -
    -For the given contract:
    -
    -[source,groovy]
    -
    -
    -
    -

    def contractDsl = Contract.make { +

    def contractDsl = Contract.make {
     	label 'some_label'
     	input {
     		triggeredBy('bookReturnedTriggered()')
    @@ -2605,25 +3286,19 @@ For the given contract:
     			messagingContentType(applicationJson())
     		}
     	}
    -}

    +}
    +
    +
    +
    +

    The following JUnit test will be created:

    -
    The following JUnit test will be created:
    +
    '''
    + // when:
    +  bookReturnedTriggered();
     
    -[source,groovy]
    -
    -
    -
    -
    -
    -
    // when:
    - bookReturnedTriggered();
    -
    -
    -
    -
    -
     // then:
    + // then:
       ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output");
       assertThat(response).isNotNull();
       assertThat(response.getHeader("BOOK-NAME")).isNotNull();
    @@ -2633,47 +3308,39 @@ For the given contract:
      // and:
       DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
       assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
    -'''
    -
    -
    -
    -
    -
    And the following Spock test would be created:
    -
    -[source,groovy]
    -
    -
    -
    -
    -
    -
    when:
    - bookReturnedTriggered()
    -
    -
    -
    -
    -
    then:
    - ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
    - assert response != null
    - response.getHeader('BOOK-NAME')?.toString()  == 'foo'
    - response.getHeader('contentType')?.toString()  == 'application/json'
    -and:
    - DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
    - assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
    -
    -
    -
    -
    -
    -
    ===== Scenario 2 (output triggered by input)
    -
    -For the given contract:
    -
    -[source,groovy]
    +'''
    -

    def contractDsl = Contract.make { +

    And the following Spock test would be created:

    +
    +
    +
    +
    '''
    + when:
    +  bookReturnedTriggered()
    +
    + then:
    +  ContractVerifierMessage response = contractVerifierMessaging.receive('activemq:output')
    +  assert response != null
    +  response.getHeader('BOOK-NAME')?.toString()  == 'foo'
    +  response.getHeader('contentType')?.toString()  == 'application/json'
    + and:
    +  DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload))
    +  assertThatJson(parsedJson).field("bookName").isEqualTo("foo")
    +
    +'''
    +
    +
    +
    +
    +
    Scenario 2 (output triggered by input)
    +
    +

    For the given contract:

    +
    +
    +
    +
    def contractDsl = Contract.make {
     	label 'some_label'
     	input {
     		messageFrom('jms:input')
    @@ -2693,81 +3360,69 @@ For the given contract:
     			header('BOOK-NAME', 'foo')
     		}
     	}
    -}

    +}
    +
    +
    +
    +

    The following JUnit test will be created:

    -
    The following JUnit test will be created:
    -
    -[source,groovy]
    -
    -
    -
    -
    -
    -
     ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +
    '''
    +// given:
    + ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
       "{\\"bookName\\":\\"foo\\"}"
     , headers()
    -  .header("sample", "header"));
    -
    -
    -
    -
    -
    contractVerifierMessaging.send(inputMessage, "jms:input");
    -
    -
    -
    -
    -
     ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
    +  .header("sample", "header"));
    +
    +// when:
    + contractVerifierMessaging.send(inputMessage, "jms:input");
    +
    +// then:
    + ContractVerifierMessage response = contractVerifierMessaging.receive("jms:output");
      assertThat(response).isNotNull();
      assertThat(response.getHeader("BOOK-NAME")).isNotNull();
      assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
     // and:
      DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
      assertThatJson(parsedJson).field("bookName").isEqualTo("foo");
    -'''
    -
    -
    -
    -
    -
    And the following Spock test would be created:
    -
    -[source,groovy]
    +'''
    -

    """\ +

    And the following Spock test would be created:

    +
    +
    +
    +
    """\
     given:
        ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
         '''{"bookName":"foo"}''',
         ['sample': 'header']
    -  )

    -
    -
    -

    when: - contractVerifierMessaging.send(inputMessage, 'jms:input')

    -
    -
    -

    then: + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:input') + +then: ContractVerifierMessage response = contractVerifierMessaging.receive('jms:output') assert response !- null response.getHeader('BOOK-NAME')?.toString() == 'foo' and: DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.payload)) assertThatJson(parsedJson).field("bookName").isEqualTo("foo") -"""

    +"""
    +
    +
    +
    +
    +
    Scenario 3 (no output message)
    +
    +

    For the given contract:

    -
    ===== Scenario 3 (no output message)
    -
    -For the given contract:
    -
    -[source,groovy]
    -
    -
    -
    -

    def contractDsl = Contract.make { +

    def contractDsl = Contract.make {
     	label 'some_label'
     	input {
     		messageFrom('jms:delete')
    @@ -2779,83 +3434,71 @@ For the given contract:
     		}
     		assertThat('bookWasDeleted()')
     	}
    -}

    +}
    +
    +
    +
    +

    The following JUnit test will be created:

    -
    The following JUnit test will be created:
    -
    -[source,groovy]
    -
    -
    -
    -
    -
    -
     ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +
    '''
    +// given:
    + ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
     	"{\\"bookName\\":\\"foo\\"}"
     , headers()
    -	.header("sample", "header"));
    + .header("sample", "header")); + +// when: + contractVerifierMessaging.send(inputMessage, "jms:delete"); + +// then: + bookWasDeleted(); +'''
    -
    -
    -
    contractVerifierMessaging.send(inputMessage, "jms:delete");
    -
    -
    -
    -
    -
     bookWasDeleted();
    -'''
    -
    +
    +

    And the following Spock test would be created:

    -
    And the following Spock test would be created:
    -
    -[source,groovy]
    -
    -
    -
    -
    -

    given: +

    '''
    +given:
     	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
     		\'\'\'{"bookName":"foo"}\'\'\',
     		['sample': 'header']
    -	)

    -
    -
    -

    when: - contractVerifierMessaging.send(inputMessage, 'jms:delete')

    -
    -
    -

    then: + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: noExceptionThrown() bookWasDeleted() -'''

    +'''
    -
    -
    -
    ==== Consumer Stub Side generation
    -
    -Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it's parsed on the consumer side
    -and proper stubbed routes are created.
    -
    -For more information please consult the Stub Runner Messaging sections.
    -
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    +
    +
    +

    2.4.4. Consumer Stub Side generation

    +
    +

    Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it’s parsed on the consumer side +and proper stubbed routes are created.

    +
    -

    <dependencies> +

    For more information please consult the Stub Runner Messaging sections.

    +
    +
    +
    Maven
    +
    +
    <dependencies>
     	<dependency>
     		<groupId>org.springframework.cloud</groupId>
     		<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    -	</dependency>

    -
    -
    -
    -
    	<dependency>
    +	</dependency>
    +
    +	<dependency>
     		<groupId>org.springframework.cloud</groupId>
     		<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
     		<scope>test</scope>
    @@ -2865,11 +3508,9 @@ For more information please consult the Stub Runner Messaging sections.
     		<artifactId>spring-cloud-stream-test-support</artifactId>
     		<scope>test</scope>
     	</dependency>
    -</dependencies>
    -
    -
    -
    -

    <dependencyManagement> +</dependencies> + +<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> @@ -2879,143 +3520,8 @@ For more information please consult the Stub Runner Messaging sections. <scope>import</scope> </dependency> </dependencies> -</dependencyManagement>

    +</dependencyManagement>
    -
    -
    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    -
    -
    -
    -

    ext { - contractsDir = file("mappings") - stubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/") -}

    -
    -
    -

    publishing { - publications { - stubs(MavenPublication) { - artifactId "${project.name}-stubs" - artifact verifierStubsJar - } - } -}

    -
    -
    -
    -
    === Spring Cloud Contract Stub Runner
    -
    -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.
    -
    -Copying the JSON files / setting the client side for messaging manually is out of the question.
    -
    -That's why we'll introduce Spring Cloud Contract Stub Runner that can download and run the stubs
    -automatically for you.
    -
    -==== Snapshot versions
    -
    -Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:
    -
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    -
    -
    -
    -

    <repositories> - <repository> - <id>spring-snapshots</id> - <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url>; - <snapshots> - <enabled>true</enabled> - </snapshots> - </repository> - <repository> - <id>spring-milestones</id> - <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url>; - <snapshots> - <enabled>false</enabled> - </snapshots> - </repository> - <repository> - <id>spring-releases</id> - <name>Spring Releases</name> - <url>https://repo.spring.io/release</url>; - <snapshots> - <enabled>false</enabled> - </snapshots> - </repository> -</repositories> -<pluginRepositories> - <pluginRepository> - <id>spring-snapshots</id> - <name>Spring Snapshots</name> - <url>https://repo.spring.io/snapshot</url>; - <snapshots> - <enabled>true</enabled> - </snapshots> - </pluginRepository> - <pluginRepository> - <id>spring-milestones</id> - <name>Spring Milestones</name> - <url>https://repo.spring.io/milestone</url>; - <snapshots> - <enabled>false</enabled> - </snapshots> - </pluginRepository> - <pluginRepository> - <id>spring-releases</id> - <name>Spring Releases</name> - <url>https://repo.spring.io/release</url>; - <snapshots> - <enabled>false</enabled> - </snapshots> - </pluginRepository> -</pluginRepositories>

    -
    -
    -
    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    -
    -
    -
    -

    buildscript { - repositories { - mavenCentral() - mavenLocal() - maven { url "http://repo.spring.io/snapshot" } - maven { url "http://repo.spring.io/milestone" } - maven { url "http://repo.spring.io/release" } - }

    -
    -
    -
    -
    ==== Publishing stubs as JARs
    -
    -The easiest approach would be to centralize the way stubs are kept. For example you can keep them as JARs in a Maven repository.
    -
    -TIP: For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to.
    -
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    -
    -
    -
    -

    <!-- First disable the default jar setup in the properties section-→ -Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0]

    -
    -
    -

    <!-- Next add the assembly plugin to your build -→ -Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer_with_restdocs/pom.xml[tags=assembly,indent=0]

    -
    -
    -

    <!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -→ -Unresolved directive in verifier/stubrunner.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer_with_restdocs/src/assembly/stub.xml[indent=0]

    Gradle
    @@ -3042,9 +3548,210 @@ publishing {
    +
    +

    2.5. Spring Cloud Contract Stub Runner

    +
    +

    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.

    +
    +
    +

    Copying the JSON files / setting the client side for messaging manually is out of the question.

    +
    +
    +

    That’s why we’ll introduce Spring Cloud Contract Stub Runner that can download and run the stubs +automatically for you.

    +
    +
    +

    2.5.1. Snapshot versions

    +
    +

    Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build:

    +
    +
    +
    Maven
    +
    +
    <repositories>
    +	<repository>
    +		<id>spring-snapshots</id>
    +		<name>Spring Snapshots</name>
    +		<url>https://repo.spring.io/snapshot</url>
    +		<snapshots>
    +			<enabled>true</enabled>
    +		</snapshots>
    +	</repository>
    +	<repository>
    +		<id>spring-milestones</id>
    +		<name>Spring Milestones</name>
    +		<url>https://repo.spring.io/milestone</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</repository>
    +	<repository>
    +		<id>spring-releases</id>
    +		<name>Spring Releases</name>
    +		<url>https://repo.spring.io/release</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</repository>
    +</repositories>
    +<pluginRepositories>
    +	<pluginRepository>
    +		<id>spring-snapshots</id>
    +		<name>Spring Snapshots</name>
    +		<url>https://repo.spring.io/snapshot</url>
    +		<snapshots>
    +			<enabled>true</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +	<pluginRepository>
    +		<id>spring-milestones</id>
    +		<name>Spring Milestones</name>
    +		<url>https://repo.spring.io/milestone</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +	<pluginRepository>
    +		<id>spring-releases</id>
    +		<name>Spring Releases</name>
    +		<url>https://repo.spring.io/release</url>
    +		<snapshots>
    +			<enabled>false</enabled>
    +		</snapshots>
    +	</pluginRepository>
    +</pluginRepositories>
    +
    +
    +
    +
    Gradle
    +
    +
    buildscript {
    +	repositories {
    +		mavenCentral()
    +		mavenLocal()
    +		maven { url "http://repo.spring.io/snapshot" }
    +		maven { url "http://repo.spring.io/milestone" }
    +		maven { url "http://repo.spring.io/release" }
    +	}
    +
    +
    +
    +
    +

    2.5.2. Publishing stubs as JARs

    +
    +

    The easiest approach would be to centralize the way stubs are kept. For example you can keep them as JARs in a Maven repository.

    +
    +
    + + + + + +
    + + +For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to. +
    +
    +
    +
    Maven
    +
    +
    <!-- First disable the default jar setup in the properties section-->
    +<!-- we don't want the verifier to do a jar for us -->
    +<spring.cloud.contract.verifier.skip>true</spring.cloud.contract.verifier.skip>
    +
    +<!-- Next add the assembly plugin to your build -->
    +<!-- we want the assembly plugin to generate the JAR -->
    +<plugin>
    +	<groupId>org.apache.maven.plugins</groupId>
    +	<artifactId>maven-assembly-plugin</artifactId>
    +	<executions>
    +		<execution>
    +			<id>stub</id>
    +			<phase>prepare-package</phase>
    +			<goals>
    +				<goal>single</goal>
    +			</goals>
    +			<inherited>false</inherited>
    +			<configuration>
    +				<attach>true</attach>
    +				<descriptor>${basedir}/src/assembly/stub.xml</descriptor>
    +			</configuration>
    +		</execution>
    +	</executions>
    +</plugin>
    +
    +<!-- Finally setup your assembly. Below you can find the contents of src/main/assembly/stub.xml -->
    +<assembly
    +	xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
    +	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +	xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    +	<id>stubs</id>
    +	<formats>
    +		<format>jar</format>
    +	</formats>
    +	<includeBaseDirectory>false</includeBaseDirectory>
    +	<fileSets>
    +		<fileSet>
    +			<directory>src/main/java</directory>
    +			<outputDirectory>/</outputDirectory>
    +			<includes>
    +				<include>**com/example/model/*.*</include>
    +			</includes>
    +		</fileSet>
    +		<fileSet>
    +			<directory>${project.build.directory}/classes</directory>
    +			<outputDirectory>/</outputDirectory>
    +			<includes>
    +				<include>**com/example/model/*.*</include>
    +			</includes>
    +		</fileSet>
    +		<fileSet>
    +			<directory>${project.build.directory}/snippets/stubs</directory>
    +			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings</outputDirectory>
    +			<includes>
    +				<include>**/*</include>
    +			</includes>
    +		</fileSet>
    +		<fileSet>
    +			<directory>${basedir}/src/test/resources/contracts</directory>
    +			<outputDirectory>META-INF/${project.groupId}/${project.artifactId}/${project.version}/contracts</outputDirectory>
    +			<includes>
    +				<include>**/*.groovy</include>
    +			</includes>
    +		</fileSet>
    +	</fileSets>
    +</assembly>
    +
    +
    +
    +
    Gradle
    +
    +
    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
    +		}
    +	}
    +}
    +
    +
    +
    -

    2.3. Stub Runner Core

    +

    2.6. Stub Runner Core

    Runs stubs for service collaborators. Treating stubs as contracts of services allows to use stub-runner as an implementation of Consumer Driven Contracts.

    @@ -3054,7 +3761,7 @@ publishing { For messaging, special stub routes are defined.

    -

    2.3.1. Retrieving stubs

    +

    2.6.1. Retrieving stubs

    You can pick the following options of acquiring stubs

    @@ -3239,7 +3946,7 @@ HTTP stubs without the need to download artifacts.

    -

    2.3.2. Running stubs

    +

    2.6.2. Running stubs

    Limitations
    @@ -3394,7 +4101,7 @@ mappings available for the given server:

    -

    2.4. Stub Runner JUnit Rule

    +

    2.7. Stub Runner JUnit Rule

    Stub Runner comes with a JUnit rule thanks to which you can very easily download and run stubs for given group and artifact id:

    @@ -3554,21 +4261,21 @@ If you don’t do this then whenever you try to send a message an exception
    -

    2.4.1. Maven settings

    +

    2.7.1. Maven settings

    The stub downloader honors Maven settings for a different local repository folder. Authentication details for repositories and profiles are currently not taken into account, so you need to specify it using the properties mentioned above.

    -

    2.4.2. Providing fixed ports

    +

    2.7.2. Providing fixed ports

    You can also run your stubs on fixed ports. You can do it in two different ways. One is to pass it in the properties, and the other via fluent API of JUnit rule.

    -

    2.4.3. Fluent API

    +

    2.7.3. Fluent API

    When using the StubRunnerRule you can add a stub to download and then pass the port for the last downloaded stub.

    @@ -3592,7 +4299,7 @@ then(rule.findStubUrl("fraudDetectionServer")).isEqualTo(URI.create("http://loca
    -

    2.4.4. Stub Runner with Spring

    +

    2.7.4. Stub Runner with Spring

    Sets up Spring configuration of the Stub Runner project.

    @@ -3740,7 +4447,7 @@ for every registered WireMock server. Example for Stub Runner ids
    -

    2.5. Stub Runner Spring Cloud

    +

    2.8. Stub Runner Spring Cloud

    Stub Runner can integrate with Spring Cloud.

    @@ -3758,7 +4465,7 @@ for every registered WireMock server. Example for Stub Runner ids
    -

    2.5.1. Stubbing Service Discovery

    +

    2.8.1. Stubbing Service Discovery

    The most important feature of Stub Runner Spring Cloud is the fact that it’s stubbing

    @@ -3831,7 +4538,7 @@ via a static block like presented below (example for Eureka)

    -

    2.5.2. Additional Configuration

    +

    2.8.2. Additional Configuration

    You can match the artifactId of the stub with the name of your app by using the stubrunner.idsToServiceIds: map. You can disable Stub Runner Ribbon support by providing: stubrunner.cloud.ribbon.enabled equal to false @@ -3855,7 +4562,7 @@ an existing DiscoveryClient its results will be ignored. However, i

    -

    2.6. Stub Runner Boot Application

    +

    2.9. Stub Runner Boot Application

    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.

    @@ -3865,7 +4572,7 @@ trigger the messaging labels and to access started WireMock servers.

    more about this in the "Microservice Deployment" article at Too Much Coding blog.

    -

    2.6.1. How to use it?

    +

    2.9.1. How to use it?

    Just add the

    @@ -3882,7 +4589,7 @@ trigger the messaging labels and to access started WireMock servers.

    -

    2.6.2. Endpoints

    +

    2.9.2. Endpoints

    HTTP
    @@ -3917,7 +4624,7 @@ trigger the messaging labels and to access started WireMock servers.

    -

    2.6.3. Example

    +

    2.9.3. Example

    @ContextConfiguration(classes = StubRunnerBoot, loader = SpringBootContextLoader)
    @@ -4011,7 +4718,7 @@ class StubRunnerBootSpec extends Specification {
     
    -

    2.6.4. Stub Runner Boot with Service Discovery

    +

    2.9.4. Stub Runner Boot with Service Discovery

    One of the possibilities of using Stub Runner Boot is to use it as a feed of stubs for "smoke-tests". What does it mean? Let’s assume that you don’t want to deploy 50 microservice to a test environment in order @@ -4073,7 +4780,7 @@ the Stub Runner Boot.

    -

    2.7. Stubs Per Consumer

    +

    2.10. Stubs Per Consumer

    There are cases in which 2 consumers of the same endpoint want to have 2 different responses.

    @@ -4202,9 +4909,9 @@ information about the reasons behind this change.

    -

    2.8. Common

    +

    2.11. Common

    -

    2.8.1. Common properties for JUnit and Spring

    +

    2.11.1. Common properties for JUnit and Spring

    Some of the properties that are repetitive can be set using system properties or configuration properties (for Spring). Here are their names with their default values:

    @@ -4344,7 +5051,7 @@ segments are padded with trailing 0 or "ga" segments, respectively, until the ki
    -

    2.9. Stub Runner for Messaging

    +

    2.12. Stub Runner for Messaging

    Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box

    @@ -4368,7 +5075,7 @@ segments are padded with trailing 0 or "ga" segments, respectively, until the ki

    It also provides points of entry to integrate with any other solution on the market.

    -

    2.9.1. Stub triggering

    +

    2.12.1. Stub triggering

    To trigger a message it’s enough to use the StubTrigger interface:

    @@ -4458,21 +5165,21 @@ public interface StubTrigger {
    -

    2.10. Stub Runner Camel

    +

    2.13. Stub Runner Camel

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Apache Camel. For the provided artifacts it will automatically download the stubs and register the required routes.

    -

    2.10.1. Adding it to the project

    +

    2.13.1. Adding it to the project

    It’s enough to have both Apache Camel and Spring Cloud Contract Stub Runner on classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    -

    2.10.2. Examples

    +

    2.13.2. Examples

    Stubs structure
    @@ -4560,7 +5267,7 @@ Remember to annotate your test class with @AutoConfigureStubRunner.
    -
    Scenario 1 (no input message)
    +
    Scenario 1 (no input message)

    So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

    @@ -4589,7 +5296,7 @@ receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
    -
    Scenario 2 (output triggered by input)
    +
    Scenario 2 (output triggered by input)

    Since the route is set for you it’s enough to just send a message to the jms:output destination.

    @@ -4631,21 +5338,21 @@ receivedMessage.in.headers.get('BOOK-NAME') == 'foo'
    -

    2.11. Stub Runner Integration

    +

    2.14. Stub Runner Integration

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Integration. For the provided artifacts it will automatically download the stubs and register the required routes.

    -

    2.11.1. Adding it to the project

    +

    2.14.1. Adding it to the project

    It’s enough to have both Spring Integration and Spring Cloud Contract Stub Runner on classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    -

    2.11.2. Examples

    +

    2.14.2. Examples

    Stubs structure
    @@ -4759,7 +5466,7 @@ Remember to annotate your test class with @AutoConfigureStubRunner.
    -
    Scenario 1 (no input message)
    +
    Scenario 1 (no input message)

    So as to trigger a message via the return_book_1 label we’ll use the StubTigger interface as follows

    @@ -4788,7 +5495,7 @@ receivedMessage.headers.get('BOOK-NAME') == 'foo'
    -
    Scenario 2 (output triggered by input)
    +
    Scenario 2 (output triggered by input)

    Since the route is set for you it’s enough to just send a message to the output destination.

    @@ -4830,7 +5537,7 @@ receivedMessage.headers.get('BOOK-NAME') == 'foo'
    -

    2.12. Stub Runner Stream

    +

    2.15. Stub Runner Stream

    Spring Cloud Contract Verifier Stub Runner’s messaging module gives you an easy way to integrate with Spring Stream. For the provided artifacts it will automatically download the stubs and register the required @@ -4880,14 +5587,14 @@ If you want to use Spring Cloud Stream remember to add a

    -

    2.12.1. Adding it to the project

    +

    2.15.1. Adding it to the project

    It’s enough to have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on classpath. Remember to annotate your test class with @AutoConfigureStubRunner.

    -

    2.12.2. Examples

    +

    2.15.2. Examples

    Stubs structure
    @@ -4990,7 +5697,7 @@ debug: true
    -
    Scenario 1 (no input message)
    +
    Scenario 1 (no input message)

    So as to trigger a message via the return_book_1 label we’ll use the StubTrigger interface as follows

    @@ -5019,7 +5726,7 @@ receivedMessage.headers.get('BOOK-NAME') == 'foo'
    -
    Scenario 2 (output triggered by input)
    +
    Scenario 2 (output triggered by input)

    Since the route is set for you it’s enough to just send a message to the bookStorage destination.

    @@ -5061,7 +5768,7 @@ receivedMessage.headers.get('BOOK-NAME') == 'foo'
    -

    2.13. Stub Runner Spring AMQP

    +

    2.16. Stub Runner Spring AMQP

    Spring Cloud Contract Verifier Stub Runner’s messaging module provides an easy way to integrate with Spring AMQP’s Rabbit Template. For the provided artifacts it will automatically download the stubs and register the required @@ -5083,14 +5790,14 @@ Then it collects the queues from the Spring exchanges and tries to find messages The message is triggered to all matching message listeners.

    -

    2.13.1. Adding it to the project

    +

    2.16.1. Adding it to the project

    It’s enough to have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and set the property stubrunner.amqp.enabled=true. Remember to annotate your test class with @AutoConfigureStubRunner.

    -

    2.13.2. Examples

    +

    2.16.2. Examples

    Stubs structure
    @@ -5253,7 +5960,7 @@ The message is directly handed over to the onMessage method of the
    -

    2.14. Contract DSL

    +

    2.17. Contract DSL

    @@ -5349,7 +6056,7 @@ Spring Cloud Contract supports defining multiple contracts in a single file!
    @@ -5392,7 +6099,7 @@ Groovy Map notation.
    -

    2.14.2. Common Top-Level elements

    +

    2.17.2. Common Top-Level elements

    Description
    @@ -5520,7 +6227,7 @@ folder in which the contract lays.

    -

    2.14.3. HTTP Top-Level Elements

    +

    2.17.3. HTTP Top-Level Elements

    Following methods can be called in the top-level closure of a contract definition. Request and response are mandatory, priority is optional.

    @@ -5550,7 +6257,7 @@ folder in which the contract lays.

    -

    2.14.4. Request

    +

    2.17.4. Request

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

    @@ -5775,7 +6482,7 @@ where the value can be a dynamic property (e.g. formParameter: $(consumer(
    -

    2.14.5. Response

    +

    2.17.5. Response

    Minimal response must contain HTTP status code.

    @@ -5798,7 +6505,7 @@ where the value can be a dynamic property (e.g. formParameter: $(consumer(
    -

    2.14.6. Dynamic properties

    +

    2.17.6. Dynamic properties

    The contract can contain some dynamic properties - timestamps / ids etc. You don’t want to enforce the consumers to stub their clocks to always return the same value of time so that it gets matched by the stub. That’s why we allow you to provide the dynamic @@ -6876,7 +7583,7 @@ via the byCommand(…​) method.

    -

    2.14.7. JAX-RS support

    +

    2.17.7. JAX-RS support

    We support JAX-RS 2 Client API. Base class needs to define protected WebTarget webTarget and server initialization, right now the only option how to test JAX-RS API is to start a web server.

    @@ -6923,7 +7630,7 @@ via the byCommand(…​) method.

    -

    2.14.8. Async support

    +

    2.17.8. Async support

    If you’re using asynchronous communication on the server side (your controllers are returning Callable, DeferredResult etc. then inside your contract you have to provide in the response @@ -6946,7 +7653,7 @@ section a async() method. Example:

    -

    2.14.9. Working with Context Paths

    +

    2.17.9. Working with Context Paths

    Spring Cloud Contract supports context paths.

    @@ -7047,7 +7754,7 @@ have that information (e.g. in the stubs you’ll see that you have too call
    -

    2.14.10. Messaging Top-Level Elements

    +

    2.17.10. Messaging Top-Level Elements

    The DSL for messaging looks a little bit different than the one that focuses on HTTP.

    @@ -7159,7 +7866,7 @@ as presented below (note you can use either $ or value
    -

    2.14.11. Multiple contracts in one file

    +

    2.17.11. Multiple contracts in one file

    It’s possible to define multiple contracts in one file. An example of such a contract can look like this

    @@ -7276,9 +7983,9 @@ As you can see it’s much better if you name your contracts since then your
    -

    2.15. Customization

    +

    2.18. Customization

    -

    2.15.1. Extending the DSL

    +

    2.18.1. Extending the DSL

    It is possible to provide your own functions to the DSL. The key requirement for this feature was to maintain the static compatibility. Below you will be able to see an example @@ -7307,89 +8014,285 @@ of:

    -
    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/common/src/main/java/com/example/PatternUtils.java[]
    +
    package com.example;
     
    -*ConsumerUtils* contains functions used by the **consumer**.
    +import java.util.regex.Pattern;
     
    -[source,java]
    +/** + * If you want to use {@link Pattern} directly in your tests + * then you can create a class resembling this one. It can + * contain all the {@link Pattern} you want to use in the DSL. + * + * <pre> + * {@code + * request { + * body( + * [ age: $(c(PatternUtils.oldEnough()))] + * ) + * } + * </pre> + * + * Notice that we're using both {@code $()} for dynamic values + * and {@code c()} for the consumer side. + * + * @author Marcin Grzejszczak + */ +//tag::impl[] +public class PatternUtils { + + public static String tooYoung() { + //remove::start[] + return "[0-1][0-9]"; + //remove::end[return] + } + + public static Pattern oldEnough() { + //remove::start[] + return Pattern.compile("[2-9][0-9]"); + //remove::end[return] + } + + /** + * Makes little sense but it's just an example ;) + */ + public static Pattern ok() { + //remove::start[] + return Pattern.compile("OK"); + //remove::end[return] + } +} +//end::impl[]
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/common/src/main/java/com/example/ConsumerUtils.java[]

    +

    ConsumerUtils contains functions used by the consumer.

    +
    +
    +
    +
    package com.example;
    +
    +import org.springframework.cloud.contract.spec.internal.ClientDslProperty;
    +
    +/**
    + * DSL Properties passed to the DSL from the consumer's perspective.
    + * That means that on the input side {@code Request} for HTTP
    + * or {@code Input} for messaging you can have a regular expression.
    + * On the {@code Response} for HTTP or {@code Output} for messaging
    + * you have to have a concrete value.
    + *
    + * @author Marcin Grzejszczak
    + */
    +//tag::impl[]
    +public class ConsumerUtils {
    +	/**
    +	 * Consumer side property. By using the {@link ClientDslProperty}
    +	 * you can omit most of boilerplate code from the perspective
    +	 * of dynamic values. Example
    +	 *
    +	 * <pre>
    +	 * {@code
    +	 * request {
    +	 *     body(
    +	 *         [ age: $(ConsumerUtils.oldEnough())]
    +	 *     )
    +	 * }
    +	 * </pre>
    +	 *
    +	 * That way it's in the implementation that we decide what value we will pass to the consumer
    +	 * and which one to the producer.
    +	 *
    +	 * @author Marcin Grzejszczak
    +	 */
    +	public static ClientDslProperty oldEnough() {
    +		//remove::start[]
    +		// this example is not the best one and
    +		// theoretically you could just pass the regex instead of `ServerDslProperty` but
    +		// it's just to show some new tricks :)
    +		return new ClientDslProperty(PatternUtils.oldEnough(), 40);
    +		//remove::end[return]
    +	}
    +
    +}
    +//end::impl[]
    +

    ProducerUtils contains functions used by the producer.

    -
    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/common/src/main/java/com/example/ProducerUtils.java[]
    +
    package com.example;
     
    -===== Adding the dependency to project
    +import org.springframework.cloud.contract.spec.internal.ServerDslProperty;
     
    -In order for the plugins and IDE to be able to reference the common JAR classes you need
    -to pass the dependency to your project.
    +/**
    + * DSL Properties passed to the DSL from the producer's perspective.
    + * That means that on the input side {@code Request} for HTTP
    + * or {@code Input} for messaging you have to have a concrete value.
    + * On the {@code Response} for HTTP or {@code Output} for messaging
    + * you can have a regular expression.
    + *
    + * @author Marcin Grzejszczak
    + */
    +//tag::impl[]
    +public class ProducerUtils {
     
    -====== Test dependency in project's dependencies
    -
    -First add the common jar dependency as a test dependency. That way since your
    +	/**
    +	 * Producer side property. By using the {@link ProducerUtils}
    +	 * you can omit most of boilerplate code from the perspective
    +	 * of dynamic values. Example
    +	 *
    +	 * <pre>
    +	 * {@code
    +	 * response {
    +	 *     body(
    +	 *         [ status: $(ProducerUtils.ok())]
    +	 *     )
    +	 * }
    +	 * </pre>
    +	 *
    +	 * That way it's in the implementation that we decide what value we will pass to the consumer
    +	 * and which one to the producer.
    +	 */
    +	public static ServerDslProperty ok() {
    +		// this example is not the best one and
    +		// theoretically you could just pass the regex instead of `ServerDslProperty` but
    +		// it's just to show some new tricks :)
    +		return new ServerDslProperty( PatternUtils.ok(), "OK");
    +	}
    +}
    +//end::impl[]
    +
    +
    +
    +
    +
    Adding the dependency to project
    +
    +

    In order for the plugins and IDE to be able to reference the common JAR classes you need +to pass the dependency to your project.

    +
    +
    +
    Test dependency in project’s dependencies
    +
    +

    First add the common jar dependency as a test dependency. That way since your contracts files are available at test resources path, automatically the -common jar classes will be visible in your Groovy files. - -[source,xml,indent=0,subs="verbatim,attributes",role="primary"] -.Maven +common jar classes will be visible in your Groovy files.

    +
    +
    +
    Maven
    +
    +
    <dependency>
    +	<groupId>com.example</groupId>
    +	<artifactId>beer-common</artifactId>
    +	<version>${project.version}</version>
    +	<scope>test</scope>
    +</dependency>
    +
    +
    Gradle
    +
    +
    testCompile("com.example:beer-common:0.0.1-SNAPSHOT")
    +
    +
    +
    +
    +
    Test dependency in plugin’s dependencies
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/pom.xml[tags=test_dep,indent=0]

    +

    Now you have to add the dependency for the plugin to reuse at runtime.

    +
    +
    +
    Maven
    +
    +
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +	<configuration>
    +		<packageWithBaseClasses>com.example</packageWithBaseClasses>
    +		<baseClassMappings>
    +			<baseClassMapping>
    +				<contractPackageRegex>.*intoxication.*</contractPackageRegex>
    +				<baseClassFQN>com.example.intoxication.BeerIntoxicationBase</baseClassFQN>
    +			</baseClassMapping>
    +		</baseClassMappings>
    +	</configuration>
    +	<dependencies>
    +		<dependency>
    +			<groupId>com.example</groupId>
    +			<artifactId>beer-common</artifactId>
    +			<version>${project.version}</version>
    +			<scope>compile</scope>
    +		</dependency>
    +	</dependencies>
    +</plugin>
    +
    +
    +
    +
    Gradle
    +
    +
    classpath "com.example:beer-common:0.0.1-SNAPSHOT"
    +
    +
    +
    +
    +
    Referencing classes in DSLs
    +
    +

    Now you can reference your classes in your DSL. Example:

    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    -
    -
    -
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/build.gradle[tags=test_dep,indent=0]

    -
    -
    -
    -
    ====== Test dependency in plugin's dependencies
    +
    package contracts.beer.rest
     
    -Now you have to add the dependency for the plugin to reuse at runtime.
    +import com.example.ConsumerUtils
    +import com.example.ProducerUtils
    +import org.springframework.cloud.contract.spec.Contract
     
    -[source,xml,indent=0,subs="verbatim,attributes",role="primary"]
    -.Maven
    -
    -
    -
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/pom.xml[tags=test_dep_in_plugin,indent=0]

    -
    -
    -
    -
    [source,groovy,indent=0,subs="verbatim,attributes",role="secondary"]
    -.Gradle
    -
    -
    -
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/build.gradle[tags=test_dep_in_plugin,indent=0]

    -
    -
    -
    -
    ====== Referencing classes in DSLs
    +Contract.make {
    +	description("""
    +Represents a successful scenario of getting a beer
     
    -Now you can reference your classes in your DSL. Example:
    +```
    +given:
    +	client is old enough
    +when:
    +	he applies for a beer
    +then:
    +	we'll grant him the beer
    +```
     
    -[source,groovy]
    +""") + request { + method 'POST' + url '/check' + body( + age: $(ConsumerUtils.oldEnough()) + ) + headers { + contentType(applicationJson()) + } + } + response { + status 200 + body(""" + { + "status": "${value(ProducerUtils.ok())}" + } + """) + headers { + contentType(applicationJson()) + } + } +}
    -
    -

    Unresolved directive in verifier/contract.adoc - include::https://raw.githubusercontent.com/spring-cloud-samples/spring-cloud-contract-samples/master/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0]

    -

    2.16. Pluggable architecture

    +

    2.19. Pluggable architecture

    There are cases where you have your contracts defined in other formats like YAML, RAML or PACT. On the other hand you’d like to profit from @@ -7399,7 +8302,7 @@ tests for other languages) and you can do the same for stubs generation (you can stubs for other stub http server implementations).

    -

    2.16.1. Custom contract converter

    +

    2.19.1. Custom contract converter

    Let’s assume that your contract is written in a YAML file like this:

    @@ -7778,7 +8681,7 @@ testCompile 'au.com.dius:pact-jvm-model:2.4.18'
    -

    2.16.2. Custom test generator

    +

    2.19.2. Custom test generator

    If you want to generate tests for different languages than Java or you’re not happy with the way we’re building Java tests for you then you can register @@ -7835,7 +8738,7 @@ com.example.MyGenerator

    -

    2.16.3. Custom stub generator

    +

    2.19.3. Custom stub generator

    If you want to generate stubs for other stub server than WireMock it’s enough to plug in your own implementation of this interface:

    @@ -7910,7 +8813,7 @@ DSL as input you can e.g. produce WireMock stubs and Pact files too!
    -

    2.16.4. Custom Stub Runner

    +

    2.19.4. Custom Stub Runner

    If you decide to have a custom stub generation you also need a custom way of running stubs with your different stub provider.

    @@ -8032,7 +8935,7 @@ will be picked. If you provide more than one then the first one on the list will
    -

    2.16.5. Custom Stub Downloader

    +

    2.19.5. Custom Stub Downloader

    You can customize the way your stubs are downloaded. It’s enough to create an implementation of the StubDownloaderBuilder

    @@ -8093,7 +8996,7 @@ If you don’t provide any implementation then the default one will be picke
    - +

    Here you can find interesting links related to Spring Cloud Contract Verifier: