From 8dfcde2af0a690594e10a6743f69d18d5d98c3c8 Mon Sep 17 00:00:00 2001 From: buildmaster Date: Wed, 7 Mar 2018 20:23:06 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- multi/multi__spring_cloud_contract_faq.html | 2 +- ..._cloud_contract_verifier_introduction.html | 200 +++++++++++- ...ing_cloud_contract_verifier_messaging.html | 2 +- multi/multi_spring-cloud-contract.html | 2 +- single/spring-cloud-contract.html | 206 +++++++++++- spring-cloud-contract.xml | 307 +++++++++++++++++- 6 files changed, 699 insertions(+), 20 deletions(-) diff --git a/multi/multi__spring_cloud_contract_faq.html b/multi/multi__spring_cloud_contract_faq.html index 8f4463c629..b4c4b40ba1 100644 --- a/multi/multi__spring_cloud_contract_faq.html +++ b/multi/multi__spring_cloud_contract_faq.html @@ -45,7 +45,7 @@ sides of the communication. You can pass the values:

Either via the

or using the $() method

$(consumer(...), producer(...))
 $(stub(...), test(...))
-$(client(...), server(...))

You can read more about this in the Contract DSL section.

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +$(client(...), server(...))

You can read more about this in the Contract DSL section.

Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

[Tip]Tip

If on one side you have passed the regular expression and you haven’t passed the other, then the other side will get auto-generated.

Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression diff --git a/multi/multi__spring_cloud_contract_verifier_introduction.html b/multi/multi__spring_cloud_contract_verifier_introduction.html index e3195e63b0..bb075c6f55 100644 --- a/multi/multi__spring_cloud_contract_verifier_introduction.html +++ b/multi/multi__spring_cloud_contract_verifier_introduction.html @@ -24,7 +24,197 @@ sides.

  • To generate boilerplate test code to be used on features in the contracts. Assume that we have a business use case of fraud check. If a user can be a fraud for 100 different reasons, we would assume that you would create 2 contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior.

    2.3 How It Works

    This section explores how Spring Cloud Contract Verifier with Stub Runner works.

    2.3.1 Defining the contract

    As consumers of services, we need to define what exactly we want to achieve. We need to +used to test contracts between applications and not to simulate full behavior.

    2.3 How It Works

    This section explores how Spring Cloud Contract Verifier with Stub Runner works.

    2.3.1 A three second tour

    On the Producer Side

    In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts.

    Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
    +	<scope>test</scope>
    +</dependency>
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +</plugin>

    Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests..

    As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail.

    To make them pass, the correct implementation of either handling HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup).

    Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. The changes can now be merged + and both the application and the stub artifacts may be published in an online repository.

    On the Consumer Side

    Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service.

    Add the dependency to Spring Cloud Contract Stub Runner:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>

    Get the Producer-side stubs installed in your Maven repository by either:

    • checking out the Producer side repository, adding contracts and generating the stubs by running:
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail;

    or:

    • getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties:
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: http://repo.spring.io/libs-snapshot

    Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you.

    [Tip]Tip

    Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
    +		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {

    Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service.

    2.3.2 A three minute tour

    On the Producer Side

    In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts.

    For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP +methods, urls, headers, status codes, etc.). A sample HTTP stub contract in Groovy DSL would look like this:

    package contracts
    +
    +org.springframework.cloud.contract.spec.Contract.make {
    +	request {
    +		method 'PUT'
    +		url '/fraudcheck'
    +		body([
    +			   "client.id": $(regex('[0-9]{10}')),
    +			   loanAmount: 99999
    +		])
    +		headers {
    +			contentType('application/json')
    +		}
    +	}
    +	response {
    +		status 200
    +		body([
    +			   fraudCheckStatus: "FRAUD",
    +			   "rejection.reason": "Amount too high"
    +		])
    +		headers {
    +			contentType('application/json')
    +		}
    +	}
    +}

    While the same contract expressed in YAML would look the following way:

    request:
    +  method: PUT
    +  url: /fraudcheck
    +  body:
    +    "client.id": 1234567890
    +    loanAmount: 99999
    +  headers:
    +    Content-Type: application/json
    +  matchers:
    +    body:
    +      - path: $.['client.id']
    +        type: by_regex
    +        value: "[0-9]{10}"
    +response:
    +  status: 200
    +  body:
    +    fraudCheckStatus: "FRAUD"
    +    "rejection.reason": "Amount too high"
    +  headers:
    +    Content-Type: application/json;charset=UTF-8

    In the case of messaging, the input and the output messages can be defined (taking into account from and +where to it was sent, the message body and header), as well as the methods that should be called after the message + is received or the methods that, when called, should trigger a message. +An example of a Camel messaging contract expressed in Groovy DSL whould look like this:

    def contractDsl = Contract.make {
    +	label 'some_label'
    +	input {
    +		messageFrom('jms:delete')
    +		messageBody([
    +				bookName: 'foo'
    +		])
    +		messageHeaders {
    +			header('sample', 'header')
    +		}
    +		assertThat('bookWasDeleted()')
    +	}
    +}

    While, the same contract expressed in YAML would look as in the code below:

    label: some_label
    +input:
    +  messageFrom: jms:delete
    +  messageBody:
    +    bookName: 'foo'
    +  messageHeaders:
    +    sample: header
    +  assertThat: bookWasDeleted()

    Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
    +	<scope>test</scope>
    +</dependency>
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +</plugin>

    Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests..

    A sample auto-generated test for an HTTP contract would look the following way:

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

    The sample above uses Spring’s MockMvc to run the tests. This is the default test mode for HTTP +contracts, however also JAX-RX client and explicit HTTP invocations can be used as well (just change +the testMode property of the plugin to JAX-RS or EXPLICIT.

    Apart from the default JUnit, you can also use Spock tests, instead, by setting the plugin testFramework +property to Spock.

    [Tip]Tip

    You can now also generate WireMock scenarios based on the contracts, by including an order number followed by + an underscore at the beginning of the contract file names.

    A sample auto-generated test in Spock for a messaging stub contract would look similar to this:

    [source,groovy,indent=0]
    given:
    +	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +		\'\'\'{"bookName":"foo"}\'\'\',
    +		['sample': 'header']
    +	)
    +
    +when:
    +	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
    +
    +then:
    +	 noExceptionThrown()
    +	 bookWasDeleted()

    As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail.

    To make them pass, the correct implementation of handling either HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup).

    Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. Information about + installing the stubs jar to the local repository will appear in the logs:

    [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
    +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
    +[INFO]
    +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
    +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
    +[INFO]
    +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
    +[INFO]
    +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
    +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
    +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
    +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

    The changes can now be merged and both the application and the stub artifacts may be published in an online repository.

    Docker Project

    In order to enable working with contracts while creating applications in non-JVM technologies, +the springcloud/spring-cloud-contract Docker image has been created. It contains a project that will +automatically generate tests for HTTP contracts and execute them in EXPLICIT test mode, then, if +the tests pass, generate Wiremock stubs and -optionally- publish them to an artifact manager. In order to use the +image, it’s sufficient to mount the contracts into the /contracts directory and set a few environment variables.

    On the Consumer Side

    Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service.

    Add the dependency to Spring Cloud Contract Stub Runner:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>

    Get the Producer-side stubs installed in your Maven repository by either:

    • checking out the Producer side repository, adding contracts and generating the stubs by running:
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail;

    or:

    • getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties:
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: http://repo.spring.io/libs-snapshot

    Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you.

    [Tip]Tip

    Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
    +		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {

    Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service. You will see entries similar to theses in the build logs:

    2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
    +2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
    +2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
    +2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
    +2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
    +2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
    +2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

    2.3.3 Defining the contract

    As consumers of services, we need to define what exactly we want to achieve. We need to formulate our expectations. That is why we write contracts.

    Assume that you want to send a request containing the ID of a client company and the amount it wants to borrow from us. You also want to send it to the /fraudcheck url via the PUT method.

    Groovy DSL.  @@ -138,7 +328,7 @@ response: # (7) #(9) - and JSON body equal to # { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } #(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

    -

    2.3.2 Client Side

    Spring Cloud Contract generates stubs, which you can use during client-side testing. +

    2.3.4 Client Side

    Spring Cloud Contract generates stubs, which you can use during client-side testing. You get a running WireMock instance/Messaging route that simulates the service. You would like to feed that instance with a proper stub definition.

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

    ResponseEntity<FraudServiceResponse> response =
     		restTemplate.exchange("http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
    @@ -150,7 +340,7 @@ You would like to feed that instance with a proper stub definition.

    At som @DirtiesContext public class LoanApplicationServiceTests {

    After that, during the tests, Spring Cloud Contract automatically finds the stubs (simulating the real service) in the Maven repository and exposes them on a configured -(or random) port.

    2.3.3 Server Side

    Since you are developing your stub, you need to be sure that it actually resembles your +(or random) port.

    2.3.5 Server Side

    Since you are developing your stub, you need to be sure that it actually resembles your concrete implementation. You cannot have a situation where your stub acts in one way and your application behaves in a different way, especially in production.

    To ensure that your application behaves the way you define in your stub, tests are generated from the stub you provide.

    The autogenerated test looks, more or less, like this:

    @Test
    @@ -383,7 +573,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo
     different ranges of values. To enable ranges of values, you can set regular expressions
     matching those values for the consumer side. You can provide the body by means of either
     a map notation or String with interpolations.
    -Consult the docs
    +Consult the docs
     for more information. We highly recommend using the map notation!

    [Tip]Tip

    You must understand the map notation in order to set up contracts. Please read the Groovy docs regarding JSON.

    The previously shown contract is an agreement between two sides that:

    • if an HTTP request is sent with all of

      • a PUT method on the /fraudcheck endpoint,
      • a JSON body with a client.id that matches the regular expression [0-9]{10} and loanAmount equal to 99999,
      • and a Content-Type header with a value of application/vnd.fraud.v1+json,
    • then an HTTP response is sent to the consumer that

      • has status 200,
      • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and @@ -441,7 +631,7 @@ Application service):

        Add the Spring Cloud Co </dependency>

    Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the group-id and artifact-id for the Stub Runner to download the stubs of your collaborators. (Optional step) Because you’re playing with the collaborators offline, you -can also provide the offline work switch.

    @RunWith(SpringRunner.class)
    +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

    @RunWith(SpringRunner.class)
     @SpringBootTest(webEnvironment=WebEnvironment.NONE)
     @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
     		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    diff --git a/multi/multi__spring_cloud_contract_verifier_messaging.html b/multi/multi__spring_cloud_contract_verifier_messaging.html
    index b2899fe179..4cdad5f35d 100644
    --- a/multi/multi__spring_cloud_contract_verifier_messaging.html
    +++ b/multi/multi__spring_cloud_contract_verifier_messaging.html
    @@ -1,6 +1,6 @@
     
           
    -   5. Spring Cloud Contract Verifier Messaging

    5. Spring Cloud Contract Verifier Messaging

    Spring Cloud Contract Verifier lets you verify applications that uses messaging as a + 5. Spring Cloud Contract Verifier Messaging

    5. Spring Cloud Contract Verifier Messaging

    Spring Cloud Contract Verifier lets you verify applications that use messaging as a means of communication. All of the integrations shown in this document work with Spring, but you can also create one of your own and use that.

    5.1 Integrations

    You can use one of the following four integration configurations:

    • Apache Camel
    • Spring Integration
    • Spring Cloud Stream
    • Spring AMQP

    Since we use Spring Boot, if you have added one of these libraries to the classpath, all the messaging configuration is automatically set up.

    [Important]Important

    Remember to put @AutoConfigureMessageVerifier on the base class of your diff --git a/multi/multi_spring-cloud-contract.html b/multi/multi_spring-cloud-contract.html index c904c7106c..28a202e34a 100644 --- a/multi/multi_spring-cloud-contract.html +++ b/multi/multi_spring-cloud-contract.html @@ -1,3 +1,3 @@ - Spring Cloud Contract

    Spring Cloud Contract


    Table of Contents

    1. Spring Cloud Contract
    2. Spring Cloud Contract Verifier Introduction
    2.1. Why a Contract Verifier?
    2.1.1. Testing issues
    2.2. Purposes
    2.3. How It Works
    2.3.1. Defining the contract
    2.3.2. Client Side
    2.3.3. Server Side
    2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
    2.4.1. Technical note
    2.4.2. Consumer side (Loan Issuance)
    2.4.3. Producer side (Fraud Detection server)
    2.4.4. Consumer Side (Loan Issuance) Final Step
    2.5. Dependencies
    2.6. Additional Links
    2.6.1. Spring Cloud Contract video
    2.6.2. Readings
    2.7. Samples
    3. Spring Cloud Contract FAQ
    3.1. Why use Spring Cloud Contract Verifier and not X ?
    3.2. I don’t want to write a contract in Groovy!
    3.3. What is this value(consumer(), producer()) ?
    3.4. How to do Stubs versioning?
    3.4.1. API Versioning
    3.4.2. JAR versioning
    3.4.3. Dev or prod stubs
    3.5. Common repo with contracts
    3.5.1. Repo structure
    3.5.2. Workflow
    3.5.3. Consumer
    3.5.4. Producer
    3.5.5. How can I define messaging contracts per topic not per producer?
    For Maven Project
    For Gradle Project
    3.6. Can I have multiple base classes for tests?
    3.7. How can I debug the request/response being sent by the generated tests client?
    3.7.1. How can I debug the mapping/request/response being sent by WireMock?
    3.7.2. How can I see what got registered in the HTTP server stub?
    3.7.3. Can I reference the request from the response?
    3.7.4. Can I reference text from file?
    4. Spring Cloud Contract Verifier Setup
    4.1. Gradle Project
    4.1.1. Prerequisites
    4.1.2. Add Gradle Plugin with Dependencies
    4.1.3. Gradle and Rest Assured 2.0
    4.1.4. Snapshot Versions for Gradle
    4.1.5. Add stubs
    4.1.6. Run the Plugin
    4.1.7. Default Setup
    4.1.8. Configure Plugin
    4.1.9. Configuration Options
    4.1.10. Single Base Class for All Tests
    4.1.11. Different Base Classes for Contracts
    4.1.12. Invoking Generated Tests
    4.1.13. Spring Cloud Contract Verifier on the Consumer Side
    4.2. Maven Project
    4.2.1. Add maven plugin
    4.2.2. Maven and Rest Assured 2.0
    4.2.3. Snapshot versions for Maven
    4.2.4. Add stubs
    4.2.5. Run plugin
    4.2.6. Configure plugin
    4.2.7. Configuration Options
    4.2.8. Single Base Class for All Tests
    4.2.9. Different base classes for contracts
    4.2.10. Invoking generated tests
    4.2.11. Maven Plugin and STS
    4.3. Stubs and Transitive Dependencies
    4.4. CI Server setup
    4.5. Scenarios
    4.6. Docker Project
    4.6.1. Short intro to Maven, JARs and Binary storage
    4.6.2. How it works
    Environment Variables
    4.6.3. Example of usage
    4.6.4. Server side (nodejs)
    5. Spring Cloud Contract Verifier Messaging
    5.1. Integrations
    5.2. Manual Integration Testing
    5.3. Publisher-Side Test Generation
    5.3.1. Scenario 1: No Input Message
    5.3.2. Scenario 2: Output Triggered by Input
    5.3.3. Scenario 3: No Output Message
    5.4. Consumer Stub Generation
    6. Spring Cloud Contract Stub Runner
    6.1. Snapshot versions
    6.2. Publishing Stubs as JARs
    6.3. Stub Runner Core
    6.3.1. Retrieving stubs
    Stub downloading
    Classpath scanning
    6.3.2. Running stubs
    Limitations
    Running using main app
    HTTP Stubs
    Viewing registered mappings
    Messaging Stubs
    6.4. Stub Runner JUnit Rule
    6.4.1. Maven settings
    6.4.2. Providing fixed ports
    6.4.3. Fluent API
    6.4.4. Stub Runner with Spring
    6.5. Stub Runner Spring Cloud
    6.5.1. Stubbing Service Discovery
    Test profiles and service discovery
    6.5.2. Additional Configuration
    6.6. Stub Runner Boot Application
    6.6.1. How to use it?
    Stub Runner Server
    Stub Runner Server Fat Jar
    Spring Cloud CLI
    6.6.2. Endpoints
    HTTP
    Messaging
    6.6.3. Example
    6.6.4. Stub Runner Boot with Service Discovery
    6.7. Stubs Per Consumer
    6.8. Common
    6.8.1. Common Properties for JUnit and Spring
    6.8.2. Stub Runner Stubs IDs
    6.9. Stub Runner Docker
    6.9.1. How to use it
    6.9.2. Example of client side usage in a non JVM project
    7. Stub Runner for Messaging
    7.1. Stub triggering
    7.1.1. Trigger by Label
    7.1.2. Trigger by Group and Artifact Ids
    7.1.3. Trigger by Artifact Ids
    7.1.4. Trigger All Messages
    7.2. Stub Runner Integration
    7.2.1. Adding the Runner to the Project
    7.2.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.3. Stub Runner Stream
    7.3.1. Adding the Runner to the Project
    7.3.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.4. Stub Runner Spring AMQP
    7.4.1. Adding the Runner to the Project
    Triggering the message
    Spring AMQP Test Configuration
    8. Contract DSL
    8.1. Limitations
    8.2. Common Top-Level elements
    8.2.1. Description
    8.2.2. Name
    8.2.3. Ignoring Contracts
    8.2.4. Passing Values from Files
    8.2.5. HTTP Top-Level Elements
    8.3. Request
    8.4. Response
    8.5. Dynamic properties
    8.5.1. Dynamic properties inside the body
    8.5.2. Regular expressions
    8.5.3. Passing Optional Parameters
    8.5.4. Executing Custom Methods on the Server Side
    8.5.5. Referencing the Request from the Response
    8.5.6. Registering Your Own WireMock Extension
    8.5.7. Dynamic Properties in the Matchers Sections
    8.6. JAX-RS Support
    8.7. Async Support
    8.8. Working with Context Paths
    8.9. Messaging Top-Level Elements
    8.9.1. Output Triggered by a Method
    8.9.2. Output Triggered by a Message
    8.9.3. Consumer/Producer
    8.9.4. Common
    8.10. Multiple Contracts in One File
    9. Customization
    9.1. Extending the DSL
    9.1.1. Common JAR
    9.1.2. Adding the Dependency to the Project
    9.1.3. Test the Dependency in the Project’s Dependencies
    9.1.4. Test a Dependency in the Plugin’s Dependencies
    9.1.5. Referencing classes in DSLs
    10. Using the Pluggable Architecture
    10.1. Custom Contract Converter
    10.1.1. Pact Converter
    10.1.2. Pact Contract
    10.1.3. Pact for Producers
    10.1.4. Pact for Consumers
    10.2. Using the Custom Test Generator
    10.3. Using the Custom Stub Generator
    10.4. Using the Custom Stub Runner
    10.5. Using the Custom Stub Downloader
    11. Spring Cloud Contract WireMock
    11.1. Registering Stubs Automatically
    11.2. Using Files to Specify the Stub Bodies
    11.3. Alternative: Using JUnit Rules
    11.4. Relaxed SSL Validation for Rest Template
    11.5. WireMock and Spring MVC Mocks
    11.6. Customization of WireMock configuration
    11.7. Generating Stubs using REST Docs
    11.8. Generating Contracts by Using REST Docs
    12. Migrations
    12.1. 1.0.x → 1.1.x
    12.1.1. New structure of generated stubs
    12.2. 1.1.x → 1.2.x
    12.2.1. Custom HttpServerStub
    12.2.2. New packages for generated tests
    12.2.3. New Methods in TemplateProcessor
    12.2.4. RestAssured 3.0
    12.3. 1.2.x → 2.0.x
    12.3.1. No Camel support
    13. Links
    \ No newline at end of file + Spring Cloud Contract

    Spring Cloud Contract


    Table of Contents

    1. Spring Cloud Contract
    2. Spring Cloud Contract Verifier Introduction
    2.1. Why a Contract Verifier?
    2.1.1. Testing issues
    2.2. Purposes
    2.3. How It Works
    2.3.1. A three second tour
    On the Producer Side
    On the Consumer Side
    2.3.2. A three minute tour
    On the Producer Side
    On the Consumer Side
    2.3.3. Defining the contract
    2.3.4. Client Side
    2.3.5. Server Side
    2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
    2.4.1. Technical note
    2.4.2. Consumer side (Loan Issuance)
    2.4.3. Producer side (Fraud Detection server)
    2.4.4. Consumer Side (Loan Issuance) Final Step
    2.5. Dependencies
    2.6. Additional Links
    2.6.1. Spring Cloud Contract video
    2.6.2. Readings
    2.7. Samples
    3. Spring Cloud Contract FAQ
    3.1. Why use Spring Cloud Contract Verifier and not X ?
    3.2. I don’t want to write a contract in Groovy!
    3.3. What is this value(consumer(), producer()) ?
    3.4. How to do Stubs versioning?
    3.4.1. API Versioning
    3.4.2. JAR versioning
    3.4.3. Dev or prod stubs
    3.5. Common repo with contracts
    3.5.1. Repo structure
    3.5.2. Workflow
    3.5.3. Consumer
    3.5.4. Producer
    3.5.5. How can I define messaging contracts per topic not per producer?
    For Maven Project
    For Gradle Project
    3.6. Can I have multiple base classes for tests?
    3.7. How can I debug the request/response being sent by the generated tests client?
    3.7.1. How can I debug the mapping/request/response being sent by WireMock?
    3.7.2. How can I see what got registered in the HTTP server stub?
    3.7.3. Can I reference the request from the response?
    3.7.4. Can I reference text from file?
    4. Spring Cloud Contract Verifier Setup
    4.1. Gradle Project
    4.1.1. Prerequisites
    4.1.2. Add Gradle Plugin with Dependencies
    4.1.3. Gradle and Rest Assured 2.0
    4.1.4. Snapshot Versions for Gradle
    4.1.5. Add stubs
    4.1.6. Run the Plugin
    4.1.7. Default Setup
    4.1.8. Configure Plugin
    4.1.9. Configuration Options
    4.1.10. Single Base Class for All Tests
    4.1.11. Different Base Classes for Contracts
    4.1.12. Invoking Generated Tests
    4.1.13. Spring Cloud Contract Verifier on the Consumer Side
    4.2. Maven Project
    4.2.1. Add maven plugin
    4.2.2. Maven and Rest Assured 2.0
    4.2.3. Snapshot versions for Maven
    4.2.4. Add stubs
    4.2.5. Run plugin
    4.2.6. Configure plugin
    4.2.7. Configuration Options
    4.2.8. Single Base Class for All Tests
    4.2.9. Different base classes for contracts
    4.2.10. Invoking generated tests
    4.2.11. Maven Plugin and STS
    4.3. Stubs and Transitive Dependencies
    4.4. CI Server setup
    4.5. Scenarios
    4.6. Docker Project
    4.6.1. Short intro to Maven, JARs and Binary storage
    4.6.2. How it works
    Environment Variables
    4.6.3. Example of usage
    4.6.4. Server side (nodejs)
    5. Spring Cloud Contract Verifier Messaging
    5.1. Integrations
    5.2. Manual Integration Testing
    5.3. Publisher-Side Test Generation
    5.3.1. Scenario 1: No Input Message
    5.3.2. Scenario 2: Output Triggered by Input
    5.3.3. Scenario 3: No Output Message
    5.4. Consumer Stub Generation
    6. Spring Cloud Contract Stub Runner
    6.1. Snapshot versions
    6.2. Publishing Stubs as JARs
    6.3. Stub Runner Core
    6.3.1. Retrieving stubs
    Stub downloading
    Classpath scanning
    6.3.2. Running stubs
    Limitations
    Running using main app
    HTTP Stubs
    Viewing registered mappings
    Messaging Stubs
    6.4. Stub Runner JUnit Rule
    6.4.1. Maven settings
    6.4.2. Providing fixed ports
    6.4.3. Fluent API
    6.4.4. Stub Runner with Spring
    6.5. Stub Runner Spring Cloud
    6.5.1. Stubbing Service Discovery
    Test profiles and service discovery
    6.5.2. Additional Configuration
    6.6. Stub Runner Boot Application
    6.6.1. How to use it?
    Stub Runner Server
    Stub Runner Server Fat Jar
    Spring Cloud CLI
    6.6.2. Endpoints
    HTTP
    Messaging
    6.6.3. Example
    6.6.4. Stub Runner Boot with Service Discovery
    6.7. Stubs Per Consumer
    6.8. Common
    6.8.1. Common Properties for JUnit and Spring
    6.8.2. Stub Runner Stubs IDs
    6.9. Stub Runner Docker
    6.9.1. How to use it
    6.9.2. Example of client side usage in a non JVM project
    7. Stub Runner for Messaging
    7.1. Stub triggering
    7.1.1. Trigger by Label
    7.1.2. Trigger by Group and Artifact Ids
    7.1.3. Trigger by Artifact Ids
    7.1.4. Trigger All Messages
    7.2. Stub Runner Integration
    7.2.1. Adding the Runner to the Project
    7.2.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.3. Stub Runner Stream
    7.3.1. Adding the Runner to the Project
    7.3.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.4. Stub Runner Spring AMQP
    7.4.1. Adding the Runner to the Project
    Triggering the message
    Spring AMQP Test Configuration
    8. Contract DSL
    8.1. Limitations
    8.2. Common Top-Level elements
    8.2.1. Description
    8.2.2. Name
    8.2.3. Ignoring Contracts
    8.2.4. Passing Values from Files
    8.2.5. HTTP Top-Level Elements
    8.3. Request
    8.4. Response
    8.5. Dynamic properties
    8.5.1. Dynamic properties inside the body
    8.5.2. Regular expressions
    8.5.3. Passing Optional Parameters
    8.5.4. Executing Custom Methods on the Server Side
    8.5.5. Referencing the Request from the Response
    8.5.6. Registering Your Own WireMock Extension
    8.5.7. Dynamic Properties in the Matchers Sections
    8.6. JAX-RS Support
    8.7. Async Support
    8.8. Working with Context Paths
    8.9. Messaging Top-Level Elements
    8.9.1. Output Triggered by a Method
    8.9.2. Output Triggered by a Message
    8.9.3. Consumer/Producer
    8.9.4. Common
    8.10. Multiple Contracts in One File
    9. Customization
    9.1. Extending the DSL
    9.1.1. Common JAR
    9.1.2. Adding the Dependency to the Project
    9.1.3. Test the Dependency in the Project’s Dependencies
    9.1.4. Test a Dependency in the Plugin’s Dependencies
    9.1.5. Referencing classes in DSLs
    10. Using the Pluggable Architecture
    10.1. Custom Contract Converter
    10.1.1. Pact Converter
    10.1.2. Pact Contract
    10.1.3. Pact for Producers
    10.1.4. Pact for Consumers
    10.2. Using the Custom Test Generator
    10.3. Using the Custom Stub Generator
    10.4. Using the Custom Stub Runner
    10.5. Using the Custom Stub Downloader
    11. Spring Cloud Contract WireMock
    11.1. Registering Stubs Automatically
    11.2. Using Files to Specify the Stub Bodies
    11.3. Alternative: Using JUnit Rules
    11.4. Relaxed SSL Validation for Rest Template
    11.5. WireMock and Spring MVC Mocks
    11.6. Customization of WireMock configuration
    11.7. Generating Stubs using REST Docs
    11.8. Generating Contracts by Using REST Docs
    12. Migrations
    12.1. 1.0.x → 1.1.x
    12.1.1. New structure of generated stubs
    12.2. 1.1.x → 1.2.x
    12.2.1. Custom HttpServerStub
    12.2.2. New packages for generated tests
    12.2.3. New Methods in TemplateProcessor
    12.2.4. RestAssured 3.0
    12.3. 1.2.x → 2.0.x
    12.3.1. No Camel support
    13. Links
    \ No newline at end of file diff --git a/single/spring-cloud-contract.html b/single/spring-cloud-contract.html index a96b466b7e..7b131ef596 100644 --- a/single/spring-cloud-contract.html +++ b/single/spring-cloud-contract.html @@ -1,6 +1,6 @@ - Spring Cloud Contract

    Spring Cloud Contract


    Table of Contents

    1. Spring Cloud Contract
    2. Spring Cloud Contract Verifier Introduction
    2.1. Why a Contract Verifier?
    2.1.1. Testing issues
    2.2. Purposes
    2.3. How It Works
    2.3.1. Defining the contract
    2.3.2. Client Side
    2.3.3. Server Side
    2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
    2.4.1. Technical note
    2.4.2. Consumer side (Loan Issuance)
    2.4.3. Producer side (Fraud Detection server)
    2.4.4. Consumer Side (Loan Issuance) Final Step
    2.5. Dependencies
    2.6. Additional Links
    2.6.1. Spring Cloud Contract video
    2.6.2. Readings
    2.7. Samples
    3. Spring Cloud Contract FAQ
    3.1. Why use Spring Cloud Contract Verifier and not X ?
    3.2. I don’t want to write a contract in Groovy!
    3.3. What is this value(consumer(), producer()) ?
    3.4. How to do Stubs versioning?
    3.4.1. API Versioning
    3.4.2. JAR versioning
    3.4.3. Dev or prod stubs
    3.5. Common repo with contracts
    3.5.1. Repo structure
    3.5.2. Workflow
    3.5.3. Consumer
    3.5.4. Producer
    3.5.5. How can I define messaging contracts per topic not per producer?
    For Maven Project
    For Gradle Project
    3.6. Can I have multiple base classes for tests?
    3.7. How can I debug the request/response being sent by the generated tests client?
    3.7.1. How can I debug the mapping/request/response being sent by WireMock?
    3.7.2. How can I see what got registered in the HTTP server stub?
    3.7.3. Can I reference the request from the response?
    3.7.4. Can I reference text from file?
    4. Spring Cloud Contract Verifier Setup
    4.1. Gradle Project
    4.1.1. Prerequisites
    4.1.2. Add Gradle Plugin with Dependencies
    4.1.3. Gradle and Rest Assured 2.0
    4.1.4. Snapshot Versions for Gradle
    4.1.5. Add stubs
    4.1.6. Run the Plugin
    4.1.7. Default Setup
    4.1.8. Configure Plugin
    4.1.9. Configuration Options
    4.1.10. Single Base Class for All Tests
    4.1.11. Different Base Classes for Contracts
    4.1.12. Invoking Generated Tests
    4.1.13. Spring Cloud Contract Verifier on the Consumer Side
    4.2. Maven Project
    4.2.1. Add maven plugin
    4.2.2. Maven and Rest Assured 2.0
    4.2.3. Snapshot versions for Maven
    4.2.4. Add stubs
    4.2.5. Run plugin
    4.2.6. Configure plugin
    4.2.7. Configuration Options
    4.2.8. Single Base Class for All Tests
    4.2.9. Different base classes for contracts
    4.2.10. Invoking generated tests
    4.2.11. Maven Plugin and STS
    4.3. Stubs and Transitive Dependencies
    4.4. CI Server setup
    4.5. Scenarios
    4.6. Docker Project
    4.6.1. Short intro to Maven, JARs and Binary storage
    4.6.2. How it works
    Environment Variables
    4.6.3. Example of usage
    4.6.4. Server side (nodejs)
    5. Spring Cloud Contract Verifier Messaging
    5.1. Integrations
    5.2. Manual Integration Testing
    5.3. Publisher-Side Test Generation
    5.3.1. Scenario 1: No Input Message
    5.3.2. Scenario 2: Output Triggered by Input
    5.3.3. Scenario 3: No Output Message
    5.4. Consumer Stub Generation
    6. Spring Cloud Contract Stub Runner
    6.1. Snapshot versions
    6.2. Publishing Stubs as JARs
    6.3. Stub Runner Core
    6.3.1. Retrieving stubs
    Stub downloading
    Classpath scanning
    6.3.2. Running stubs
    Limitations
    Running using main app
    HTTP Stubs
    Viewing registered mappings
    Messaging Stubs
    6.4. Stub Runner JUnit Rule
    6.4.1. Maven settings
    6.4.2. Providing fixed ports
    6.4.3. Fluent API
    6.4.4. Stub Runner with Spring
    6.5. Stub Runner Spring Cloud
    6.5.1. Stubbing Service Discovery
    Test profiles and service discovery
    6.5.2. Additional Configuration
    6.6. Stub Runner Boot Application
    6.6.1. How to use it?
    Stub Runner Server
    Stub Runner Server Fat Jar
    Spring Cloud CLI
    6.6.2. Endpoints
    HTTP
    Messaging
    6.6.3. Example
    6.6.4. Stub Runner Boot with Service Discovery
    6.7. Stubs Per Consumer
    6.8. Common
    6.8.1. Common Properties for JUnit and Spring
    6.8.2. Stub Runner Stubs IDs
    6.9. Stub Runner Docker
    6.9.1. How to use it
    6.9.2. Example of client side usage in a non JVM project
    7. Stub Runner for Messaging
    7.1. Stub triggering
    7.1.1. Trigger by Label
    7.1.2. Trigger by Group and Artifact Ids
    7.1.3. Trigger by Artifact Ids
    7.1.4. Trigger All Messages
    7.2. Stub Runner Integration
    7.2.1. Adding the Runner to the Project
    7.2.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.3. Stub Runner Stream
    7.3.1. Adding the Runner to the Project
    7.3.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.4. Stub Runner Spring AMQP
    7.4.1. Adding the Runner to the Project
    Triggering the message
    Spring AMQP Test Configuration
    8. Contract DSL
    8.1. Limitations
    8.2. Common Top-Level elements
    8.2.1. Description
    8.2.2. Name
    8.2.3. Ignoring Contracts
    8.2.4. Passing Values from Files
    8.2.5. HTTP Top-Level Elements
    8.3. Request
    8.4. Response
    8.5. Dynamic properties
    8.5.1. Dynamic properties inside the body
    8.5.2. Regular expressions
    8.5.3. Passing Optional Parameters
    8.5.4. Executing Custom Methods on the Server Side
    8.5.5. Referencing the Request from the Response
    8.5.6. Registering Your Own WireMock Extension
    8.5.7. Dynamic Properties in the Matchers Sections
    8.6. JAX-RS Support
    8.7. Async Support
    8.8. Working with Context Paths
    8.9. Messaging Top-Level Elements
    8.9.1. Output Triggered by a Method
    8.9.2. Output Triggered by a Message
    8.9.3. Consumer/Producer
    8.9.4. Common
    8.10. Multiple Contracts in One File
    9. Customization
    9.1. Extending the DSL
    9.1.1. Common JAR
    9.1.2. Adding the Dependency to the Project
    9.1.3. Test the Dependency in the Project’s Dependencies
    9.1.4. Test a Dependency in the Plugin’s Dependencies
    9.1.5. Referencing classes in DSLs
    10. Using the Pluggable Architecture
    10.1. Custom Contract Converter
    10.1.1. Pact Converter
    10.1.2. Pact Contract
    10.1.3. Pact for Producers
    10.1.4. Pact for Consumers
    10.2. Using the Custom Test Generator
    10.3. Using the Custom Stub Generator
    10.4. Using the Custom Stub Runner
    10.5. Using the Custom Stub Downloader
    11. Spring Cloud Contract WireMock
    11.1. Registering Stubs Automatically
    11.2. Using Files to Specify the Stub Bodies
    11.3. Alternative: Using JUnit Rules
    11.4. Relaxed SSL Validation for Rest Template
    11.5. WireMock and Spring MVC Mocks
    11.6. Customization of WireMock configuration
    11.7. Generating Stubs using REST Docs
    11.8. Generating Contracts by Using REST Docs
    12. Migrations
    12.1. 1.0.x → 1.1.x
    12.1.1. New structure of generated stubs
    12.2. 1.1.x → 1.2.x
    12.2.1. Custom HttpServerStub
    12.2.2. New packages for generated tests
    12.2.3. New Methods in TemplateProcessor
    12.2.4. RestAssured 3.0
    12.3. 1.2.x → 2.0.x
    12.3.1. No Camel support
    13. Links

    _Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, + Spring Cloud Contract

    Spring Cloud Contract


    Table of Contents

    1. Spring Cloud Contract
    2. Spring Cloud Contract Verifier Introduction
    2.1. Why a Contract Verifier?
    2.1.1. Testing issues
    2.2. Purposes
    2.3. How It Works
    2.3.1. A three second tour
    On the Producer Side
    On the Consumer Side
    2.3.2. A three minute tour
    On the Producer Side
    On the Consumer Side
    2.3.3. Defining the contract
    2.3.4. Client Side
    2.3.5. Server Side
    2.4. Step-by-step Guide to Consumer Driven Contracts (CDC)
    2.4.1. Technical note
    2.4.2. Consumer side (Loan Issuance)
    2.4.3. Producer side (Fraud Detection server)
    2.4.4. Consumer Side (Loan Issuance) Final Step
    2.5. Dependencies
    2.6. Additional Links
    2.6.1. Spring Cloud Contract video
    2.6.2. Readings
    2.7. Samples
    3. Spring Cloud Contract FAQ
    3.1. Why use Spring Cloud Contract Verifier and not X ?
    3.2. I don’t want to write a contract in Groovy!
    3.3. What is this value(consumer(), producer()) ?
    3.4. How to do Stubs versioning?
    3.4.1. API Versioning
    3.4.2. JAR versioning
    3.4.3. Dev or prod stubs
    3.5. Common repo with contracts
    3.5.1. Repo structure
    3.5.2. Workflow
    3.5.3. Consumer
    3.5.4. Producer
    3.5.5. How can I define messaging contracts per topic not per producer?
    For Maven Project
    For Gradle Project
    3.6. Can I have multiple base classes for tests?
    3.7. How can I debug the request/response being sent by the generated tests client?
    3.7.1. How can I debug the mapping/request/response being sent by WireMock?
    3.7.2. How can I see what got registered in the HTTP server stub?
    3.7.3. Can I reference the request from the response?
    3.7.4. Can I reference text from file?
    4. Spring Cloud Contract Verifier Setup
    4.1. Gradle Project
    4.1.1. Prerequisites
    4.1.2. Add Gradle Plugin with Dependencies
    4.1.3. Gradle and Rest Assured 2.0
    4.1.4. Snapshot Versions for Gradle
    4.1.5. Add stubs
    4.1.6. Run the Plugin
    4.1.7. Default Setup
    4.1.8. Configure Plugin
    4.1.9. Configuration Options
    4.1.10. Single Base Class for All Tests
    4.1.11. Different Base Classes for Contracts
    4.1.12. Invoking Generated Tests
    4.1.13. Spring Cloud Contract Verifier on the Consumer Side
    4.2. Maven Project
    4.2.1. Add maven plugin
    4.2.2. Maven and Rest Assured 2.0
    4.2.3. Snapshot versions for Maven
    4.2.4. Add stubs
    4.2.5. Run plugin
    4.2.6. Configure plugin
    4.2.7. Configuration Options
    4.2.8. Single Base Class for All Tests
    4.2.9. Different base classes for contracts
    4.2.10. Invoking generated tests
    4.2.11. Maven Plugin and STS
    4.3. Stubs and Transitive Dependencies
    4.4. CI Server setup
    4.5. Scenarios
    4.6. Docker Project
    4.6.1. Short intro to Maven, JARs and Binary storage
    4.6.2. How it works
    Environment Variables
    4.6.3. Example of usage
    4.6.4. Server side (nodejs)
    5. Spring Cloud Contract Verifier Messaging
    5.1. Integrations
    5.2. Manual Integration Testing
    5.3. Publisher-Side Test Generation
    5.3.1. Scenario 1: No Input Message
    5.3.2. Scenario 2: Output Triggered by Input
    5.3.3. Scenario 3: No Output Message
    5.4. Consumer Stub Generation
    6. Spring Cloud Contract Stub Runner
    6.1. Snapshot versions
    6.2. Publishing Stubs as JARs
    6.3. Stub Runner Core
    6.3.1. Retrieving stubs
    Stub downloading
    Classpath scanning
    6.3.2. Running stubs
    Limitations
    Running using main app
    HTTP Stubs
    Viewing registered mappings
    Messaging Stubs
    6.4. Stub Runner JUnit Rule
    6.4.1. Maven settings
    6.4.2. Providing fixed ports
    6.4.3. Fluent API
    6.4.4. Stub Runner with Spring
    6.5. Stub Runner Spring Cloud
    6.5.1. Stubbing Service Discovery
    Test profiles and service discovery
    6.5.2. Additional Configuration
    6.6. Stub Runner Boot Application
    6.6.1. How to use it?
    Stub Runner Server
    Stub Runner Server Fat Jar
    Spring Cloud CLI
    6.6.2. Endpoints
    HTTP
    Messaging
    6.6.3. Example
    6.6.4. Stub Runner Boot with Service Discovery
    6.7. Stubs Per Consumer
    6.8. Common
    6.8.1. Common Properties for JUnit and Spring
    6.8.2. Stub Runner Stubs IDs
    6.9. Stub Runner Docker
    6.9.1. How to use it
    6.9.2. Example of client side usage in a non JVM project
    7. Stub Runner for Messaging
    7.1. Stub triggering
    7.1.1. Trigger by Label
    7.1.2. Trigger by Group and Artifact Ids
    7.1.3. Trigger by Artifact Ids
    7.1.4. Trigger All Messages
    7.2. Stub Runner Integration
    7.2.1. Adding the Runner to the Project
    7.2.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.3. Stub Runner Stream
    7.3.1. Adding the Runner to the Project
    7.3.2. Disabling the functionality
    Scenario 1 (no input message)
    Scenario 2 (output triggered by input)
    Scenario 3 (input with no output)
    7.4. Stub Runner Spring AMQP
    7.4.1. Adding the Runner to the Project
    Triggering the message
    Spring AMQP Test Configuration
    8. Contract DSL
    8.1. Limitations
    8.2. Common Top-Level elements
    8.2.1. Description
    8.2.2. Name
    8.2.3. Ignoring Contracts
    8.2.4. Passing Values from Files
    8.2.5. HTTP Top-Level Elements
    8.3. Request
    8.4. Response
    8.5. Dynamic properties
    8.5.1. Dynamic properties inside the body
    8.5.2. Regular expressions
    8.5.3. Passing Optional Parameters
    8.5.4. Executing Custom Methods on the Server Side
    8.5.5. Referencing the Request from the Response
    8.5.6. Registering Your Own WireMock Extension
    8.5.7. Dynamic Properties in the Matchers Sections
    8.6. JAX-RS Support
    8.7. Async Support
    8.8. Working with Context Paths
    8.9. Messaging Top-Level Elements
    8.9.1. Output Triggered by a Method
    8.9.2. Output Triggered by a Message
    8.9.3. Consumer/Producer
    8.9.4. Common
    8.10. Multiple Contracts in One File
    9. Customization
    9.1. Extending the DSL
    9.1.1. Common JAR
    9.1.2. Adding the Dependency to the Project
    9.1.3. Test the Dependency in the Project’s Dependencies
    9.1.4. Test a Dependency in the Plugin’s Dependencies
    9.1.5. Referencing classes in DSLs
    10. Using the Pluggable Architecture
    10.1. Custom Contract Converter
    10.1.1. Pact Converter
    10.1.2. Pact Contract
    10.1.3. Pact for Producers
    10.1.4. Pact for Consumers
    10.2. Using the Custom Test Generator
    10.3. Using the Custom Stub Generator
    10.4. Using the Custom Stub Runner
    10.5. Using the Custom Stub Downloader
    11. Spring Cloud Contract WireMock
    11.1. Registering Stubs Automatically
    11.2. Using Files to Specify the Stub Bodies
    11.3. Alternative: Using JUnit Rules
    11.4. Relaxed SSL Validation for Rest Template
    11.5. WireMock and Spring MVC Mocks
    11.6. Customization of WireMock configuration
    11.7. Generating Stubs using REST Docs
    11.8. Generating Contracts by Using REST Docs
    12. Migrations
    12.1. 1.0.x → 1.1.x
    12.1.1. New structure of generated stubs
    12.2. 1.1.x → 1.2.x
    12.2.1. Custom HttpServerStub
    12.2.2. New packages for generated tests
    12.2.3. New Methods in TemplateProcessor
    12.2.4. RestAssured 3.0
    12.3. 1.2.x → 2.0.x
    12.3.1. No Camel support
    13. Links

    _Documentation Authors: Adam Dudczak, Mathias Düsterhöft, Marcin Grzejszczak, Dennis Kieselhorst, Jakub Kubryński, Karol Lassak, Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer, Jay Bryant

    2.0.0.BUILD-SNAPSHOT

    1. Spring Cloud Contract

    You need confidence when pushing new features to a new application or service in a distributed system. This project provides support for Consumer Driven Contracts and service schemas in Spring applications (for both HTTP and message-based interactions), @@ -29,7 +29,197 @@ sides.

  • To generate boilerplate test code to be used on features in the contracts. Assume that we have a business use case of fraud check. If a user can be a fraud for 100 different reasons, we would assume that you would create 2 contracts, one for the positive case and one for the negative case. Contract tests are -used to test contracts between applications and not to simulate full behavior.

  • 2.3 How It Works

    This section explores how Spring Cloud Contract Verifier with Stub Runner works.

    2.3.1 Defining the contract

    As consumers of services, we need to define what exactly we want to achieve. We need to +used to test contracts between applications and not to simulate full behavior.

    2.3 How It Works

    This section explores how Spring Cloud Contract Verifier with Stub Runner works.

    2.3.1 A three second tour

    On the Producer Side

    In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts.

    Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
    +	<scope>test</scope>
    +</dependency>
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +</plugin>

    Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests..

    As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail.

    To make them pass, the correct implementation of either handling HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup).

    Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. The changes can now be merged + and both the application and the stub artifacts may be published in an online repository.

    On the Consumer Side

    Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service.

    Add the dependency to Spring Cloud Contract Stub Runner:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>

    Get the Producer-side stubs installed in your Maven repository by either:

    • checking out the Producer side repository, adding contracts and generating the stubs by running:
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail;

    or:

    • getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties:
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: http://repo.spring.io/libs-snapshot

    Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you.

    [Tip]Tip

    Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
    +		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {

    Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service.

    2.3.2 A three minute tour

    On the Producer Side

    In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts.

    For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP +methods, urls, headers, status codes, etc.). A sample HTTP stub contract in Groovy DSL would look like this:

    package contracts
    +
    +org.springframework.cloud.contract.spec.Contract.make {
    +	request {
    +		method 'PUT'
    +		url '/fraudcheck'
    +		body([
    +			   "client.id": $(regex('[0-9]{10}')),
    +			   loanAmount: 99999
    +		])
    +		headers {
    +			contentType('application/json')
    +		}
    +	}
    +	response {
    +		status 200
    +		body([
    +			   fraudCheckStatus: "FRAUD",
    +			   "rejection.reason": "Amount too high"
    +		])
    +		headers {
    +			contentType('application/json')
    +		}
    +	}
    +}

    While the same contract expressed in YAML would look the following way:

    request:
    +  method: PUT
    +  url: /fraudcheck
    +  body:
    +    "client.id": 1234567890
    +    loanAmount: 99999
    +  headers:
    +    Content-Type: application/json
    +  matchers:
    +    body:
    +      - path: $.['client.id']
    +        type: by_regex
    +        value: "[0-9]{10}"
    +response:
    +  status: 200
    +  body:
    +    fraudCheckStatus: "FRAUD"
    +    "rejection.reason": "Amount too high"
    +  headers:
    +    Content-Type: application/json;charset=UTF-8

    In the case of messaging, the input and the output messages can be defined (taking into account from and +where to it was sent, the message body and header), as well as the methods that should be called after the message + is received or the methods that, when called, should trigger a message. +An example of a Camel messaging contract expressed in Groovy DSL whould look like this:

    def contractDsl = Contract.make {
    +	label 'some_label'
    +	input {
    +		messageFrom('jms:delete')
    +		messageBody([
    +				bookName: 'foo'
    +		])
    +		messageHeaders {
    +			header('sample', 'header')
    +		}
    +		assertThat('bookWasDeleted()')
    +	}
    +}

    While, the same contract expressed in YAML would look as in the code below:

    label: some_label
    +input:
    +  messageFrom: jms:delete
    +  messageBody:
    +    bookName: 'foo'
    +  messageHeaders:
    +    sample: header
    +  assertThat: bookWasDeleted()

    Then, add Spring Cloud Contract Verifier dependency and plugin to your build file:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-verifier</artifactId>
    +	<scope>test</scope>
    +</dependency>
    <plugin>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-contract-maven-plugin</artifactId>
    +	<version>${spring-cloud-contract.version}</version>
    +	<extensions>true</extensions>
    +</plugin>

    Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests..

    A sample auto-generated test for an HTTP contract would look the following way:

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

    The sample above uses Spring’s MockMvc to run the tests. This is the default test mode for HTTP +contracts, however also JAX-RX client and explicit HTTP invocations can be used as well (just change +the testMode property of the plugin to JAX-RS or EXPLICIT.

    Apart from the default JUnit, you can also use Spock tests, instead, by setting the plugin testFramework +property to Spock.

    [Tip]Tip

    You can now also generate WireMock scenarios based on the contracts, by including an order number followed by + an underscore at the beginning of the contract file names.

    A sample auto-generated test in Spock for a messaging stub contract would look similar to this:

    [source,groovy,indent=0]
    given:
    +	 ContractVerifierMessage inputMessage = contractVerifierMessaging.create(
    +		\'\'\'{"bookName":"foo"}\'\'\',
    +		['sample': 'header']
    +	)
    +
    +when:
    +	 contractVerifierMessaging.send(inputMessage, 'jms:delete')
    +
    +then:
    +	 noExceptionThrown()
    +	 bookWasDeleted()

    As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail.

    To make them pass, the correct implementation of handling either HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup).

    Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. Information about + installing the stubs jar to the local repository will appear in the logs:

    [INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
    +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
    +[INFO]
    +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
    +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
    +[INFO]
    +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
    +[INFO]
    +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
    +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
    +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
    +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar

    The changes can now be merged and both the application and the stub artifacts may be published in an online repository.

    Docker Project

    In order to enable working with contracts while creating applications in non-JVM technologies, +the springcloud/spring-cloud-contract Docker image has been created. It contains a project that will +automatically generate tests for HTTP contracts and execute them in EXPLICIT test mode, then, if +the tests pass, generate Wiremock stubs and -optionally- publish them to an artifact manager. In order to use the +image, it’s sufficient to mount the contracts into the /contracts directory and set a few environment variables.

    On the Consumer Side

    Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service.

    Add the dependency to Spring Cloud Contract Stub Runner:

    <dependency>
    +	<groupId>org.springframework.cloud</groupId>
    +	<artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
    +	<scope>test</scope>
    +</dependency>

    Get the Producer-side stubs installed in your Maven repository by either:

    • checking out the Producer side repository, adding contracts and generating the stubs by running:
    $ cd local-http-server-repo
    +$ ./mvnw clean install -DskipTests
    [Tip]Tip

    The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail;

    or:

    • getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties:
    stubrunner:
    +  ids: 'com.example:http-server-dsl:+:stubs:8080'
    +  repositoryRoot: http://repo.spring.io/libs-snapshot

    Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you.

    [Tip]Tip

    Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work.

    @RunWith(SpringRunner.class)
    +@SpringBootTest(webEnvironment=WebEnvironment.NONE)
    +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
    +		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    +@DirtiesContext
    +public class LoanApplicationServiceTests {

    Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service. You will see entries similar to theses in the build logs:

    2016-07-19 14:22:25.403  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Desired version is + - will try to resolve the latest version
    +2016-07-19 14:22:25.438  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved version is 0.0.1-SNAPSHOT
    +2016-07-19 14:22:25.439  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
    +2016-07-19 14:22:25.451  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
    +2016-07-19 14:22:25.465  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
    +2016-07-19 14:22:25.475  INFO 41050 --- [           main] o.s.c.c.stubrunner.AetherStubDownloader  : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
    +2016-07-19 14:22:27.737  INFO 41050 --- [           main] o.s.c.c.stubrunner.StubRunnerExecutor    : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]

    2.3.3 Defining the contract

    As consumers of services, we need to define what exactly we want to achieve. We need to formulate our expectations. That is why we write contracts.

    Assume that you want to send a request containing the ID of a client company and the amount it wants to borrow from us. You also want to send it to the /fraudcheck url via the PUT method.

    Groovy DSL.  @@ -143,7 +333,7 @@ response: # (7) #(9) - and JSON body equal to # { "fraudCheckStatus": "FRAUD", "rejectionReason": "Amount too high" } #(10) - with header `Content-Type` equal to `application/json;charset=UTF-8`

    -

    2.3.2 Client Side

    Spring Cloud Contract generates stubs, which you can use during client-side testing. +

    2.3.4 Client Side

    Spring Cloud Contract generates stubs, which you can use during client-side testing. You get a running WireMock instance/Messaging route that simulates the service. You would like to feed that instance with a proper stub definition.

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

    ResponseEntity<FraudServiceResponse> response =
     		restTemplate.exchange("http://localhost:" + port + "/fraudcheck", HttpMethod.PUT,
    @@ -155,7 +345,7 @@ You would like to feed that instance with a proper stub definition.

    At som @DirtiesContext public class LoanApplicationServiceTests {

    After that, during the tests, Spring Cloud Contract automatically finds the stubs (simulating the real service) in the Maven repository and exposes them on a configured -(or random) port.

    2.3.3 Server Side

    Since you are developing your stub, you need to be sure that it actually resembles your +(or random) port.

    2.3.5 Server Side

    Since you are developing your stub, you need to be sure that it actually resembles your concrete implementation. You cannot have a situation where your stub acts in one way and your application behaves in a different way, especially in production.

    To ensure that your application behaves the way you define in your stub, tests are generated from the stub you provide.

    The autogenerated test looks, more or less, like this:

    @Test
    @@ -388,7 +578,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo
     different ranges of values. To enable ranges of values, you can set regular expressions
     matching those values for the consumer side. You can provide the body by means of either
     a map notation or String with interpolations.
    -Consult the docs
    +Consult the docs
     for more information. We highly recommend using the map notation!

    [Tip]Tip

    You must understand the map notation in order to set up contracts. Please read the Groovy docs regarding JSON.

    The previously shown contract is an agreement between two sides that:

    • if an HTTP request is sent with all of

      • a PUT method on the /fraudcheck endpoint,
      • a JSON body with a client.id that matches the regular expression [0-9]{10} and loanAmount equal to 99999,
      • and a Content-Type header with a value of application/vnd.fraud.v1+json,
    • then an HTTP response is sent to the consumer that

      • has status 200,
      • contains a JSON body with the fraudCheckStatus field containing a value FRAUD and @@ -446,7 +636,7 @@ Application service):

        Add the Spring Cloud Co </dependency>

    Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the group-id and artifact-id for the Stub Runner to download the stubs of your collaborators. (Optional step) Because you’re playing with the collaborators offline, you -can also provide the offline work switch.

    @RunWith(SpringRunner.class)
    +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL).

    @RunWith(SpringRunner.class)
     @SpringBootTest(webEnvironment=WebEnvironment.NONE)
     @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"},
     		stubsMode = StubRunnerProperties.StubsMode.LOCAL)
    @@ -610,7 +800,7 @@ sides of the communication. You can pass the values:

    Either via the

    or using the $() method

    $(consumer(...), producer(...))
     $(stub(...), test(...))
    -$(client(...), server(...))

    You can read more about this in the Contract DSL section.

    Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. +$(client(...), server(...))

    You can read more about this in the Contract DSL section.

    Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). Inside the producer() method you pass the value that should be used on the producer side (in the generated test).

    [Tip]Tip

    If on one side you have passed the regular expression and you haven’t passed the other, then the other side will get auto-generated.

    Most often you will use that method together with the regex helper method. E.g. consumer(regex('[0-9]{10}')).

    To sum it up the contract for the aforementioned scenario would look more or less like this (the regular expression @@ -1568,7 +1758,7 @@ stateful situation

      • the contracts will be taken from /contracts folder.
      • the output of the test execution is available under node_modules/spring-cloud-contract/output.
  • the stubs will be uploaded to Artifactory. You can check them out under http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/ . -The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.
  • To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

    5. Spring Cloud Contract Verifier Messaging

    Spring Cloud Contract Verifier lets you verify applications that uses messaging as a +The stubs will be here http://localhost:8081/artifactory/libs-release-local/com/example/bookstore/0.0.1.RELEASE/bookstore-0.0.1.RELEASE-stubs.jar.

    To see how the client side looks like check out the Section 6.9, “Stub Runner Docker” section.

    5. Spring Cloud Contract Verifier Messaging

    Spring Cloud Contract Verifier lets you verify applications that use messaging as a means of communication. All of the integrations shown in this document work with Spring, but you can also create one of your own and use that.

    5.1 Integrations

    You can use one of the following four integration configurations:

    • Apache Camel
    • Spring Integration
    • Spring Cloud Stream
    • Spring AMQP

    Since we use Spring Boot, if you have added one of these libraries to the classpath, all the messaging configuration is automatically set up.

    [Important]Important

    Remember to put @AutoConfigureMessageVerifier on the base class of your diff --git a/spring-cloud-contract.xml b/spring-cloud-contract.xml index 0eab894eac..341c5548e3 100644 --- a/spring-cloud-contract.xml +++ b/spring-cloud-contract.xml @@ -168,6 +168,305 @@ used to test contracts between applications and not to simulate full behavior. How It Works This section explores how Spring Cloud Contract Verifier with Stub Runner works. +

    +A three second tour +
    +On the Producer Side +In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts. +Then, add Spring Cloud Contract Verifier dependency and plugin to your build file: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> +</plugin> +Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests.. +As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail. +To make them pass, the correct implementation of either handling HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup). +Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. The changes can now be merged + and both the application and the stub artifacts may be published in an online repository. +
    +
    +On the Consumer Side +Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service. +Add the dependency to Spring Cloud Contract Stub Runner: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> +</dependency> +Get the Producer-side stubs installed in your Maven repository by either: + + +checking out the Producer side repository, adding contracts and generating the stubs by running: + + +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests + +The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail; + +or: + + +getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties: + + +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: http://repo.spring.io/libs-snapshot +Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you. + +Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work. + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +@DirtiesContext +public class LoanApplicationServiceTests { +Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service. +
    +
    +
    +A three minute tour +
    +On the Producer Side +In order to start working with Spring Cloud Contract, add files with REST/ messaging contracts expressed in either +Groovy DSL or YAML to the contracts directory set by the +contractsDslDir property, by default $rootDir/src/test/resources/contracts. +For the HTTP stubs, a contract defines what kind of response should be returned for a given request (taking into account the HTTP +methods, urls, headers, status codes, etc.). A sample HTTP stub contract in Groovy DSL would look like this: +package contracts + +org.springframework.cloud.contract.spec.Contract.make { + request { + method 'PUT' + url '/fraudcheck' + body([ + "client.id": $(regex('[0-9]{10}')), + loanAmount: 99999 + ]) + headers { + contentType('application/json') + } + } + response { + status 200 + body([ + fraudCheckStatus: "FRAUD", + "rejection.reason": "Amount too high" + ]) + headers { + contentType('application/json') + } + } +} +While the same contract expressed in YAML would look the following way: +request: + method: PUT + url: /fraudcheck + body: + "client.id": 1234567890 + loanAmount: 99999 + headers: + Content-Type: application/json + matchers: + body: + - path: $.['client.id'] + type: by_regex + value: "[0-9]{10}" +response: + status: 200 + body: + fraudCheckStatus: "FRAUD" + "rejection.reason": "Amount too high" + headers: + Content-Type: application/json;charset=UTF-8 +In the case of messaging, the input and the output messages can be defined (taking into account from and +where to it was sent, the message body and header), as well as the methods that should be called after the message + is received or the methods that, when called, should trigger a message. +An example of a Camel messaging contract expressed in Groovy DSL whould look like this: +def contractDsl = Contract.make { + label 'some_label' + input { + messageFrom('jms:delete') + messageBody([ + bookName: 'foo' + ]) + messageHeaders { + header('sample', 'header') + } + assertThat('bookWasDeleted()') + } +} +While, the same contract expressed in YAML would look as in the code below: +label: some_label +input: + messageFrom: jms:delete + messageBody: + bookName: 'foo' + messageHeaders: + sample: header + assertThat: bookWasDeleted() +Then, add Spring Cloud Contract Verifier dependency and plugin to your build file: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-verifier</artifactId> + <scope>test</scope> +</dependency> +<plugin> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-maven-plugin</artifactId> + <version>${spring-cloud-contract.version}</version> + <extensions>true</extensions> +</plugin> +Now, running ./mvnw clean install will cause tests that verify the application +compliance with the added contracts to be automatically generated, by default under org.springframework.cloud.contract.verifier.tests.. +A sample auto-generated test for an HTTP contract would look the following way: +@Test +public void validate_shouldMarkClientAsFraud() throws Exception { + // given: + MockMvcRequestSpecification request = given() + .header("Content-Type", "application/vnd.fraud.v1+json") + .body("{\"client.id\":\"1234567890\",\"loanAmount\":99999}"); + + // when: + ResponseOptions response = given().spec(request) + .put("/fraudcheck"); + + // then: + assertThat(response.statusCode()).isEqualTo(200); + assertThat(response.header("Content-Type")).matches("application/vnd.fraud.v1.json.*"); + // and: + DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); + assertThatJson(parsedJson).field("['fraudCheckStatus']").matches("[A-Z]{5}"); + assertThatJson(parsedJson).field("['rejection.reason']").isEqualTo("Amount too high"); +} +The sample above uses Spring’s MockMvc to run the tests. This is the default test mode for HTTP +contracts, however also JAX-RX client and explicit HTTP invocations can be used as well (just change +the testMode property of the plugin to JAX-RS or EXPLICIT. +Apart from the default JUnit, you can also use Spock tests, instead, by setting the plugin testFramework +property to Spock. + +You can now also generate WireMock scenarios based on the contracts, by including an order number followed by + an underscore at the beginning of the contract file names. + +A sample auto-generated test in Spock for a messaging stub contract would look similar to this: +[source,groovy,indent=0] +given: + ContractVerifierMessage inputMessage = contractVerifierMessaging.create( + \'\'\'{"bookName":"foo"}\'\'\', + ['sample': 'header'] + ) + +when: + contractVerifierMessaging.send(inputMessage, 'jms:delete') + +then: + noExceptionThrown() + bookWasDeleted() +As the implementation of the functionalities described by the contracts is not yet present, + the tests will fail. +To make them pass, the correct implementation of handling either HTTP requests or messages +will have to be added. Also, a correct base test class for auto-generated tests needs to be added to the project. +This class will be extended by all the auto-generated tests and it should contain all the setup +necessary to run them (for example RestAssuredMockMvc controller setup or messaging test setup). +Once the implementation and the test base class are in place, the tests will pass, and both the application + and the stub artifacts will be built and installed in the local Maven repository. Information about + installing the stubs jar to the local repository will appear in the logs: +[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar +[INFO] +[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server --- +[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar +[INFO] +[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server --- +[INFO] +[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server --- +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar +[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom +[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +The changes can now be merged and both the application and the stub artifacts may be published in an online repository. +Docker Project +In order to enable working with contracts while creating applications in non-JVM technologies, +the springcloud/spring-cloud-contract Docker image has been created. It contains a project that will +automatically generate tests for HTTP contracts and execute them in EXPLICIT test mode, then, if +the tests pass, generate Wiremock stubs and -optionally- publish them to an artifact manager. In order to use the +image, it’s sufficient to mount the contracts into the /contracts directory and set a few environment variables. +
    +
    +On the Consumer Side +Spring Cloud Contract Stub Runner can be used in the integration tests to get a running WireMock instance/ +messaging route that simulates the actual service. +Add the dependency to Spring Cloud Contract Stub Runner: +<dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-starter-contract-stub-runner</artifactId> + <scope>test</scope> +</dependency> +Get the Producer-side stubs installed in your Maven repository by either: + + +checking out the Producer side repository, adding contracts and generating the stubs by running: + + +$ cd local-http-server-repo +$ ./mvnw clean install -DskipTests + +The tests are being skipped because the Producer-side contract implementation is not in place yet, +so the automatically-generated contract tests would fail; + +or: + + +getting already existing producer service stubs from a remote repository; to do this, simply pass the +stub artifact ids and artifact repository url as Spring Cloud Contract Stub Runner properties: + + +stubrunner: + ids: 'com.example:http-server-dsl:+:stubs:8080' + repositoryRoot: http://repo.spring.io/libs-snapshot +Now just annotate your test class with @AutoConfigureStubRunner. In the annotation, provide +the group-id and artifact-id for Spring Cloud Contract Stub Runner to run the collaborators' stubs for you. + +Use the REMOTE stubsMode when downloading stubs from an online repository and LOCAL for offline work. + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment=WebEnvironment.NONE) +@AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, + stubsMode = StubRunnerProperties.StubsMode.LOCAL) +@DirtiesContext +public class LoanApplicationServiceTests { +Now in your integration test, you will be able to receive stubbed versions of HTTP responses or messages that are +expected to be emitted by the collaborator service. You will see entries similar to theses in the build logs: +2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version +2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT +2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories [] +2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar +2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar] +2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265] +2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}] +
    +
    Defining the contract As consumers of services, we need to define what exactly we want to achieve. We need to @@ -644,7 +943,7 @@ of an identifier or a timestamp, you need not hardcode a value. You want to allo different ranges of values. To enable ranges of values, you can set regular expressions matching those values for the consumer side. You can provide the body by means of either a map notation or String with interpolations. -Consult the docs +Consult the docs for more information. We highly recommend using the map notation! You must understand the map notation in order to set up contracts. Please read the @@ -765,7 +1064,7 @@ Application service): Annotate your test class with @AutoConfigureStubRunner. In the annotation, provide the group-id and artifact-id for the Stub Runner to download the stubs of your collaborators. (Optional step) Because you’re playing with the collaborators offline, you -can also provide the offline work switch. +can also provide the offline work switch (StubRunnerProperties.StubsMode.LOCAL). @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment=WebEnvironment.NONE) @AutoConfigureStubRunner(ids = {"com.example:http-server-dsl:+:stubs:6565"}, @@ -1067,7 +1366,7 @@ value(client(...), server(...)) $(consumer(...), producer(...)) $(stub(...), test(...)) $(client(...), server(...)) -You can read more about this in the Contract DSL section. +You can read more about this in the Contract DSL section. Calling value() or $() tells Spring Cloud Contract that you will be passing a dynamic value. Inside the consumer() method you pass the value that should be used on the consumer side (in the generated stub). Inside the producer() method you pass the value that should be used on the producer side (in the generated test). @@ -2798,7 +3097,7 @@ The stubs will be here Spring Cloud Contract Verifier Messaging -Spring Cloud Contract Verifier lets you verify applications that uses messaging as a +Spring Cloud Contract Verifier lets you verify applications that use messaging as a means of communication. All of the integrations shown in this document work with Spring, but you can also create one of your own and use that.