diff --git a/README.adoc b/README.adoc index d322057f1a..7d7e782472 100644 --- a/README.adoc +++ b/README.adoc @@ -8,104 +8,127 @@ image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg[ == Spring Cloud Contract -What you always need is confidence in pushing new features into a new application or service in a distributed system. -This project provides support for Consumer Driven Contracts and service schemas in Spring applications, covering a -range of options for writing tests, publishing them as assets, asserting that a contract is kept by producers -and consumers, for HTTP and message-based interactions. +You always need confidence when pushing new features into a new application or service in +a distributed system. To that end, this project provides support for Consumer-driven +Contracts and service schemas in Spring applications, covering a range of options for +writing tests, publishing them as assets, and asserting that a contract is kept by +producers and consumers -- for both HTTP and message-based interactions. === Spring Cloud Contract workshops -If you prefer to learn about the project by doing some tutorials you can check out the workshops under +If you prefer to learn about the project by doing some tutorials, you can check out the +workshops under http://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link]. === Spring Cloud Contract Verifier == Spring Cloud Contract Verifier Introduction -TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski (http://codearte.io[codearte.io]) +TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski +(http://codearte.io[codearte.io]) -Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped -with __Contract Definition Language__ (DSL). Contract definitions are used to produce following resources: +Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture. -* JSON stub definitions to be used by WireMock when doing integration testing on the client code (__client tests__). -Test code must still be written by hand, test data is produced by Spring Cloud Contract Verifier. -* Messaging routes if you're using one. We're integrating with Spring Integration, Spring Cloud Stream, Spring AMQP. You can however set your own integrations if you want to -* Acceptance tests (in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (__server tests__). -Full test is generated by Spring Cloud Contract Verifier. +Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract +definitions are used to produce the following resources: -Spring Cloud Contract Verifier moves TDD to the level of software architecture. +* JSON stub definitions to be used by WireMock when doing integration testing on the +client code (_client tests_). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier. +* Messaging routes, if you're using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations. +* Acceptance tests (in JUnit or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (__server tests__). A full test is generated by +Spring Cloud Contract Verifier. -=== Why? +=== Why a Contract Verifier? -Let us assume that we have a system comprising of multiple microservices: +Assume that we have a system consisting of multiple microservices: image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] ==== Testing issues -If we wanted to test the application in top left corner if it can communicate with other services then we could do one of two things: +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: -- deploy all microservices and perform end to end tests -- mock other microservices in unit / integration tests +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. -Both have their advantages but also a lot of disadvantages. Let's focus on the latter. +Both have their advantages but also a lot of disadvantages. *Deploy all microservices and perform end to end tests* Advantages: -- simulates production -- tests real communication between services +- Simulates production. +- Tests real communication between services. Disadvantages: -- to test one microservice we would have to deploy 6 microservices, a couple of databases etc. -- the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime). -- long to run -- very late feedback -- extremely hard to debug +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. -*Mock other microservices in unit / integration tests* +*Mock other microservices in unit/integration tests* Advantages: -- very fast feedback -- no infrastructure requirements +- They provide very fast feedback. +- They have no infrastructure requirements. Disadvantages: -- the implementor of the service creates stubs thus they might have nothing to do with the reality -- you can go to production with passing tests and failing production +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. -To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need -to set up the whole world of microservices. If you work on stubs then the only applications you need are those that your application is using directly. +To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] -Spring Cloud Contract Verifier gives you the certainty that the stubs that you're using were created by the service that you're calling. Also if you can use them it means that they were -tested against the producer's side. In other words - you can trust those stubs. +Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. === Purposes The main purposes of Spring Cloud Contract Verifier with Stub Runner are: - - to ensure that WireMock / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do, - - to promote ATDD method and Microservices architectural style, - - to provide a way to publish changes in contracts that are immediately visible on both sides, - - to generate boilerplate test code used on the server side. +- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both +sides. +- To generate boilerplate test code to be used on the server side. -IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business features in the contracts. -Let's 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 and one for the negative fraud case. -Contract tests are used to test contracts between applications and not to simulate full behaviour. +IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. -=== How +=== How It Works -==== Define the contract +This section explores how Spring Cloud Contract Verifier with Stub Runner works. -As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract. +==== Defining the contract -Let’s assume that we’d like to send the request containing the id of the client and the amount he wants to borrow from us. We’d like to send it to the /fraudcheck url via the PUT method. +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. [source,groovy,indent=0] ---- @@ -170,11 +193,11 @@ From the Producer perspective, in the autogenerated producer-side test: ==== Client Side -Spring Cloud Contract will generate stubs, which you can use during client side testing. -You will have a WireMock instance / Messaging route up and running that simulates the service Y. +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. +At some point in time, you need to send a request to the Fraud Detection service. [source,groovy,indent=0] ---- @@ -195,18 +218,20 @@ Annotate your test class with `@AutoConfigureStubRunner`. In the annotation prov public class LoanApplicationServiceTests { ---- -After that, during the tests Spring Cloud Contract will automatically find the stubs (simulating the real service) in Maven repository and expose them on configured (or random) port. +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. ==== Server Side -Being a service Y since you are developing your stub, you need to be sure that it's actually resembling your -concrete implementation. You can't have a situation where your stub acts in one way and your application on -production behaves in a different way. +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. -That's why from the provided stub acceptance tests will be generated that will ensure -that your application behaves in the same way as you define in your stub. +To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide. -The autogenerated test would look like this: +The autogenerated test looks like this: [source,java,indent=0] ---- @@ -231,26 +256,33 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -=== Step by step guide to CDC +=== Step-by-step Guide to Consumer Driven Contracts (CDC) -Let's take an example of Fraud Detection and Loan Issuance process. The business scenario is such that we want to issue loans to people but don't want them to steal the money from us. The current implementation of our system grants loans to everybody. +Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody. -Let's assume that the `Loan Issuance` is a client to the -`Fraud Detection` server. In the current sprint we are required to develop a new feature - if a client wants to borrow too much money then we mark him as fraud. +Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud. -Technical remark - Fraud Detection will have artifact id `http-server`, Loan Issuance `http-client` and both have group id `com.example`. +Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan +Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. -Social remark - both client and server development teams need to communicate directly and discuss changes while -going through the process. CDC is all about communication. +Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication. -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the client side code here]. +The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server +side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the +client code here]. -TIP: In this case the ownership of the contracts lays on the producer side. It means that physically -all the contract are present in the producer's repository +TIP: In this case, the producer owns the contracts. Physically, all the contract are +in the producer's repository. ==== Technical note -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the following section to your +If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the +following section to your build: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -323,9 +355,22 @@ repositories { ==== Consumer side (Loan Issuance) -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: -*start doing TDD by writing a test to your feature* +. Start doing TDD by writing a test for your feature. +. Write the missing implementation. +. Clone the Fraud Detection service repository locally. +. Define the contract locally in the repo of Fraud Detection service. +. Add the Spring Cloud Contract Verifier plugin. +. Run the integration tests. +. File a pull request. +. Create an initial implementation. +. Take over the pull request. +. Write the missing implementation. +. Deploy your app. +. Work online. + +*Start doing TDD by writing a test for your feature.* [source,groovy,indent=0] ---- @@ -343,11 +388,14 @@ public void shouldBeRejectedDueToAbnormalLoanAmount() { } ---- -We've just written a test of our new feature. If a loan application for a big amount is received we should reject that loan application with some description. +Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description. -*write the missing implementation* +*Write the missing implementation.* -At some point in time you need to send a request to the Fraud Detection service. Let's assume that we'd like to send the request containing the id of the client and the amount he wants to borrow from us. We'd like to send it to the `/fraudcheck` url via the `PUT` method. +At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. [source,groovy,indent=0] ---- @@ -357,25 +405,29 @@ ResponseEntity response = FraudServiceResponse.class); ---- -For simplicity we've hardcoded the port of the Fraud Detection service at `8080` and our application is running on `8090`. +For simplicity, the port of the Fraud Detection service is set to `8080`, and the +application runs on `8090`. -If we'd start the written test it would obviously break since we have no service running on port `8080`. +If you start the test at this point, it breaks, because no service currently runs on port +`8080`. -*clone the Fraud Detection service repository locally* +*Clone the Fraud Detection service repository locally.* -We'll start playing around with the server side contract. That's why we need to first clone it. +You can start by playing around with the server side contract. To do so, you must first +clone it. [source,bash,indent=0] ---- git clone https://your-git-server.com/server-side.git local-http-server-repo ---- -*define the contract locally in the repo of Fraud Detection service* +*Define the contract locally in the repo of Fraud Detection service.* -As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract. +As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract: -IMPORTANT: We're placing the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder -is important cause we'll reference that folder in the producer's test base class name. +IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder +is important because the producer's test base class name references that folder. [source,groovy,indent=0] ---- @@ -438,34 +490,39 @@ From the Producer perspective, in the autogenerated producer-side test: */ ---- -The Contract is written using a statically typed Groovy DSL. You might be wondering what are those -`value(client(...), server(...))` parts. By using this notation Spring Cloud Contract allows you to -define parts of a JSON / URL / etc. which are dynamic. In case of an identifier or a timestamp you -don't want to hardcode a value. You want to allow some different ranges of values. That's why for -the consumer side you can set regular expressions matching those values. You can provide the body -either by means of a map notation or String with interpolations. +The Contract is written using a statically typed Groovy DSL. You might wonder what about +those `value(client(...), server(...))` parts. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_contract_dsl[Consult the docs for more information.] We highly recommend using the map notation! -TIP: It's really important that you understand the map notation to set up contracts. Please read the -http://groovy-lang.org/json.html[Groovy docs regarding JSON] +TIP: You must understand the map notation in order to set up contracts. Please read the +http://groovy-lang.org/json.html[Groovy docs regarding JSON]. -The aforementioned contract is an agreement between two sides that: +The previously shown contract is an agreement between two sides that: -- if an HTTP request is sent with -** a method `PUT` on an endpoint `/fraudcheck` -** JSON body with `client.id` matching the regular expression `[0-9]{10}` and `loanAmount` equal to `99999` -** and with a header `Content-Type` equal to `application/vnd.fraud.v1+json` -- then an HTTP response would be sent to the consumer that -** has status `200` -** contains JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and the `rejectionReason` field having value `Amount too high` -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json` +- 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 +the `rejectionReason` field having value `Amount too high`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. -Once we're ready to check the API in practice in the integration tests we need to just install the stubs locally +Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally. -*add the Spring Cloud Contract Verifier plugin* +*Add the Spring Cloud Contract Verifier plugin.* -We can add either Maven or Gradle plugin - in this example we'll show how to add Maven. First we need to add the `Spring Cloud Contract` BOM. +We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the `Spring Cloud Contract` BOM. [source,xml,indent=0] ---- @@ -482,7 +539,7 @@ We can add either Maven or Gradle plugin - in this example we'll show how to add ---- -Next, the `Spring Cloud Contract Verifier` Maven plugin +Next, add the `Spring Cloud Contract Verifier` Maven plugin [source,xml,indent=0] ---- @@ -497,12 +554,14 @@ Next, the `Spring Cloud Contract Verifier` Maven plugin ---- -Since the plugin was added we get the `Spring Cloud Contract Verifier` features which from the provided contracts: +Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, +from the provided contracts: - generate and run tests - produce and install stubs -We don't want to generate tests since we, as consumers, want only to play with the stubs. That's why we need to skip the tests generation and execution. When we execute: +You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute: [source,bash,indent=0] ---- @@ -510,7 +569,7 @@ cd local-http-server-repo ./mvnw clean install -DskipTests ---- -In the logs we'll see something like this: +In the logs, you see something like this: [source,bash,indent=0] ---- @@ -528,20 +587,23 @@ In the logs we'll see something like this: [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 ---- -This line is extremely important +The following line is extremely important: [source,bash,indent=0] ---- [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 ---- -It's confirming that the stubs of the `http-server` have been installed in the local repository. +It confirms that the stubs of the `http-server` have been installed in the local +repository. -*run the integration tests* +*Run the integration tests.* -In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic stub downloading you have to do the following in our consumer side project (`Loan Application service`). +In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (`Loan +Application service`): -Add the `Spring Cloud Contract` BOM +Add the `Spring Cloud Contract` BOM: [source,xml,indent=0] ---- @@ -558,7 +620,7 @@ Add the `Spring Cloud Contract` BOM ---- -Add the dependency to `Spring Cloud Contract Stub Runner` +Add the dependency to `Spring Cloud Contract Stub Runner`: [source,xml,indent=0] ---- @@ -569,7 +631,10 @@ Add the dependency to `Spring Cloud Contract Stub Runner` ---- -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. Also provide the offline work switch since you're playing with the collaborators offline (optional step). +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. [source,groovy,indent=0] ---- @@ -580,7 +645,7 @@ Annotate your test class with `@AutoConfigureStubRunner`. In the annotation prov public class LoanApplicationServiceTests { ---- -Now if you run your tests you'll see sth like this: +Now, when you run your tests, you see something like this: [source,bash,indent=0] ---- @@ -593,21 +658,26 @@ Now if you run your tests you'll see sth like this: 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}] ---- -Which means that Stub Runner has found your stubs and started a server for app with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of the stubs and with `stubs` classifier on port `8080`. +This output means that Stub Runner has found your stubs and started a server for your app +with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of +the stubs and with `stubs` classifier on port `8080`. -*file a PR* +*File a pull request.* -What we did until now is an iterative process. We can play around with the contract, install it locally and work on the consumer side until we're happy with the contract. +What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish. -Once we're satisfied with the results and the test passes publish a PR to the server side. Currently the consumer side work is done. +Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done. ==== Producer side (Fraud Detection server) As a developer of the Fraud Detection server (a server to the Loan Issuance service): -*initial implementation* +*Create an initial implementation.* -As a reminder here you can see the initial implementation +As a reminder, you can see the initial implementation here: [source,java,indent=0] ---- @@ -617,7 +687,7 @@ return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); } ---- -*take over the PR* +*Take over the pull request.* [source,bash,indent=0] ---- @@ -625,7 +695,7 @@ git checkout -b contract-change-pr master git pull https://your-git-server.com/server-side-fork.git contract-change-pr ---- -You have to add the dependencies needed by the autogenerated tests +You must add the dependencies needed by the autogenerated tests: [source,xml,indent=0] ---- @@ -636,7 +706,7 @@ You have to add the dependencies needed by the autogenerated tests ---- -In the configuration of the Maven plugin we passed the `packageWithBaseClasses` property +In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property [source,xml,indent=0] ---- @@ -651,14 +721,16 @@ In the configuration of the Maven plugin we passed the `packageWithBaseClasses` ---- -IMPORTANT: We've decided to use the "convention based" naming by setting the `packageWithBaseClasses` property. -That means that 2 last packages will be combined into a name of the base test class. In our case the contracts -were placed under `src/test/resources/contracts/fraud`. Since we don't have 2 packages starting from the `contracts` -folder we're picking only one which is `fraud`. We're adding the `Base` suffix and we're capitalizing `fraud`. -That gives us the `FraudBase` test class name. +IMPORTANT: This example uses "convention based" naming by setting the +`packageWithBaseClasses` property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +`src/test/resources/contracts/fraud`. Since you do not have two packages starting from +the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and +capitalize `fraud`. That gives you the `FraudBase` test class name. -That's because all the generated tests will extend that class. Over there you can set up your Spring Context or -whatever is necessary. In our case we're using http://rest-assured.io/[Rest Assured MVC] to start the server side `FraudDetectionController`. +All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use http://rest-assured.io/[Rest Assured MVC] to +start the server side `FraudDetectionController`. [source,java,indent=0] ---- @@ -693,7 +765,7 @@ public class FraudBase { } ---- -Now, if you run the `./mvnw clean install` you would get sth like this: +Now, if you run the `./mvnw clean install`, you get something like this: [source,bash,indent=0] ---- @@ -703,7 +775,9 @@ Tests in error: ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ---- -That's because you have a new contract from which a test was generated and it failed since you haven't implemented the feature. The autogenerated test would look like this: +This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this: [source,java,indent=0] ---- @@ -728,13 +802,19 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -As you can see all the `producer()` parts of the Contract that were present in the `value(consumer(...), producer(...))` blocks got injected into the test. +As you can see, all the `producer()` parts of the Contract that were present in the +`value(consumer(...), producer(...))` blocks got injected into the test. -What's important here to note is that on the producer side we also are doing TDD. We have expectations in form of a test. This test is shooting a request to our own application to an URL, headers and body defined in the contract. It also is expecting very precisely defined values in the response. In other words you have is your `red` part of `red`, `green` and `refactor`. Time to convert the `red` into the `green`. +Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the `red` part of `red`, `green`, and +`refactor`. It is time to convert the `red` into the `green`. -*write the missing implementation* +*Write the missing implementation.* -Now since we now what is the expected input and expected output let's write the missing implementation. +Because you know the expected input and expected output, you can write the missing +implementation: [source,java,indent=0] ---- @@ -747,11 +827,13 @@ return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); } ---- -If we execute `./mvnw clean install` again the tests will pass. Since the `Spring Cloud Contract Verifier` plugin adds the tests to the `generated-test-sources` you can actually run those tests from your IDE. +When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud +Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can +actually run those tests from your IDE. -*deploy your app* +*Deploy your app.* -Once you've finished your work it's time to deploy your change. First merge the branch +Once you finish your work, you can deploy your change. First, merge the branch: [source,bash,indent=0] ---- @@ -760,13 +842,14 @@ git merge --no-ff contract-change-pr git push origin master ---- -Then we assume that your CI would run sth like `./mvnw clean deploy` which would publish both the application and the stub artifcats. +Your CI might run something like `./mvnw clean deploy`, which would publish both the +application and the stub artifacts. -==== Consumer side (Loan Issuance) final step +==== Consumer Side (Loan Issuance) Final Step As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): -*merge branch to master* +*Merge branch to master.* [source,bash,indent=0] ---- @@ -774,11 +857,13 @@ git checkout master git merge --no-ff contract-change-pr ---- -*work online* +*Work online.* -Now you can disable the offline work for Spring Cloud Contract Stub Runner and provide where the repository with your stubs is placed. At this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory. -You can switch off the value of the `workOffline` parameter in your annotation. Below you can see an -example of achieving the same by changing the properties. +Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can switch off the value of +the `workOffline` parameter in your annotation. The following code shows an example of +achieving the same thing by changing the properties. [source,yaml,indent=0] ---- @@ -787,19 +872,20 @@ stubrunner: repositoryRoot: http://repo.spring.io/libs-snapshot ---- -And that's it! +That's it! === Dependencies -The best way to add the dependencies is to just use the proper `starter` dependency. +The best way to add dependencies is to use the proper `starter` dependency. -For `stub-runner` use `spring-cloud-starter-stub-runner` and when you're using a plugin just add +For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add `spring-cloud-starter-contract-verifier`. -=== Additional links +=== Additional Links -Below you can find some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some can be outdated since the Spring Cloud Contract Verifier project -is under constant development. +Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development. ==== Spring Cloud Contract video @@ -816,21 +902,30 @@ video::sAAklvxmPmk[youtube,start=538,width=640,height=480] === Samples -Here you can find some https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. +You can find some samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. == Links -Here you can find interesting links related to Spring Cloud Contract Verifier: +The following links may be helpful when working with Spring Cloud Contract Verifier: -- https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github Repository] -- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud Contract Samples] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud Contract Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest Legacy Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring Cloud Contract Stub Runner Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring Cloud Contract Stub Runner Messaging Documentation] -- https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin] -- https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by Marcin Grzejszczak] +* https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github +Repository] +* https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud +Contract Samples] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud +Contract Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest +Legacy Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring +Cloud Contract Stub Runner Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring +Cloud Contract Stub Runner Messaging Documentation] +* https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring +Cloud Contract Maven Plugin] +* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by +Marcin Grzejszczak] === Spring Cloud Contract WireMock @@ -840,18 +935,17 @@ Here you can find interesting links related to Spring Cloud Contract Verifier: == Spring Cloud Contract WireMock -Modules giving you the possibility to use -http://wiremock.org[WireMock] in a Spring Boot application. Check out the +The Spring Cloud Contract WireMock modules let you use http://wiremock.org[WireMock] in a +Spring Boot application. Check out the https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples] for more details. -If you have a Spring Boot application that uses Tomcat as an embedded -server, for example (the default with `spring-boot-starter-web`), then -you can simply add `spring-cloud-contract-wiremock` to your classpath -and add `@AutoConfigureWireMock` in order to be able to use Wiremock -in your tests. Wiremock runs as a stub server and you can register -stub behaviour using a Java API or via static JSON declarations as -part of your test. Here's a simple example: +If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with `spring-boot-starter-web`), you can add +`spring-cloud-contract-wiremock` to your classpath and add `@AutoConfigureWireMock` in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example: [source,java,indent=0] ---- @@ -875,16 +969,20 @@ public class WiremockForDocsTests { } ---- -To start the stub server on a different port use `@AutoConfigureWireMock(port=9999)` (for example), and for a random port use the value 0. The stub server port will be bindable in the test application context as "wiremock.server.port". Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to your test application context, where it will be cached in between methods and classes having the same context, just like for normal Spring integration tests. +To start the stub server on a different port use (for example), +`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. === Registering Stubs Automatically -If you use `@AutoConfigureWireMock` then it will register WireMock -JSON stubs from the file system or classpath, by default from -`file:src/test/resources/mappings`. You can customize the locations -using the `stubs` attribute in the annotation, which can be a resource -pattern (ant-style) or a directory, in which case `**/*.json` is -appended. Example: +If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file +system or classpath (by default, from `file:src/test/resources/mappings`). You can +customize the locations using the `stubs` attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is +appended. The following code shows an example: ---- @RunWith(SpringRunner.class) @@ -903,35 +1001,32 @@ public class WiremockImportApplicationTests { } ---- -NOTE: Actually WireMock always loads mappings from -`src/test/resources/mappings` *as well as* the custom locations in the -stubs attribute. To change this behaviour you have to also specify a -files root as described next. +NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as +well as* the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. === Using Files to Specify the Stub Bodies -WireMock can read response bodies from files on the classpath or file -system. In that case you will see in the JSON DSL that the response -has a "bodyFileName" instead of a (literal) "body". The files are -resolved relative to a root directory `src/test/resources/\__files` by -default. To customize this location you can set the `files` attribute -in the `@AutoConfigureWireMock` annotation to the location of the -parent directory (i.e. the place `__files` is a -subdirectory). You can use Spring resource notation to refer to -`file:...` or `classpath:...` locations (but generic URLs are not -supported). A list of values can be given and WireMock will resolve -the first file that exists when it needs to find a response body. +WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a +(literal) `body`. The files are resolved relative to a root directory (by default, +`src/test/resources/\__files`). To customize this location you can set the `files` +attribute in the `@AutoConfigureWireMock` annotation to the location of the parent +directory (in other words, `__files` is a subdirectory). You can use Spring resource +notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body. -NOTE: when you configure the `files` root, then it affects the -automatic loading of stubs as well (they come from the root location -in a subdirectory called "mappings"). The value of `files` has no +NOTE: When you configure the `files` root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of `files` has no effect on the stubs loaded explicitly from the `stubs` attribute. === Alternative: Using JUnit Rules -For a more conventional WireMock experience, using JUnit `@Rules` to -start and stop the server, just use the `WireMockSpring` convenience -class to obtain an `Options` instance: +For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop +the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` +instance, as shown in the followin example: [source,java,indent=0] ---- @@ -961,18 +1056,20 @@ public class WiremockForDocsClassRuleTests { } ---- -The use `@ClassRule` means that the server will shut down after all the methods in this class. +The `@ClassRule` means that the server shuts down after all the methods in this class +have been run. === Relaxed SSL Validation for Rest Template -WireMock allows you to stub a "secure" server with an "https" URL protocol. If your application wants to -contact that stub server in an integration test, then it will find that the SSL certificates are not -valid (it's the usual problem with self-installed certificates). The best option is often to just -re-configure the client to use "http", but if that's not open to you then you can ask Spring to configure -an HTTP client that ignores SSL validation errors (just for tests). +WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that's not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course). -To make this work with minimum fuss you need to be using the Spring Boot `RestTemplateBuilder` in your app, -e.g. +To make this work with minimum fuss, you need to be using the Spring Boot +`RestTemplateBuilder` in your app, as shown in the following example: [source,java,indent=0] ---- @@ -982,10 +1079,11 @@ e.g. } ---- -This is because the builder is passed through callbacks to initalize it, so the SSL validation can be set up -in the client at that point. This will happen automatically in your test if you are using the -`@AutoConfigureWireMock` annotation (or the stub runner). If you are using the JUnit `@Rule` approach you need -to add the `@AutoConfigureHttpClient` annotation as well: +You need `RestTemplateBuilder` because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the `@AutoConfigureWireMock` +annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the +`@AutoConfigureHttpClient` annotation as well, as shown in the following example: [source,java,indent=0] ---- @@ -1001,15 +1099,16 @@ public class WiremockHttpsServerApplicationTests { } ---- -If you are using `spring-boot-starter-test` then you will have the Apache HTTP client on the classpath and it will -be selected by the `RestTemplateBuilder` and configured to ignore SSL errors. If you are using the default `java.net` -client you don't need the annotation (but it won't do any harm). There is no support currently for other clients, but -it may be added in future releases. +If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the +classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL +errors. If you use the default `java.net` client, you do not need the annotation (but it +won't do any harm). There is no support currently for other clients, but it may be added +in future releases. === WireMock and Spring MVC Mocks -Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a -Spring `MockRestServiceServer`. Here's an example: +Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring `MockRestServiceServer`. The following code shows an example: [source,java,indent=0] ---- @@ -1036,33 +1135,29 @@ public class WiremockForDocsMockServerApplicationTests { } ---- -The `baseUrl` is prepended to all mock calls, and the `stubs()` -method takes a stub path resource pattern as an argument. So in this -example the stub defined at `/stubs/resource.json` is loaded into the -mock server, so if the `RestTemplate` is asked to visit -`http://example.org/` it will get the responses as declared -there. More than one stub pattern can be specified, and each one can -be a directory (for a recursive list of all ".json"), or a fixed -filename (like in the example above) or an ant-style pattern. The JSON -format is the normal WireMock format which you can read about in the -WireMock website. +The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to +visit `http://example.org/`, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +http://wiremock.org/docs/stubbing/[WireMock website]. -Currently we support Tomcat, Jetty and Undertow as Spring Boot -embedded servers, and Wiremock itself has "native" support for a -particular version of Jetty (currently 9.2). To use the native Jetty -you need to add the native wiremock dependencies and exclude the -Spring Boot container if there is one. +Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one). -=== Generating Stubs using RestDocs - -https://projects.spring.io/spring-restdocs[Spring RestDocs] can be -used to generate documentation (e.g. in asciidoctor format) for an -HTTP API with Spring MockMvc or Rest Assured. At the same time as you -generate documentation for your API, you can also generate WireMock -stubs, by using Spring Cloud Contract WireMock. Just write your normal -RestDocs test cases and use `@AutoConfigureRestDocs` to have stubs -automatically in the restdocs output directory. For example: +=== Generating Stubs using REST Docs +https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc or +Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example: [source,java,indent=0] ---- @@ -1084,20 +1179,19 @@ public class ApplicationTests { } ---- -From this test will be generated a WireMock stub at -"target/snippets/stubs/resource.json". It matches all GET requests to -the "/resource" path. +This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. -Without any additional configuration this will create a stub with a -request matcher for the HTTP method and all headers except "host" and -"content-length". To match the request more precisely, for example to -match the body of a POST or PUT, we need to explicitly create a -request matcher. This will do two things: 1) create a stub that only -matches the way you specify, 2) assert that the request in the test -case also matches the same conditions. +Without any additional configuration, this tests creates a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects: -The main entry point for this is `WireMockRestDocs.verify()` which can -be used as a substitute for the `document()` convenience method. For +* Creating a stub that matches only in the way you specify. +* Asserting that the request in the test case also matches the same conditions. + +The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used +as a substitute for the `document()` convenience method, as shown in the following example: [source,java,indent=0] @@ -1122,15 +1216,14 @@ public class ApplicationTests { } ---- -So this contract is saying: any valid POST with an "id" field will get -back an the same response as in this test. You can chain together -calls to `.jsonPath()` to add additional matchers. The -https://github.com/jayway/JsonPath[JayWay documentation] can help you -to get up to speed with JSON Path if it is unfamiliar to you. +This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to `.jsonPath()` to add additional +matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay +documentation] can help you get up to speed. -Instead of the `jsonPath` and `contentType` convenience methods, you -can also use the WireMock APIs to verify the request matches the -created stub. Example: +Instead of the `jsonPath` and `contentType` convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example: [source,java,indent=0] ---- @@ -1147,10 +1240,9 @@ created stub. Example: } ---- -The WireMock API is rich - you can match headers, query parameters, -and request body by regex as well as by json path - so this can useful -to create stubs with a wider range of parameters. The above example -will generate a stub something like this: +The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example: .post-resource.json [source,json] @@ -1174,32 +1266,33 @@ will generate a stub something like this: } ---- -NOTE: You can use either the `wiremock()` method or the `jsonPath()` -and `contentType()` methods to create request matchers, but not both. +NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` +methods to create request matchers, but you can't use both approaches. -On the consumer side, you can make the `resource.json` generated above -available on the classpath (by https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing stubs as JARs] for example). -After that, you can create a stub using WireMock in a -number of different ways, including as described above using -`@AutoConfigureWireMock(stubs="classpath:resource.json")`. +On the consumer side, you can make the `resource.json` generated earlier in this section +available on the classpath (by +https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing +stubs as JARs], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +`@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this +document. -=== Generating Contracts using RestDocs +=== Generating Contracts by Using REST Docs -Another thing that can be generated with Spring RestDocs is the Spring Cloud -Contract DSL file and documentation. If you combine that with Spring Cloud -WireMock then you're getting both the contracts and stubs. +You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs. Why would you want to use this feature? Some people in the community asked questions -about situation in which they would like to move to DSL based contract definition -but they already have a lot of Spring MVC tests. Using this feature allows you to generate -the contract files that you can later modify and move to proper folders so that the -plugin picks them up. +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them. -TIP: You might wonder why this functionality is in the WireMock module. -Come to think of it, it does make sense since it makes little sense to generate -only contracts and not generate the stubs. That's why we suggest to do both. +TIP: You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. -Let's imagine the following test: +Consider the following test: [source,java] ---- @@ -1219,10 +1312,10 @@ Let's imagine the following test: .andDo(document("index", SpringCloudContractRestDocs.dslContract())); ---- -This will lead in the creation of the stub as presented in the previous -section, contract will get generated and a documentation file too. +The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file. -The contract will be called `index.groovy` and look more like this. +The contract is called `index.groovy` and might look like the following example: [source,groovy] ---- @@ -1256,12 +1349,13 @@ Contract.make { } ---- -the generated document (example for Asciidoc) will contain a formatted contract -(the location of this file would be `index/dsl-contract.adoc`). +The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be `index/dsl-contract.adoc`. == Documentation -You can read more about Spring Cloud Contract Verifier by reading the {documentation_url}[docs] +You can read more about Spring Cloud Contract Verifier by reading the +{documentation_url}[docs] == Contributing diff --git a/docs/src/main/asciidoc/README.adoc b/docs/src/main/asciidoc/README.adoc index b61e6e9850..c091616c79 100644 --- a/docs/src/main/asciidoc/README.adoc +++ b/docs/src/main/asciidoc/README.adoc @@ -6,14 +6,16 @@ image::https://circleci.com/gh/spring-cloud/spring-cloud-contract.svg?style=svg[ == Spring Cloud Contract -What you always need is confidence in pushing new features into a new application or service in a distributed system. -This project provides support for Consumer Driven Contracts and service schemas in Spring applications, covering a -range of options for writing tests, publishing them as assets, asserting that a contract is kept by producers -and consumers, for HTTP and message-based interactions. +You always need confidence when pushing new features into a new application or service in +a distributed system. To that end, this project provides support for Consumer-driven +Contracts and service schemas in Spring applications, covering a range of options for +writing tests, publishing them as assets, and asserting that a contract is kept by +producers and consumers -- for both HTTP and message-based interactions. === Spring Cloud Contract workshops -If you prefer to learn about the project by doing some tutorials you can check out the workshops under +If you prefer to learn about the project by doing some tutorials, you can check out the +workshops under http://cloud-samples.spring.io/spring-cloud-contract-samples/workshops.html[this link]. === Spring Cloud Contract Verifier @@ -28,7 +30,8 @@ include::spring-cloud-wiremock.adoc[] == Documentation -You can read more about Spring Cloud Contract Verifier by reading the {documentation_url}[docs] +You can read more about Spring Cloud Contract Verifier by reading the +{documentation_url}[docs] == Contributing diff --git a/docs/src/main/asciidoc/links.adoc b/docs/src/main/asciidoc/links.adoc index 29164aedfc..35a5f9dcfe 100644 --- a/docs/src/main/asciidoc/links.adoc +++ b/docs/src/main/asciidoc/links.adoc @@ -1,13 +1,21 @@ == Links -Here you can find interesting links related to Spring Cloud Contract Verifier: +The following links may be helpful when working with Spring Cloud Contract Verifier: -- https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github Repository] -- https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud Contract Samples] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud Contract Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest Legacy Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring Cloud Contract Stub Runner Documentation] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring Cloud Contract Stub Runner Messaging Documentation] -- https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] -- https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin] -- https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by Marcin Grzejszczak] +* https://github.com/spring-cloud/spring-cloud-contract/[Spring Cloud Contract Github +Repository] +* https://github.com/spring-cloud-samples/spring-cloud-contract-samples/[Spring Cloud +Contract Samples] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html[Spring Cloud +Contract Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/deprecated[Accurest +Legacy Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#spring-cloud-contract-stub-runner[Spring +Cloud Contract Stub Runner Documentation] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[Spring +Cloud Contract Stub Runner Messaging Documentation] +* https://gitter.im/spring-cloud/spring-cloud-contract[Spring Cloud Contract Gitter] +* https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring +Cloud Contract Maven Plugin] +* https://www.youtube.com/watch?v=sAAklvxmPmk[Spring Cloud Contract WJUG Presentation by +Marcin Grzejszczak] diff --git a/docs/src/main/asciidoc/migrations.adoc b/docs/src/main/asciidoc/migrations.adoc index e3643eca69..d6c77f812a 100644 --- a/docs/src/main/asciidoc/migrations.adoc +++ b/docs/src/main/asciidoc/migrations.adoc @@ -4,33 +4,38 @@ == Migrations -In the following document we will write about necessary migration steps between versions. +This section covers migrating from one version of Spring Cloud Contract Verifier to the +next version. It covers the following versions upgrade paths: +[[cloud-verifier-1.0-1.1]] === 1.0.x -> 1.1.x +This section covers upgrading from version 1.0 to version 1.1. + ==== New structure of generated stubs -In `1.1.x` we have introduced a changed structure of generated stubs. So if you've -been using the following `@AutoConfigureWireMock` notation to use the stubs from classpath +In `1.1.x` we have introduced a change to the structure of generated stubs. If you have +been using the `@AutoConfigureWireMock` notation to use the stubs from the classpath, +it no longer works. The following example shows how the `@AutoConfigureWireMock` notation +used to work: [source,java] ---- @AutoConfigureWireMock(stubs = "classpath:/customer-stubs/mappings", port = 8084) ---- -It will no longer work with the new stubs. You have to either change the location of stubs -to : `classpath:.../META-INF/groupId/artifactId/version/mappings` as follows +You must either change the location of the stubs to: +`classpath:.../META-INF/groupId/artifactId/version/mappings` or use the new +classpath-based `@AutoConfigureStubRunner`, as shown in the following example: [source,java] ---- @AutoConfigureWireMock(stubs = "classpath:customer-stubs/META-INF/travel.components/customer-contract/1.0.2-SNAPSHOT/mappings/", port = 8084) ---- -Or migrate to the new classpath based `@AutoConfigureStubRunner`. - -If however you don't want to do that and you want to remain with the old structure -just set your plugin tasks accordingly. Example for the structure presented in the -snippet above. +If you do not want to use `@AutoConfigureStubRunner` and you want to remain with the old +structure, set your plugin tasks accordingly. The following example would work for the +structure presented in the previous snippet. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -111,36 +116,64 @@ task copyStubs(type: Copy, dependsOn: 'generateWireMockClientStubs') { } ---- +[[cloud-verifier-1.1-1.2]] === 1.1.x -> 1.2.x +This section covers upgrading from version 1.1 to version 1.2. + ==== Custom `HttpServerStub` -By introducing a method `String registeredMappings()` in the public interface -`HttpServerStub`, if you wrote a custom `HttpServerStub` implementation, you'll -have to implement that method too. It should return a `String` representing -all mappings available in a single `HttpServerStub`. Related to -https://github.com/spring-cloud/spring-cloud-contract/issues/355[issue 355]. +`HttpServerStub` includes a method that was not in version 1.1. The method is +`String registeredMappings()` If you have classes that implement `HttpServerStub`, you +now have to implement the `registeredMappings()` method. It should return a `String` +representing all mappings available in a single `HttpServerStub`. + +See https://github.com/spring-cloud/spring-cloud-contract/issues/355[issue 355] for more +detail. ==== New packages for generated tests The flow for setting the generated tests package name will look like this: -- pick `basePackageForTests` -- if `basePackageForTests` wasn't set pick the package from `baseClassForTests` -- if `baseClassForTests` wasn't set pick `packageWithBaseClasses` -- if nothing got set pick the default `org.springframework.cloud.contract.verifier.tests` value +* Set `basePackageForTests` +* If `basePackageForTests` was not set, pick the package from `baseClassForTests` +* If `baseClassForTests` was not set, pick `packageWithBaseClasses` +* If nothing got set, pick the default value: +`org.springframework.cloud.contract.verifier.tests` -Related to -https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260]. +See https://github.com/spring-cloud/spring-cloud-contract/issues/260[issue 260] for more +detail. -==== New methods in TemplateProcessor +==== New Methods in TemplateProcessor -In order to add support for `fromRequest.path` some methods had to be added to the -`TemplateProcessor` interface. +In order to add support for `fromRequest.path`, the following methods had to be added to the +`TemplateProcessor` interface: -Related to -https://github.com/spring-cloud/spring-cloud-contract/issues/388[issue 388]. +* `path()` +* `path(int index)` +See https://github.com/spring-cloud/spring-cloud-contract/issues/388[issue 388] for more +detail. + +==== RestAssured 3.0 + +Rest Assured, used in the generated test classes, got bumped to `3.0`. If +you manually set versions of Spring Cloud Contract and the release train +you might see the following exception: + +[source,bash] +---- +Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project some-project: Compilation failure: Compilation failure: +[ERROR] /some/path/SomeClass.java:[4,39] package com.jayway.restassured.response does not exist +---- + +This exception will occur due to the fact that the tests got generated with +an old version of plugin and at test execution time you have an incompatible +version of the release train (and vice versa). + +Done via https://github.com/spring-cloud/spring-cloud-contract/issues/267[issue 267] + +[[cloud-verifier-1.2-2.0]] === 1.2.x -> 2.0.x ==== No Camel support diff --git a/docs/src/main/asciidoc/spring-cloud-contract.adoc b/docs/src/main/asciidoc/spring-cloud-contract.adoc index 207b11f766..e104c768b3 100644 --- a/docs/src/main/asciidoc/spring-cloud-contract.adoc +++ b/docs/src/main/asciidoc/spring-cloud-contract.adoc @@ -10,16 +10,17 @@ = Spring Cloud Contract _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_ +Olga Maciaszek-Sharma, Mariusz Smykuła, Dave Syer_, Jay Bryant {spring-cloud-version} == Spring Cloud Contract -What you always need is confidence in pushing new features into a new application or service in a distributed system. -This project provides support for Consumer Driven Contracts and service schemas in Spring applications, covering a -range of options for writing tests, publishing them as assets, asserting that a contract is kept by producers -and consumers, for HTTP and message-based interactions. +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), +covering a range of options for writing tests, publishing them as assets, and asserting +that a contract is kept by producers and consumers. include::spring-cloud-contract-verifier.adoc[] @@ -27,4 +28,4 @@ include::spring-cloud-wiremock.adoc[] include::migrations.adoc[] -include::links.adoc[] \ No newline at end of file +include::links.adoc[] diff --git a/docs/src/main/asciidoc/spring-cloud-wiremock.adoc b/docs/src/main/asciidoc/spring-cloud-wiremock.adoc index fea6ec6602..39c100b9c9 100644 --- a/docs/src/main/asciidoc/spring-cloud-wiremock.adoc +++ b/docs/src/main/asciidoc/spring-cloud-wiremock.adoc @@ -4,18 +4,17 @@ == Spring Cloud Contract WireMock -Modules giving you the possibility to use -http://wiremock.org[WireMock] in a Spring Boot application. Check out the +The Spring Cloud Contract WireMock modules let you use http://wiremock.org[WireMock] in a +Spring Boot application. Check out the https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples[samples] for more details. -If you have a Spring Boot application that uses Tomcat as an embedded -server, for example (the default with `spring-boot-starter-web`), then -you can simply add `spring-cloud-contract-wiremock` to your classpath -and add `@AutoConfigureWireMock` in order to be able to use Wiremock -in your tests. Wiremock runs as a stub server and you can register -stub behaviour using a Java API or via static JSON declarations as -part of your test. Here's a simple example: +If you have a Spring Boot application that uses Tomcat as an embedded server (which is +the default with `spring-boot-starter-web`), you can add +`spring-cloud-contract-wiremock` to your classpath and add `@AutoConfigureWireMock` in +order to be able to use Wiremock in your tests. Wiremock runs as a stub server and you +can register stub behavior using a Java API or via static JSON declarations as part of +your test. The following code shows an example: [source,java,indent=0] ---- @@ -23,16 +22,20 @@ include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags= include::{doc_samples}/src/test/java/com/example/WiremockForDocsTests.java[tags=wiremock_test2] ---- -To start the stub server on a different port use `@AutoConfigureWireMock(port=9999)` (for example), and for a random port use the value 0. The stub server port will be bindable in the test application context as "wiremock.server.port". Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to your test application context, where it will be cached in between methods and classes having the same context, just like for normal Spring integration tests. +To start the stub server on a different port use (for example), +`@AutoConfigureWireMock(port=9999)`. For a random port, use a value of `0`. The stub +server port can be bound in the test application context with the "wiremock.server.port" +property. Using `@AutoConfigureWireMock` adds a bean of type `WiremockConfiguration` to +your test application context, where it will be cached in between methods and classes +having the same context, the same as for Spring integration tests. === Registering Stubs Automatically -If you use `@AutoConfigureWireMock` then it will register WireMock -JSON stubs from the file system or classpath, by default from -`file:src/test/resources/mappings`. You can customize the locations -using the `stubs` attribute in the annotation, which can be a resource -pattern (ant-style) or a directory, in which case `**/*.json` is -appended. Example: +If you use `@AutoConfigureWireMock`, it registers WireMock JSON stubs from the file +system or classpath (by default, from `file:src/test/resources/mappings`). You can +customize the locations using the `stubs` attribute in the annotation, which can be an +Ant-style resource pattern or a directory. In the case of a directory, `**/*.json` is +appended. The following code shows an example: ---- @RunWith(SpringRunner.class) @@ -51,35 +54,32 @@ public class WiremockImportApplicationTests { } ---- -NOTE: Actually WireMock always loads mappings from -`src/test/resources/mappings` *as well as* the custom locations in the -stubs attribute. To change this behaviour you have to also specify a -files root as described next. +NOTE: Actually, WireMock always loads mappings from `src/test/resources/mappings` *as +well as* the custom locations in the stubs attribute. To change this behavior, you can +also specify a files root as described in the next section of this document. === Using Files to Specify the Stub Bodies -WireMock can read response bodies from files on the classpath or file -system. In that case you will see in the JSON DSL that the response -has a "bodyFileName" instead of a (literal) "body". The files are -resolved relative to a root directory `src/test/resources/\__files` by -default. To customize this location you can set the `files` attribute -in the `@AutoConfigureWireMock` annotation to the location of the -parent directory (i.e. the place `__files` is a -subdirectory). You can use Spring resource notation to refer to -`file:...` or `classpath:...` locations (but generic URLs are not -supported). A list of values can be given and WireMock will resolve -the first file that exists when it needs to find a response body. +WireMock can read response bodies from files on the classpath or the file system. In that +case, you can see in the JSON DSL that the response has a `bodyFileName` instead of a +(literal) `body`. The files are resolved relative to a root directory (by default, +`src/test/resources/\__files`). To customize this location you can set the `files` +attribute in the `@AutoConfigureWireMock` annotation to the location of the parent +directory (in other words, `__files` is a subdirectory). You can use Spring resource +notation to refer to `file:...` or `classpath:...` locations. Generic URLs are not +supported. A list of values can be given, in which case WireMock resolves the first file +that exists when it needs to find a response body. -NOTE: when you configure the `files` root, then it affects the -automatic loading of stubs as well (they come from the root location -in a subdirectory called "mappings"). The value of `files` has no +NOTE: When you configure the `files` root, it also affects the +automatic loading of stubs, because they come from the root location +in a subdirectory called "mappings". The value of `files` has no effect on the stubs loaded explicitly from the `stubs` attribute. === Alternative: Using JUnit Rules -For a more conventional WireMock experience, using JUnit `@Rules` to -start and stop the server, just use the `WireMockSpring` convenience -class to obtain an `Options` instance: +For a more conventional WireMock experience, you can use JUnit `@Rules` to start and stop +the server. To do so, use the `WireMockSpring` convenience class to obtain an `Options` +instance, as shown in the followin example: [source,java,indent=0] ---- @@ -87,18 +87,20 @@ include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.j include::{doc_samples}/src/test/java/com/example/WiremockForDocsClassRuleTests.java[tags=wiremock_test2] ---- -The use `@ClassRule` means that the server will shut down after all the methods in this class. +The `@ClassRule` means that the server shuts down after all the methods in this class +have been run. === Relaxed SSL Validation for Rest Template -WireMock allows you to stub a "secure" server with an "https" URL protocol. If your application wants to -contact that stub server in an integration test, then it will find that the SSL certificates are not -valid (it's the usual problem with self-installed certificates). The best option is often to just -re-configure the client to use "http", but if that's not open to you then you can ask Spring to configure -an HTTP client that ignores SSL validation errors (just for tests). +WireMock lets you stub a "secure" server with an "https" URL protocol. If your +application wants to contact that stub server in an integration test, it will find that +the SSL certificates are not valid (the usual problem with self-installed certificates). +The best option is often to re-configure the client to use "http". If that's not an +option, you can ask Spring to configure an HTTP client that ignores SSL validation errors +(do so only for tests, of course). -To make this work with minimum fuss you need to be using the Spring Boot `RestTemplateBuilder` in your app, -e.g. +To make this work with minimum fuss, you need to be using the Spring Boot +`RestTemplateBuilder` in your app, as shown in the following example: [source,java,indent=0] ---- @@ -108,10 +110,11 @@ e.g. } ---- -This is because the builder is passed through callbacks to initalize it, so the SSL validation can be set up -in the client at that point. This will happen automatically in your test if you are using the -`@AutoConfigureWireMock` annotation (or the stub runner). If you are using the JUnit `@Rule` approach you need -to add the `@AutoConfigureHttpClient` annotation as well: +You need `RestTemplateBuilder` because the builder is passed through callbacks to +initialize it, so the SSL validation can be set up in the client at that point. This +happens automatically in your test if you are using the `@AutoConfigureWireMock` +annotation or the stub runner. If you use the JUnit `@Rule` approach, you need to add the +`@AutoConfigureHttpClient` annotation as well, as shown in the following example: [source,java,indent=0] ---- @@ -127,48 +130,45 @@ public class WiremockHttpsServerApplicationTests { } ---- -If you are using `spring-boot-starter-test` then you will have the Apache HTTP client on the classpath and it will -be selected by the `RestTemplateBuilder` and configured to ignore SSL errors. If you are using the default `java.net` -client you don't need the annotation (but it won't do any harm). There is no support currently for other clients, but -it may be added in future releases. +If you are using `spring-boot-starter-test`, you have the Apache HTTP client on the +classpath and it is selected by the `RestTemplateBuilder` and configured to ignore SSL +errors. If you use the default `java.net` client, you do not need the annotation (but it +won't do any harm). There is no support currently for other clients, but it may be added +in future releases. === WireMock and Spring MVC Mocks -Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into a -Spring `MockRestServiceServer`. Here's an example: +Spring Cloud Contract provides a convenience class that can load JSON WireMock stubs into +a Spring `MockRestServiceServer`. The following code shows an example: [source,java,indent=0] ---- include::{doc_samples}/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java[tags=wiremock_test] ---- -The `baseUrl` is prepended to all mock calls, and the `stubs()` -method takes a stub path resource pattern as an argument. So in this -example the stub defined at `/stubs/resource.json` is loaded into the -mock server, so if the `RestTemplate` is asked to visit -`http://example.org/` it will get the responses as declared -there. More than one stub pattern can be specified, and each one can -be a directory (for a recursive list of all ".json"), or a fixed -filename (like in the example above) or an ant-style pattern. The JSON -format is the normal WireMock format which you can read about in the -WireMock website. +The `baseUrl` value is prepended to all mock calls, and the `stubs()` method takes a stub +path resource pattern as an argument. In the preceding example, the stub defined at +`/stubs/resource.json` is loaded into the mock server. If the `RestTemplate` is asked to +visit `http://example.org/`, it gets the responses as being declared at that URL. More +than one stub pattern can be specified, and each one can be a directory (for a recursive +list of all ".json"), a fixed filename (as in the example above), or an Ant-style +pattern. The JSON format is the normal WireMock format, which you can read about in the +http://wiremock.org/docs/stubbing/[WireMock website]. -Currently we support Tomcat, Jetty and Undertow as Spring Boot -embedded servers, and Wiremock itself has "native" support for a -particular version of Jetty (currently 9.2). To use the native Jetty -you need to add the native wiremock dependencies and exclude the -Spring Boot container if there is one. +Currently, the Spring Cloud Contract Verifier supports Tomcat, Jetty, and Undertow as +Spring Boot embedded servers, and Wiremock itself has "native" support for a particular +version of Jetty (currently 9.2). To use the native Jetty, you need to add the native +Wiremock dependencies and exclude the Spring Boot container (if there is one). -=== Generating Stubs using RestDocs - -https://projects.spring.io/spring-restdocs[Spring RestDocs] can be -used to generate documentation (e.g. in asciidoctor format) for an -HTTP API with Spring MockMvc or Rest Assured. At the same time as you -generate documentation for your API, you can also generate WireMock -stubs, by using Spring Cloud Contract WireMock. Just write your normal -RestDocs test cases and use `@AutoConfigureRestDocs` to have stubs -automatically in the restdocs output directory. For example: +=== Generating Stubs using REST Docs +https://projects.spring.io/spring-restdocs[Spring REST Docs] can be used to generate +documentation (for example in Asciidoctor format) for an HTTP API with Spring MockMvc or +Rest Assured. At the same time that you generate documentation for your API, you can also +generate WireMock stubs by using Spring Cloud Contract WireMock. To do so, write your +normal REST Docs test cases and use `@AutoConfigureRestDocs` to have stubs be +automatically generated in the REST Docs output directory. The following code shows an +example: [source,java,indent=0] ---- @@ -190,20 +190,19 @@ public class ApplicationTests { } ---- -From this test will be generated a WireMock stub at -"target/snippets/stubs/resource.json". It matches all GET requests to -the "/resource" path. +This test generates a WireMock stub at "target/snippets/stubs/resource.json". It matches +all GET requests to the "/resource" path. -Without any additional configuration this will create a stub with a -request matcher for the HTTP method and all headers except "host" and -"content-length". To match the request more precisely, for example to -match the body of a POST or PUT, we need to explicitly create a -request matcher. This will do two things: 1) create a stub that only -matches the way you specify, 2) assert that the request in the test -case also matches the same conditions. +Without any additional configuration, this tests creates a stub with a request matcher +for the HTTP method and all headers except "host" and "content-length". To match the +request more precisely (for example, to match the body of a POST or PUT), we need to +explicitly create a request matcher. Doing so has two effects: -The main entry point for this is `WireMockRestDocs.verify()` which can -be used as a substitute for the `document()` convenience method. For +* Creating a stub that matches only in the way you specify. +* Asserting that the request in the test case also matches the same conditions. + +The main entry point for this feature is `WireMockRestDocs.verify()`, which can be used +as a substitute for the `document()` convenience method, as shown in the following example: [source,java,indent=0] @@ -228,15 +227,14 @@ public class ApplicationTests { } ---- -So this contract is saying: any valid POST with an "id" field will get -back an the same response as in this test. You can chain together -calls to `.jsonPath()` to add additional matchers. The -https://github.com/jayway/JsonPath[JayWay documentation] can help you -to get up to speed with JSON Path if it is unfamiliar to you. +This contract specifies that any valid POST with an "id" field receives the response +defined in this test. You can chain together calls to `.jsonPath()` to add additional +matchers. If JSON Path is unfamiliar, The https://github.com/jayway/JsonPath[JayWay +documentation] can help you get up to speed. -Instead of the `jsonPath` and `contentType` convenience methods, you -can also use the WireMock APIs to verify the request matches the -created stub. Example: +Instead of the `jsonPath` and `contentType` convenience methods, you can also use the +WireMock APIs to verify that the request matches the created stub, as shown in the +following example: [source,java,indent=0] ---- @@ -253,10 +251,9 @@ created stub. Example: } ---- -The WireMock API is rich - you can match headers, query parameters, -and request body by regex as well as by json path - so this can useful -to create stubs with a wider range of parameters. The above example -will generate a stub something like this: +The WireMock API is rich. You can match headers, query parameters, and request body by +regex as well as by JSON path. These features can be used to create stubs with a wider +range of parameters. The above example generates a stub resembling the following example: .post-resource.json [source,json] @@ -280,42 +277,43 @@ will generate a stub something like this: } ---- -NOTE: You can use either the `wiremock()` method or the `jsonPath()` -and `contentType()` methods to create request matchers, but not both. +NOTE: You can use either the `wiremock()` method or the `jsonPath()` and `contentType()` +methods to create request matchers, but you can't use both approaches. -On the consumer side, you can make the `resource.json` generated above -available on the classpath (by https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing stubs as JARs] for example). -After that, you can create a stub using WireMock in a -number of different ways, including as described above using -`@AutoConfigureWireMock(stubs="classpath:resource.json")`. +On the consumer side, you can make the `resource.json` generated earlier in this section +available on the classpath (by +https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_publishing_stubs_as_jars[publishing +stubs as JARs], for example). After that, you can create a stub using WireMock in a +number of different ways, including by using +`@AutoConfigureWireMock(stubs="classpath:resource.json")`, as described earlier in this +document. -=== Generating Contracts using RestDocs +=== Generating Contracts by Using REST Docs -Another thing that can be generated with Spring RestDocs is the Spring Cloud -Contract DSL file and documentation. If you combine that with Spring Cloud -WireMock then you're getting both the contracts and stubs. +You can also generate Spring Cloud Contract DSL files and documentation with Spring REST +Docs. If you do so in combination with Spring Cloud WireMock, you get both the contracts +and the stubs. Why would you want to use this feature? Some people in the community asked questions -about situation in which they would like to move to DSL based contract definition -but they already have a lot of Spring MVC tests. Using this feature allows you to generate -the contract files that you can later modify and move to proper folders so that the -plugin picks them up. +about a situation in which they would like to move to DSL-based contract definition, +but they already have a lot of Spring MVC tests. Using this feature lets you generate +the contract files that you can later modify and move to folders (defined in your +configuration) so that the plugin finds them. -TIP: You might wonder why this functionality is in the WireMock module. -Come to think of it, it does make sense since it makes little sense to generate -only contracts and not generate the stubs. That's why we suggest to do both. +TIP: You might wonder why this functionality is in the WireMock module. The functionality +is there because it makes sense to generate both the contracts and the stubs. -Let's imagine the following test: +Consider the following test: [source,java] ---- include::{wiremock_tests}/src/test/java/org/springframework/cloud/contract/wiremock/restdocs/ContractDslSnippetTests.java[tags=contract_snippet] ---- -This will lead in the creation of the stub as presented in the previous -section, contract will get generated and a documentation file too. +The preceding test creates the stub presented in the previous section, generating both +the contract and a documentation file. -The contract will be called `index.groovy` and look more like this. +The contract is called `index.groovy` and might look like the following example: [source,groovy] ---- @@ -349,5 +347,5 @@ Contract.make { } ---- -the generated document (example for Asciidoc) will contain a formatted contract -(the location of this file would be `index/dsl-contract.adoc`). +The generated document (formatted in Asciidoc in this case) contains a formatted +contract. The location of this file would be `index/dsl-contract.adoc`. diff --git a/docs/src/main/asciidoc/verifier_contract.adoc b/docs/src/main/asciidoc/verifier_contract.adoc index 5816ede6d6..efaff3b145 100644 --- a/docs/src/main/asciidoc/verifier_contract.adoc +++ b/docs/src/main/asciidoc/verifier_contract.adoc @@ -1,76 +1,99 @@ == Contract DSL -IMPORTANT: Remember that inside the contract file you have to provide the fully qualified name to -the `Contract` class and the `make` static import i.e. `org.springframework.cloud.spec.Contract.make { ... }`. -You can also provide an import to the `Contract` class `import org.springframework.cloud.spec.Contract` and then call - `Contract.make { ... }` +IMPORTANT: Remember that, inside the contract file, you have to provide the fully +qualified name to the `Contract` class and `make` static imports, such as +`org.springframework.cloud.spec.Contract.make { ... }`. You can also provide an import to +the `Contract` class: `import org.springframework.cloud.spec.Contract` and then call +`Contract.make { ... }`. -Contract DSL is written in Groovy, but don't be alarmed if you didn't use Groovy before. Knowledge of the language is not really needed as our DSL uses only -a tiny subset of it (namely literals, method calls and closures). What's more the DSL is designed to be programmer-readable without any knowledge of the DSL itself - - it's statically typed. +Contract DSL is written in Groovy, but do not be alarmed if you have not used Groovy +before. Knowledge of the language is not really needed, as the Contract DSL uses only a +tiny subset of it (only literals, method calls and closures). Also, the DSL is statically +typed, to make it programmer-readable without any knowledge of the DSL itself. -TIP: Spring Cloud Contract supports defining multiple contracts in a single file! +TIP: Spring Cloud Contract supports defining multiple contracts in a single file. -The Contract is present in the `spring-cloud-contract-spec` module of the Spring Cloud Contract Verifier repository. +The Contract is present in the `spring-cloud-contract-spec` module of the +https://github.com/spring-cloud/spring-cloud-contract/tree/master/spring-cloud-contract-verifier[Spring +Cloud Contract Verifier repository]. -Let's look at full example of a contract definition. +The following is a complete example of a contract definition: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=dsl_example,indent=0] ---- -Not all features of the DSL are used in example above. If you didn't find what you are looking for, please check next paragraphs on this page. +NOTE: The preceding example does not contain all the features of the DSL appear. The +remainder of this section describes the other features. -> You can easily compile Contracts to WireMock stubs mapping using standalone maven command: `mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert`. +You can compile Contracts to WireMock stubs mapping using standalone maven command: +`mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert` === Limitations -WARNING: Spring Cloud Contract Verifier doesn't support XML properly. Please use JSON or help us implement this feature. +WARNING: Spring Cloud Contract Verifier does not properly support XML. Please use JSON or +help us implement this feature. -WARNING: The support for the verification of size of JSON arrays is experimental. If you want to turn it on please provide -the value of a system property `spring.cloud.contract.verifier.assert.size` equal to `true`. By default this feature is set to -`false`. You can also provide the `assertJsonSize` property in the plugin configuration. +WARNING: The support for verifying the size of JSON arrays is experimental. If you want +to turn it on, please set the value of the following system property to `true`: +`spring.cloud.contract.verifier.assert.size`. By default, this feature is set to `false`. +You can also provide the `assertJsonSize` property in the plugin configuration. -WARNING: Due to the fact that JSON structure can have any form it's sometimes impossible to parse it properly when using -the `value(consumer(...), producer(...))` notation when using that in GString. That's why we highly recommend using the -Groovy Map notation. +WARNING: Because JSON structure can have any form, it can be impossible to parse it +properly when using the `value(consumer(...), producer(...))` notation in `GString`. That +is why you should use the Groovy Map notation. === Common Top-Level elements +The following sections describe the most common top-level elements: + +* <> +* <> +* <> +* <> +* <> + +[[contract-dsl-description]] ==== Description -You can add a `description` to your contract that is nothing else but an arbitrary text. Example: +You can add a `description` to your contract. The description is arbitrary text. The +following code shows an example: [source,groovy,indent=0] ---- include::{contract_spec_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=description,indent=0] ---- +[[contract-dsl-name]] ==== Name -You can provide a name of your contract. Let's assume that you've provided a name `should register a user`. -If you do this then the name of the autogenerated test will be equal to `validate_should_register_a_user`. -Also the name of the stub will be `should_register_a_user.json` in case of a WireMock stub. +You can provide a name for your contract. Assume that you provided the following name: +`should register a user`. If you do so, the name of the autogenerated test is +`validate_should_register_a_user`. Also, the name of the stub in a WireMock stub is +`should_register_a_user.json`. -IMPORTANT: Please ensure that the name doesn't contain any characters that will make the generated test - not possible to compile. Also remember that if you provide the same name for multiple contracts then your - autogenerated tests will fail to compile and your generated stubs will override each other. +IMPORTANT: You must ensure that the name does not contain any characters that make the +generated test not compile. Also, remember that, if you provide the same name for +multiple contracts, your autogenerated tests fail to compile and your generated stubs +override each other. -==== Ignoring contracts +[[contract-dsl-ignoring-contracts]] +==== Ignoring Contracts -If you want to ignore a contract you can either set a value of ignored contracts in the plugin configuration -or just set the `ignored` property on the contract itself: +If you want to ignore a contract, you can either set a value of ignored contracts in the +plugin configuration or set the `ignored` property on the contract itself: [source,groovy,indent=0] ---- include::{contract_spec_path}/src/test/groovy/org/springframework/cloud/contract/spec/internal/ContractSpec.groovy[tags=ignored,indent=0] ---- -==== Passing values from files +[[contract-dsl-passing-values-from-files]] +==== Passing Values from Files -Starting with version `1.2.0` it's possible to pass values from files. Let's assume that we have -the following resources in our project. +Starting with version `1.2.0`, you can pass values from files. Assume that you have the +following resources in our project. [source,bash,indent=0] ---- @@ -83,14 +106,14 @@ the following resources in our project.     └── response.json ---- -And our contract looks like this: +Further assume that your contract is as follows: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/resources/classpath/readFromFile.groovy[indent=0] ---- -and the json files look like this: +Further assume that the JSON files is as follows: *request.json* [source,json,indent=0] @@ -104,14 +127,16 @@ include::{verifier_core_path}/src/test/resources/classpath/request.json[indent=0 include::{verifier_core_path}/src/test/resources/classpath/response.json[indent=0] ---- -When test / stub generation takes place then the contents of the file will be -passed to the body of request / response. All thanks to the `file(...)` method. -The argument of that method needs to be a file with location relative to the -folder in which the contract lays. +When test or stub generation takes place, the contents of the file is passed to the body +of a request or a response. That works because of the `file(...)` method. The argument of +that method needs to be a file with location relative to the folder in which the contract +lays. +[[contract-dsl-http-top-level-elements]] ==== HTTP Top-Level Elements -Following methods can be called in the top-level closure of a contract definition. Request and response are mandatory, priority is optional. +The following methods can be called in the top-level closure of a contract definition. +`request` and `response` are mandatory. `priority` is optional. [source,groovy,indent=0] ---- @@ -120,14 +145,16 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract === Request -HTTP protocol requires only **method and address** to be specified in a request. The same information is mandatory in request definition of the Contract. +The HTTP protocol requires only **method and address** to be specified in a request. The +same information is mandatory in request definition of the Contract. [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=request,indent=0] ---- -It is possible to specify whole `url` instead of just path, but `urlPath` is the recommended way as it makes the tests **host-independent**. +It is possible to specify an absolute rather than relative `url`, but using `urlPath` is +the recommended way, as doing so makes the tests **host-independent**. [source,groovy,indent=0] ---- @@ -135,42 +162,46 @@ include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract ---- -Request may contain **query parameters**, which are specified in a closure nested in a call to `urlPath` or `url`. +`request` may contain **query parameters**, which are specified in a closure nested in a +call to `urlPath` or `url`. [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=urlpath,indent=0] ---- -It may contain additional **request headers**... +`request` may contain additional **request headers**, as shown in the following example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=headers,indent=0] ---- -...and a **request body**. +`request` may contain a **request body**, as shown in the following example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=body,indent=0] ---- -Request may contain **multipart** elements. Just call the `multipart()` method. +`request` may contain **multipart** elements. To include multipart elements, call the +`multipart()` method, as shown in the following example [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=multipartdsl,indent=0] ---- -In this example we defined parameters either directly by using the map notation, -where the value can be a dynamic property (e.g. `formParameter: $(consumer(...), producer(...))`) - or by using the `named(...)` method that allows you to set a named parameter. - A named parameter can set a `name` and `content`. You can call it either via - a method with 2 arguments: e.g. `named("fileName", "fileContent")` or - via a map notation `named(name: "fileName", content: "fileContent")`. +In the preceding example, we define parameters in either of two ways: -From this contract the generated test will look more or less like this: +* Directly, by using the map notation, where the value can be a dynamic property (such as +`formParameter: $(consumer(...), producer(...))`). +* By using the `named(...)` method that lets you set a named parameter. A named parameter +can set a `name` and `content`. You can call it either via a method with two arguments, +such as `named("fileName", "fileContent")`, or via a map notation, such as +`named(name: "fileName", content: "fileContent")`. + +From this contract, the generated test is as follows: [source,java,indent=0] ---- @@ -189,34 +220,40 @@ From this contract the generated test will look more or less like this: assertThat(response.statusCode()).isEqualTo(200); ---- -The WireMock stub will look more or less like this: +The WireMock stub is as follows: [source,json,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/dsl/WireMockGroovyDslSpec.groovy[tags=multipartwiremock,indent=0] ---- + === Response -Minimal response must contain **HTTP status code**. +The response must contain an **HTTP status code** and may contain other information. The +following code shows an example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=response,indent=0] ---- -Besides status response may contain **headers** and **body**, which are specified the same way as in the request (see previous paragraph). +Besides status, the response may contain **headers** and a **body**, both of which are +specified the same way as in the request (see the previous paragraph). === Dynamic properties -The contract can contain some dynamic properties - timestamps / ids etc. You don't want to enforce the consumers to stub their -clocks to always return the same value of time so that it gets matched by the stub. That's why we allow you to provide the dynamic -parts in your contracts in two ways. One is to pass them directly in the -body and one to set them in a separate section called `testMatchers` and `stubMatchers`. +The contract can contain some dynamic properties: timestamps, IDs, and so on. You do not +want to force the consumers to stub their clocks to always return the same value of time +so that it gets matched by the stub. You can provide the dynamic parts in your contracts +in two ways: pass them directly in the body or set them in separate sections called +`testMatchers` and `stubMatchers`. ==== Dynamic properties inside the body -You can set the properties inside the body either via the `value` method +You can set the properties inside the body either with the `value` method or, if you use +the Groovy map notation, with `$()`. The following example shows how to set dynamic +properties with the value method: [source,groovy,indent=0] ---- @@ -226,7 +263,7 @@ value(stub(...), test(...)) value(client(...), server(...)) ---- -or if you're using the Groovy map notation for body you can use the `$()` method +The following example shows how to set dynamic properties with `$()`: [source,groovy,indent=0] ---- @@ -236,124 +273,129 @@ $(stub(...), test(...)) $(client(...), server(...)) ---- -All of the aforementioned approaches are equal. That means that `stub` and `client` methods are aliases over the `consumer` -method. Let's take a closer look at what we can do with those values in the subsequent sections. +Both approaches work equally well. `stub` and `client` methods are aliases over the `consumer` +method. Subsequent sections take a closer look at what you can do with those values. ==== Regular expressions -You can use regular expressions to write your requests in Contract DSL. It is particularly useful when you want to indicate that a given response -should be provided for requests that follow a given pattern. Also, you can use it when you need to use patterns and not exact values both -for your test and your server side tests. +You can use regular expressions to write your requests in Contract DSL. Doing so is +particularly useful when you want to indicate that a given response should be provided +for requests that follow a given pattern. Also, you can use regular expressions when you +need to use patterns and not exact values both for your test and your server side tests. -Please see the example below: +The following example shows how to use regular expressions to write a request: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=regex,indent=0] ---- -You can also provide only one side of the communication using a regular expression. If you do that then automatically we'll -provide the generated string that matches the provided regular expression. For example: +You can also provide only one side of the communication with a regular expression. If you +do so, then the contract engine automatically provides the generated string that matches +the provided regular expression. The following code shows an example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=dsl_one_side_data_generation_example,indent=0] ---- -In this example for request and response the opposite side of the communication will have the respective data generated. +In the preceding example, the opposite side of the communication has the respective data +generated for request and response. -Spring Cloud Contract comes with a series of predefined regular expressions that you can use in your contracts. +Spring Cloud Contract comes with a series of predefined regular expressions that you can +use in your contracts, as shown in the following example: [source,groovy,indent=0] ---- include::{contract_spec_path}/src/main/groovy/org/springframework/cloud/contract/spec/internal/RegexPatterns.groovy[tags=regexps,indent=0] ---- -so in your contract you can use it like this +In your contract, you can use it as shown in the following example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=contract_with_regex,indent=0] ---- -==== Passing optional parameters +==== Passing Optional Parameters -It is possible to provide optional parameters in your contract. It's only possible to have optional parameter for the: +It is possible to provide optional parameters in your contract. However, you can provide +optional parameters only for the following: -- __STUB__ side of the Request -- __TEST__ side of the Response +* __STUB__ side of the Request +* __TEST__ side of the Response -Example: +The following example shows how to provide optional parameters: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=optionals,indent=0] ---- -By wrapping a part of the body with the `optional()` method you are in fact creating a regular expression that should be present 0 or more times. +By wrapping a part of the body with the `optional()` method, you create a regular +expression that must be present 0 or more times. -That way for the example above the following test would be generated if you pick Spock: +If you use Spock for, the following test would be generated from the previous example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=optionals_test,indent=0] ---- -and the following stub: +The following stub would also be generated: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=wiremock,indent=0] ---- -==== Executing custom methods on server side +==== Executing Custom Methods on the Server Side -It is also possible to define a method call to be executed on the server side during the test. Such a method can be added to the class defined as "baseClassForTests" -in the configuration. Example: - -*Contract* +You can define a method call that executes on the server side during the test. Such a +method can be added to the class defined as "baseClassForTests" in the configuration. The +following code shows an example of the contract portion of the test case: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=method,indent=0] ---- -*Base class* +The following code shows the base class portion of the test case: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ---- -IMPORTANT: You can't use both a String and `execute` to perform concatenation. E.g. calling -`header('Authorization', 'Bearer ' + execute('authToken()'))` will lead to improper results. -To make this work just call `header('Authorization', execute('authToken()'))` and ensure that -the `authToken()` method returns everything that you need. +IMPORTANT: You cannot use both a String and `execute` to perform concatenation. For +example, calling `header('Authorization', 'Bearer ' + execute('authToken()'))` leads to +improper results. Instead, call `header('Authorization', execute('authToken()'))` and +ensure that the `authToken()` method returns everything you need. -The type of the object read from the JSON can be one of the followings depending on the +The type of the object read from the JSON can be one of the following, depending on the JSON path: - - `String` if you point to a `String` value in a JSON - - `JSONArray` if you point to a `List` in a JSON - - `Map` if you point to a `Map` in a JSON - - proper `Number` if you point to `Integer`, `Double` etc. in a JSON - - `Boolean` if you point to a `Boolean` in a JSON +* `String`: If you point to a `String` value in the JSON. +* `JSONArray`: If you point to a `List` in the JSON. +* `Map`: If you point to a `Map` in the JSON. +* `Number`: If you point to `Integer`, `Double` etc. in the JSON. +* `Boolean`: If you point to a `Boolean` in the JSON. -In the request part of the contract you can specify that the `body` should be -taken from a method. +In the request part of the contract, you can specify that the `body` should be taken from +a method. -IMPORTANT: You have to provide both the consumer and the producer side -and the `execute` part can be applied for the whole body. Not for parts of it! +IMPORTANT: You must provide both the consumer and the producer side. The `execute` part +is applied for the whole body - not for parts of it. -Example: +The following example shows how to read an object from JSON: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MethodBodyBuilderSpec.groovy[tags=body_execute,indent=0] ---- -This will result in calling the `hashCode()` method in the request body. -It would more or less like this: +The preceding example results in calling the `hashCode()` method in the request body. +It should resemble the following code: [source,java,indent=0] ---- @@ -369,30 +411,33 @@ It would more or less like this: assertThat(response.statusCode()).isEqualTo(200); ---- -==== Referencing request from response +==== Referencing the Request from the Response -The best situation is to provide fixed values but sometimes you need to reference a request in your response. -In order to do this you can profit from the `fromRequest()` method that allows you to reference a bunch -of elements from the HTTP request. You can use the following options: +The best situation is to provide fixed values, but sometimes you need to reference a +request in your response. To do so, you can use the `fromRequest()` method, which lets +you reference a bunch of elements from the HTTP request. You can use the following +options: -- `fromRequest().url()` - return the request URL and query parameters -- `fromRequest().query(String key)` - return the first query parameter with a given name -- `fromRequest().query(String key, int index)` - return the nth query parameter with a given name -- `fromRequest().path()` - return the full path -- `fromRequest().path(int index)` - return the nth path element -- `fromRequest().header(String key)` - return the first header with a given name -- `fromRequest().header(String key, int index)` - return the nth header with a given name -- `fromRequest().body()` - return the full request body -- `fromRequest().body(String jsonPath)` - return the element from the request that matches the JSON Path +* `fromRequest().url()`: Returns the request URL and query parameters. +* `fromRequest().query(String key)`: Returns the first query parameter with a given name. +* `fromRequest().query(String key, int index)`: Returns the nth query parameter with a +given name. +* `fromRequest().path()`: Returns the full path. +* `fromRequest().path(int index)`: Returns the nth path element. +* `fromRequest().header(String key)`: Returns the first header with a given name. +* `fromRequest().header(String key, int index)`: Returns the nth header with a given name. +* `fromRequest().body()`: Returns the full request body. +* `fromRequest().body(String jsonPath)`: Returns the element from the request that +matches the JSON Path. -Let's take a look at the following contract +Consider the following contract: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderSpec.groovy[tags=template_contract,indent=0] ---- -Running a JUnit test generation will lead in creation of a test looking more or less like this +Running a JUnit test generation leads to a test that resembles the following example: [source,java,indent=0] ---- @@ -426,9 +471,9 @@ Running a JUnit test generation will lead in creation of a test looking more or assertThatJson(parsedJson).field("['responseBaz2']").isEqualTo("Bla bla bar bla bla"); ---- -As you can see elements from the request have been properly referenced in the response. +As you can see, elements from the request have been properly referenced in the response. -The generated WireMock stub will look more or less like this: +The generated WireMock stub should resemble the following example: [source,json,indent=0] ---- @@ -463,8 +508,8 @@ The generated WireMock stub will look more or less like this: } ---- -So sending a request as the one presented in the `request` part of the contract will lead in sending the following -response body +Sending a request such as the one presented in the `request` part of the contract results +in sending the following response body: [source,json,indent=0] ---- @@ -483,90 +528,98 @@ response body } ---- -IMPORTANT: This feature will work only with WireMock having version greater or equal to 2.5.1. We're using WireMock's -`response-template` response transformer. It's using Handlebars to convert the Mustache `{{{ }}}` templates into -proper values. Additionally we're registering 2 helper functions. `escapejsonbody` - that escapes the request -body in a format that can be embedded in a JSON. Another is `jsonpath` that for a given parameter knows how to -find an object in the request body. +IMPORTANT: This feature works only with WireMock having a version greater than or equal +to 2.5.1. The Spring Cloud Contract Verifier uses WireMock's +`response-template` response transformer. It uses Handlebars to convert the Mustache `{{{ }}}` templates into +proper values. Additionally, it registers two helper functions: -==== Dynamic properties in matchers sections +* `escapejsonbody`: Escapes the request body in a format that can be embedded in a JSON. +* `jsonpath`: For a given parameter, find an object in the request body. -If you've been working with https://docs.pact.io/[Pact] this might seem familiar. Quite a few users -are used to having a separation between the body and setting dynamic parts of your contract. +==== Dynamic Properties in the Matchers Sections -That's why you can profit from two separate sections. One is called `stubMatchers` where you can -define the dynamic values that should end up in a stub. You can set it in the `request` or `inputMessage` -part of your contract. The other is called `testMatchers` which is present in the `response` or -`outputMessage` side of the contract. +If you work with https://docs.pact.io/[Pact], the following discussion may seem familiar. +Quite a few users are used to having a separation between the body and setting the +dynamic parts of a contract. -Currently we support only JSON Path based matchers with the following matching possibilities. -For `stubMatchers`: +You can use two separate sections: -- `byEquality()` - the value taken from the response via the provided JSON Path needs -to be equal to the provided value in the contract -- `byRegex(...)` - the value taken from the response via the provided JSON Path needs -to match the regex -- `byDate()` - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Date -- `byTimestamp()` - the value taken from the response via the provided JSON Path needs -to match the regex for ISO DateTime -- `byTime()` - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Time +* `stubMatchers`, which lets you define the dynamic values that should end up in a stub. +You can set it in the `request` or `inputMessage` part of your contract. +* `testMatchers`, which is present in the `response` or `outputMessage` side of the +contract. -For `testMatchers`: +Currently, Spring Cloud Contract Verifier supports only JSON Path-based matchers with the +following matching possibilities: -- `byEquality()` - the value taken from the response via the provided JSON Path needs -to be equal to the provided value in the contract -- `byRegex(...)` - the value taken from the response via the provided JSON Path needs -to match the regex -- `byDate()` - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Date -- `byTimestamp()` - the value taken from the response via the provided JSON Path needs -to match the regex for ISO DateTime -- `byTime()` - the value taken from the response via the provided JSON Path needs to -match the regex for ISO Time -- `byType()` - the value taken from the response via the provided JSON Path needs to -be of the same type as the type defined in the body of the response in the contract. -`byType` can take a closure where you can set `minOccurrence` and `maxOccurrence`. -That way you can assert on the size of the flattened collection. To check the size -of an unflattened collection, use a custom method via `byCommand(...)` testMatcher. -- `byCommand(...)` - the value taken from the response via the provided JSON Path will be -passed as an input to the custom method that you're providing. E.g. `byCommand('foo($it)')` -will result in calling a `foo` method to which the value matching the JSON Path will get - passed. - ** The type of the object read from the JSON can be one of the followings depending on the - JSON path: - *** `String` if you point to a `String` value in a JSON - *** `JSONArray` if you point to a `List` in a JSON - *** `Map` if you point to a `Map` in a JSON - *** proper `Number` if you point to `Integer`, `Double` etc. in a JSON - *** `Boolean` if you point to a `Boolean` in a JSON +* For `stubMatchers`: +** `byEquality()`: The value taken from the response via the provided JSON Path must be +equal to the value provided in the contract. +** `byRegex(...)`: The value taken from the response via the provided JSON Path must +match the regex. +** `byDate()`: The value taken from the response via the provided JSON Path must +match the regex for an ISO Date value. +** `byTimestamp()`: The value taken from the response via the provided JSON Path must +match the regex for an ISO DateTime value. +** `byTime()`: The value taken from the response via the provided JSON Path must +match the regex for an ISO Time value. +* For `testMatchers`: +** `byEquality()`: The value taken from the response via the provided JSON Path must be +equal to the provided value in the contract. +** `byRegex(...)`: The value taken from the response via the provided JSON Path must +match the regex. +** `byDate()`: The value taken from the response via the provided JSON Path must match +the regex for an ISO Date value. +** `byTimestamp()`: The value taken from the response via the provided JSON Path must +match the regex for an ISO DateTime value. +** `byTime()`: The value taken from the response via the provided JSON Path must match +the regex for an ISO Time value. +** `byType()`: The value taken from the response via the provided JSON Path needs to be +of the same type as the type defined in the body of the response in the contract. +`byType` can take a closure, in which you can set `minOccurrence` and `maxOccurrence`. +That way, you can assert the size of the flattened collection. To check the size of an +unflattened collection, use a custom method with the `byCommand(...)` testMatcher. +** `byCommand(...)`: The value taken from the response via the provided JSON Path is +passed as an input to the custom method that you provide. For example, +`byCommand('foo($it)')` results in calling a `foo` method to which the value matching the +JSON Path gets passed. The type of the object read from the JSON can be one of the +following, depending on the JSON path: +*** `String`: If you point to a `String` value. +*** `JSONArray`: If you point to a `List`. +*** `Map`: If you point to a `Map`. +*** `Number`: If you point to `Integer`, `Double`, or other kind of number. +*** `Boolean`: If you point to a `Boolean`. -Let's take a look at the following example: +Consider the following example: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderWithMatchersSpec.groovy[tags=matchers,indent=0] ---- -In this example we're providing the dynamic portions of the contract in the matchers sections. - For the request part you can see that for all fields but `valueWithoutAMatcher` we're setting - explicitly the values of regular expressions we'd like the stub to contain. For the `valueWithoutAMatcher` - the verification will take place in the same way as without the usage of matchers - the test - will perform an equality check in this case. +In the preceding example, you can see the dynamic portions of the contract in the +`matchers` sections. For the request part, you can see that, for all fields but +`valueWithoutAMatcher`, the values of the regular expressions that the stub should +contain are explicitly set. For the `valueWithoutAMatcher`, the verification takes place +in the same way as without the use of matchers. In that case, the test performs an +equality check. -For the response side in the `testMatchers` section we're defining all the dynamic parts - in a similar manner. The only difference is that we have the `byType` matchers too. In that - case we're checking 4 fields in the way that we're verifying whether the response from the test - has a value whose JSON path matching the given field is of the same type as the one defined in the response body and: +For the response side in the `testMatchers` section, we define the dynamic parts in a +similar manner. The only difference is that the `byType` matchers are also present. The +verifier engine checks four fields to verify whether the response from the test +has a value for which the JSON path matches the given field, is of the same type as the one +defined in the response body, and passes the following check (based on the method being called): - - for `$.valueWithTypeMatch` - we're just checking the whether the type is the same - - for `$.valueWithMin` - we're checking the type and assert if the size is greater or equal to the min occurrence - - for `$.valueWithMax` - we're checking the type and assert if the size is smaller or equal to the max occurrence - - for `$.valueWithMinMax` - we're checking the type and assert if the size is between the min and max occurrence +* For `$.valueWithTypeMatch`, the engine checks whether the type is the same. +* For `$.valueWithMin`, the engine check the type and asserts whether the size is greater +than or equal to the minimum occurrence. +* For `$.valueWithMax`, the engine checks the type and asserts whether the size is +smaller than or equal to the maximum occurrence. +* For `$.valueWithMinMax`, the engine checks the type and asserts whether the size is +between the min and maximum occurrence. -The resulting test would look more or less like this (note that we're separating the autogenerated -assertions and the one from matchers with an `and` section): +The resulting test would resemble the following example (note that an `and` section +separates the autogenerated assertions and the assertion from matchers): [source,java,indent=0] ---- @@ -609,23 +662,25 @@ assertions and the one from matchers with an `and` section): assertThatValueIsANumber(parsedJson.read("$.duck")); ---- -IMPORTANT: Notice that for the `byCommand` method we are calling the `assertThatValueIsANumber`. This method needs -to be defined in the test base class or should be statically imported to your tests. -Notice that the `byCommand` call was converted to `assertThatValueIsANumber(parsedJson.read("$.duck"));`. That means -that we took the method name and passed the proper JSON path as a parameter to it. +IMPORTANT: Notice that, for the `byCommand` method, the example calls the +`assertThatValueIsANumber`. This method must be defined in the test base class or be +statically imported to your tests. Notice that the `byCommand` call was converted to +`assertThatValueIsANumber(parsedJson.read("$.duck"));`. That means that the engine took +the method name and passed the proper JSON path as a parameter to it. -and the WireMock stub like this: +The resulting WireMock stub is in the following example: [source,json,indent=0] ---- include::{plugins_path}/spring-cloud-contract-converters/src/test/groovy/org/springframework/cloud/contract/verifier/wiremock/DslToWireMockClientConverterSpec.groovy[tags=matchers,indent=0] ---- -IMPORTANT: If you use a `matcher` then the part of the request / response that the `matcher` is addressing -via the JSON Path will get removed from assertion. In case of verifying a collection you have to create -matchers for *all* elements of the collection. +IMPORTANT: If you use a `matcher`, then the part of the request aned response that the +`matcher` addresses with the JSON Path gets removed from the assertion. In the case of +verifying a collection, you must create matchers for *all* the elements of the +collection. -Let's look at the following example: +Consider the following example: [source,groovy,indent=0] ---- @@ -656,7 +711,7 @@ Contract.make { } ---- -This will lead in creating the following test (showing just the assertion section) +The preceding code leads to creating the following test (the code block shows only the assertion section): [source,java,indent=0] ---- @@ -673,15 +728,16 @@ This will lead in creating the following test (showing just the assertion sectio assertThat(parsedJson.read("\$.events[0].status", String.class)).matches(".+") ---- -As you can see the assertion is malformed. That's because only the first element of the array got asserted. -In order to fix this it's best to apply the assertion to the whole `$.events` collection and assert it -via the `byCommand(...)` method. +As you can see, the assertion is malformed. Only the first element of the array got +asserted. In order to fix this, you should apply the assertion to the whole `$.events` +collection and assert it with the `byCommand(...)` method. -=== JAX-RS support +=== JAX-RS Support -We support JAX-RS 2 Client API. Base class needs to define `protected WebTarget webTarget` and server initialization, right now the only option how to test JAX-RS API is to start a web server. - -Request with a body needs to have a content type set otherwise `application/octet-stream` is going to be used. +The Spring Cloud Contract Verifier supports the JAX-RS 2 Client API. The base class needs +to define `protected WebTarget webTarget` and server initialization. The only option for +testing JAX-RS API is to start a web server. Also, a request with a body needs to have a +content type set. Otherwise, the default of `application/octet-stream` gets used. In order to use JAX-RS mode, use the following settings: @@ -690,18 +746,18 @@ In order to use JAX-RS mode, use the following settings: testMode == 'JAXRSCLIENT' ---- -Example of a test API generated: +The following example shows a generated test API: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/JaxRsClientMethodBuilderSpec.groovy[tags=jaxrs,indent=0] ---- -=== Async support +=== Async Support -If you're using asynchronous communication on the server side (your controllers are returning -`Callable`, `DeferredResult` etc. then inside your contract you have to provide in the `response` -section a `async()` method. Example: +If you're using asynchronous communication on the server side (your controllers are +returning `Callable`, `DeferredResult`, and so on), then, inside your contract, you must +provide a `sync()` method in the `response` section. The following code shows an example: [source,groovy,indent=0] ---- @@ -722,10 +778,10 @@ org.springframework.cloud.contract.spec.Contract.make { Spring Cloud Contract supports context paths. -IMPORTANT: The only thing that changes in order to fully support context paths is the switch -on the *PRODUCER* side. The autogenerated tests need to be using the *EXPLICIT* mode. - -The consumer side remains untouched, in order for the generated test to pass you have to switch the *EXPLICIT* mode. +IMPORTANT: The only change needed to fully support context paths is the switch on the +*PRODUCER* side. Also, the autogenerated tests must use *EXPLICIT* mode. The consumer +side remains untouched. In order for the generated test to pass, you must use *EXPLICIT* +mode. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -749,79 +805,99 @@ contracts { } ---- -That way you'll generate a test that *DOES NOT* use MockMvc. It means that you're generating -real requests and you need to setup your generated test's base class to work on a real socket. +That way, you generate a test that *DOES NOT* use MockMvc. It means that you generate +real requests and you need to setup your generated test's base class to work on a real +socket. -Let's imagine the following contract: +Consider the following contract: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_contract,indent=0] ---- -Here is an example of how to set up a base class and Rest Assured for everything to work correctly. +The following example shows how to set up a base class and Rest Assured: [source,groovy,indent=0] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGeneratorSpec.groovy[tags=context_path_baseclass,indent=0] ---- -That way all: +If you do it this way: -- all your requests in the autogenerated tests will be sent to the real endpoint with your context path included (e.g. `/my-context-path/url`) -- your contracts reflect that you have a context path, thus your generated stubs will also - have that information (e.g. in the stubs you'll see that you have too call `/my-context-path/url`) +* All of your requests in the autogenerated tests are sent to the real endpoint with your +context path included (for example, `/my-context-path/url`). +* Your contracts reflect that you have a context path. Your generated stubs also have +that information (for example, in the stubs, you have to call `/my-context-path/url`). === Messaging Top-Level Elements -The DSL for messaging looks a little bit different than the one that focuses on HTTP. +The DSL for messaging looks a little bit different than the one that focuses on HTTP. The +following sections explain the differences: -==== Output triggered by a method +* <> +* <> +* <> -The output message can be triggered by calling a method (e.g. a Scheduler was started and a message was sent) +[[contract-dsl-output-triggered-method]] +==== Output Triggered by a Method + +The output message can be triggered by calling a method (such as a `Scheduler` when a was +started and a message was sent), as shown in the following example: [source,groovy] ---- include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=method_trigger,indent=0] ---- -In this case the output message will be sent to `output` if a method called `bookReturnedTriggered` will be executed. In the message *publisher's* side -we will generate a test that will call that method to trigger the message. On the *consumer* side you can use the `some_label` to trigger the message. +In the previous example case, the output message is sent to `output` if a method called +`bookReturnedTriggered` is executed. On the message *publisher's* side, we generate a +test that calls that method to trigger the message. On the *consumer* side, you can use +the `some_label` to trigger the message. -==== Output triggered by a message +[[contract-dsl-output-triggered-message]] +==== Output Triggered by a Message -The output message can be triggered by receiving a message. +The output message can be triggered by receiving a message, as shown in the following +example: [source,groovy] ---- include::{tests_path}/samples-messaging-integration/src/test/groovy/com/example/IntegrationMessagingApplicationSpec.groovy[tags=message_trigger,indent=0] ---- -In this case the output message will be sent to `output` if a proper message will be received on the `input` destination. In the message *publisher's* side -we will generate a test that will send the input message to the defined destination. On the *consumer* side you can either send a message to the input -destination or use the `some_label` to trigger the message. +In the preceding example, the output message is sent to `output` if a proper message is +received on the `input` destination. On the message *publisher's* side, the engine +generates a test that sends the input message to the defined destination. On the +*consumer* side, you can either send a message to the input destination or use a label +(`some_label` in the example) to trigger the message. -==== Consumer / Producer +[[contract-dsl-consumer-producer]] +==== Consumer/Producer -In HTTP you have a notion of `client`/`stub and `server`/`test` notation. You can use them also in messaging but we're providing also the `consumer` and `produer` methods -as presented below (note you can use either `$` or `value` methods to provide `consumer` and `producer` parts) +In HTTP, you have a notion of `client`/`stub and `server`/`test` notation. You can also +use those paradigms in messaging. In addition, Spring Cloud Contract Verifier also +provides the `consumer` and `producer` methods, as presented in the following example +(note that you can use either `$` or `value` methods to provide `consumer` and `producer` +parts): [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=consumer_producer] ---- -=== Multiple contracts in one file +=== Multiple Contracts in One File -It's possible to define multiple contracts in one file. An example of such a contract can look like this +You can define multiple contracts in one file. Such a contract might resemble the +following example: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/multiple-contracts/src/test/resources/contracts/com/hello/v1/WithList.groovy[lines=18..-1,indent=0] ---- -In this example one contract has the `name` field and the other doesn't. This will lead to generation of -two tests that will look more or less like this: +In the preceding example, one contract has the `name` field and the other does not. This +leads to generation of two tests that look more or less like this: [source,java,indent=0] ---- @@ -869,12 +945,12 @@ public class V1Test extends TestBase { } ---- -Notice that for the contract that has the `name` field the generated test method is named -`validate_should_post_a_user`. For the one that doesn't have the name it's called +Notice that, for the contract that has the `name` field, the generated test method is named +`validate_should_post_a_user`. For the one that does not have the name, it is called `validate_withList_1`. It corresponds to the name of the file `WithList.groovy` and the index of the contract in the list. -The generated stubs will look like this +The generated stubs is shown in the following example: [source] ---- @@ -882,30 +958,32 @@ should post a user.json 1_WithList.json ---- -As you can see the first file got the `name` parameter from the contract. The second -got the name of the contract file `WithList.groovy` prefixed with the index (in this case -contract had index `1` in the list of contracts in the file). - -TIP: As you can see it's much better if you name your contracts since then your tests - are far more meaningful. +As you can see, the first file got the `name` parameter from the contract. The second +got the name of the contract file (`WithList.groovy`) prefixed with the index (in this +case, the contract had an index of `1` in the list of contracts in the file). +TIP: As you can see, it iss much better if you name your contracts because doing so makes +your tests far more meaningful. == Customization +You can customize the Spring Cloud Contract Verifier by extending the DSL, as shown in +the remainder of this section. + === Extending the DSL -It is possible to provide your own functions to the DSL. The key requirement for this -feature was to maintain the static compatibility. Below you will be able to see an example -of: +You can provide your own functions to the DSL. The key requirement for this feature is to +maintain the static compatibility. Later in this document, you can see examples of: -- creation of a JAR with reusable classes -- referencing of these classes in the DSLs +* Creating a JAR with reusable classes. +* Referencing of these classes in the DSLs. -The full example can be found https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. +You can find the full example +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[here]. ==== Common JAR -Below you can find three classes that we will reuse in the DSLs. +The following examples show three classes that can be reused in the DSLs. *PatternUtils* contains functions used by both the **consumer** and the **producer**. @@ -928,16 +1006,18 @@ include::{samples_url}/common/src/main/java/com/example/ConsumerUtils.java[] include::{samples_url}/common/src/main/java/com/example/ProducerUtils.java[] ---- -==== Adding the dependency to project +==== Adding the Dependency to the Project -In order for the plugins and IDE to be able to reference the common JAR classes you need +In order for the plugins and IDE to be able to reference the common JAR classes, you need to pass the dependency to your project. -==== Test dependency in project's dependencies +// TODO missing code block here - we should show an example adding a dependency -First add the common jar dependency as a test dependency. That way since your -contracts files are available at test resources path, automatically the -common jar classes will be visible in your Groovy files. +==== Test the Dependency in the Project's Dependencies + +First, add the common jar dependency as a test dependency. Because your contracts files +are available on the test resources path, the common jar classes automatically become +visible in your Groovy files. The following examples show how to test the dependency: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -951,9 +1031,10 @@ include::{samples_url}/producer/pom.xml[tags=test_dep,indent=0] include::{samples_url}/producer/build.gradle[tags=test_dep,indent=0] ---- -==== Test dependency in plugin's dependencies +==== Test a Dependency in the Plugin's Dependencies -Now you have to add the dependency for the plugin to reuse at runtime. +Now, you must add the dependency for the plugin to reuse at runtime, as shown in the +following example: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -969,80 +1050,84 @@ include::{samples_url}/producer/build.gradle[tags=test_dep_in_plugin,indent=0] ==== Referencing classes in DSLs -Now you can reference your classes in your DSL. Example: +You can now reference your classes in your DSL, as shown in the following example: [source,groovy] ---- include::{samples_url}/producer/src/test/resources/contracts/beer/rest/shouldGrantABeerIfOldEnough.groovy[indent=0] ---- -== Pluggable architecture +== Using the Pluggable Architecture -There are cases where you have your contracts defined in other formats -like YAML, RAML or PACT. On the other hand you'd like to profit from -the test and stubs generation. It's really easy to add your own implementation -of either of those. Also you can customize the way tests are generated (for example you can generate -tests for other languages) and you can do the same for stubs generation (you can generate -stubs for other stub http server implementations). +You may encounter cases where you have your contracts have been defined in other formats, +such as YAML, RAML or PACT. In those cases, you still want to benefit from the automatic +generation of tests and stubs. You can add your own implementation for generating both +tests and stubs. Also, you can customize the way tests are generated (for example, you +can generate tests for other languages) and the way stubs are generated (for example, you +can generate stubs for other HTTP server implementations). -=== Custom contract converter +=== Custom Contract Converter -Let's assume that your contract is written in a YAML file like this: +Assume that your contract is written in a YAML file as follows: [source,yml] ---- include::{verifier_core_path}/src/test/resources/contract.yml[indent=0] ---- -Thanks to the interface +The `ContractConverter` interface lets you register your own implementation of a contract +structure converter. The following code listing shows the `ContractConverter` interface: [source,groovy] ---- include::{contract_spec_path}/src/main/groovy/org/springframework/cloud/contract/spec/ContractConverter.groovy[indent=0,lines=17..-1] ---- -you can register your own implementation of a contract structure converter. -Your implementation needs to state the condition on which it should start the -conversion. Also you have to define how to perform that conversion in both ways. +Your implementation must define the condition on which it should start the +conversion. Also, you must define how to perform that conversion in both directions. -IMPORTANT: Once you create your implementation you have to create a `/META-INF/spring.factories` -file in which you provide the fully qualified name of your implementation. +IMPORTANT: Once you create your implementation, you must create a +`/META-INF/spring.factories` file in which you provide the fully qualified name of your +implementation. -Example of a `spring.factories` file +The following example shows a typical `spring.factories` file: [source] ---- include::{verifier_core_path}/src/test/resources/META-INF/spring.factories[indent=0] ---- -and the YAML implementation +The following example shows a typical YAML implementation that matches the preceding +example: [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/converter/YamlContractConverter.groovy[indent=0,lines=16..-1] ---- -==== Pact converter +==== Pact Converter -Spring Cloud Contract comes with an out of the box support for https://docs.pact.io/[Pact] representation of contracts. -In other words instead of using the Groovy DSL you can use Pact files. In this section -we will present how to add such a support for your project. +Spring Cloud Contract includes support for https://docs.pact.io/[Pact] representation of +contracts. Instead of using the Groovy DSL, you can use Pact files. In this section, we +present how to add Pact support for your project. -==== Pact contract +==== Pact Contract -We will be working on the following example of a Pact contract. We've placed this file under -the `src/test/resources/contracts` folder. +Consider following example of a Pact contract, which is a file under the +`src/test/resources/contracts` folder. [source,javascript,indent=0] ---- include::{standalone_pact_path}/pact-http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.json[indent=0] ---- -==== Pact for producers +The remainder of this section about using Pact refers to the preceding file. -On the producer side you have add to your plugin configuration two additional dependencies. -One is the Spring Cloud Contract Pact support and the other represents the current -Pact version that you're using. +==== Pact for Producers + +On the producer side, you mustadd two additional dependencies to your plugin +configuration. One is the Spring Cloud Contract Pact support, and the other represents +the current Pact version that you use. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -1056,7 +1141,8 @@ include::{standalone_pact_path}/pact-http-server/pom.xml[tags=pact_dependency,in include::{standalone_pact_path}/pact-http-server/build.gradle[tags=pact_dependency,indent=0] ---- -When you execute the build of your application a test, looking more or less like this, will be generated +When you execute the build of your application, a test will be generated. The generated +test might be as follows: [source,java,indent=0] ---- @@ -1082,7 +1168,7 @@ When you execute the build of your application a test, looking more or less like } ---- -and the stub looking like this +The corresponding generated stub might be as follows: [source,javascript,indent=0] ---- @@ -1112,11 +1198,11 @@ and the stub looking like this } ---- -==== Pact for consumers +==== Pact for Consumers -On the producer side you have add to your project dependencies two additional dependencies. -One is the Spring Cloud Contract Pact support and the other represents the current -Pact version that you're using. +On the producer side, you must add two additional dependencies to your project +dependencies. One is the Spring Cloud Contract Pact support, and the other represents the +current Pact version that you use. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -1130,21 +1216,21 @@ include::{standalone_pact_path}/pact-http-client/pom.xml[tags=pact_dependency,in include::{standalone_pact_path}/pact-http-client/build.gradle[tags=pact_dependency,indent=0] ---- -=== Custom test generator +=== Using the Custom Test Generator -If you want to generate tests for different languages than Java or you're -not happy with the way we're building Java tests for you then you can register -your own implementation to do that. +If you want to generate tests for languages other than Java or you are not happy with the +way the verifier builds Java tests, you can register your own implementation. -Thanks to the interface +The `SingleTestGenerator` interface lets you register your own implementation. The +following code listing shows the `SingleTestGenerator` interface: [source,groovy] ---- include::{verifier_core_path}/src/main/groovy/org/springframework/cloud/contract/verifier/builder/SingleTestGenerator.groovy[indent=0,lines=17..-1] ---- -you can register your own implementation that generates a test. Again, it's enough to provide -a proper `spring.factories` file. Example: +Again, you must provide a `spring.factories` file, such as the one shown in the following +example: [source] ---- @@ -1152,18 +1238,19 @@ org.springframework.cloud.contract.verifier.builder.SingleTestGenerator=/ com.example.MyGenerator ---- -=== Custom stub generator +=== Using the Custom Stub Generator -If you want to generate stubs for other stub server than WireMock it's enough to - plug in your own implementation of this interface: +If you want to generate stubs for stub servers other than WireMock, you can plug in your +own implementation of the `StubGenerator` interface. The following code listing shows the +`StubGenerator` interface: [source,groovy] ---- include::{converters_path}/src/main/groovy/org/springframework/cloud/contract/verifier/converter/StubGenerator.groovy[indent=0,lines=16..-1] ---- -you can register your own implementation that generate Stubs. Again, it's enough to provide -a proper `spring.factories` file. Example: +Again, you must provide a `spring.factories` file, such as the one shown in the following +example: [source] ---- @@ -1172,26 +1259,27 @@ include::{converters_path}/src/main/resources/META-INF/spring.factories[indent=0 The default implementation is the WireMock stub generation. -TIP: You can provide multiple stub generator implementations. That way for example from a single -DSL as input you can e.g. produce WireMock stubs and Pact files too! +TIP: You can provide multiple stub generator implementations. For example, from a single +DSL, you can produce both WireMock stubs and Pact files. -=== Custom Stub Runner +=== Using the Custom Stub Runner -If you decide to have a custom stub generation you also need a custom way of running +If you decide to use a custom stub generation, you also need a custom way of running stubs with your different stub provider. -Let us assume that you're using https://github.com/dreamhead/moco[Moco] to build your stubs. -You wrote a proper stub generator and your stubs got placed in a JAR file. +Assume that you use https://github.com/dreamhead/moco[Moco] to build your stubs and that +you have written a stub generator and placed your stubs in a JAR file. -In order for Stub Runner to know how to run your stubs you have to define a custom - HTTP Stub server implementation. It can look like this: +In order for Stub Runner to know how to run your stubs, you have to define a custom +HTTP Stub server implementation, which might resemble the following example: [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-moco/src/test/groovy/org/springframework/cloud/contract/stubrunner/provider/moco/MocoHttpServerStub.groovy[indent=0,lines=16..-1] ---- -and just register it in your `spring.factories` file +Then, you can register it in your `spring.factories` file, as shown in the following +example: [source] ---- @@ -1199,15 +1287,15 @@ org.springframework.cloud.contract.stubrunner.HttpServerStub=\ org.springframework.cloud.contract.stubrunner.provider.moco.MocoHttpServerStub ---- -that way you'll be able to run stubs using Moco. +Now you can run stubs with Moco. -IMPORTANT: If you don't provide any implementation then the default one - WireMock based -will be picked. If you provide more than one then the first one on the list will be picked. +IMPORTANT: If you do not provide any implementation, then the default (WireMock) +implementation is used. If you provide more than one, the first one on the list is used. -=== Custom Stub Downloader +=== Using the Custom Stub Downloader -You can customize the way your stubs are downloaded. It's enough to create an -implementation of the `StubDownloaderBuilder` +You can customize the way your stubs are downloaded by creating an implementation of the +`StubDownloaderBuilder` interface, as shown in the following example: [source,java] ---- @@ -1233,7 +1321,8 @@ class CustomStubDownloaderBuilder implements StubDownloaderBuilder { } ---- -and just register it in your `spring.factories` file +Then you can register it in your `spring.factories` file, as shown in the following +example: [source] ---- @@ -1242,10 +1331,10 @@ org.springframework.cloud.contract.stubrunner.StubDownloaderBuilder=\ com.example.CustomStubDownloaderBuilder ---- -that way you'll be able to pick a folder with the source of your stubs. +Now you can pick a folder with the source of your stubs. -IMPORTANT: If you don't provide any implementation then the default one will be picked. - If you provide `repositoryRoot` property or `workOffline` flag then Aether based - that will download stubs from a remote repo will be picked. If you don't provide these - values then the `ClasspathStubProvider` will be picked that will scan the classpath. - If you provide more than one, then the first one on the list will be picked. +IMPORTANT: If you do not provide any implementation, then the default is used. +If you use the `repositoryRoot` property or the `workOffline` flag, then an Aether-based +implementation that downloads stubs from a remote repository is used. If you do not +provide these values, the `ClasspathStubProvider` (which will scan the classpath) is +used. If you provide more than one, then the first one on the list is used. diff --git a/docs/src/main/asciidoc/verifier_introduction.adoc b/docs/src/main/asciidoc/verifier_introduction.adoc index f71f4f7e2e..1fadbffad2 100644 --- a/docs/src/main/asciidoc/verifier_introduction.adoc +++ b/docs/src/main/asciidoc/verifier_introduction.adoc @@ -1,89 +1,110 @@ == Spring Cloud Contract Verifier Introduction -TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski (http://codearte.io[codearte.io]) +TIP: The Accurest project was initially started by Marcin Grzejszczak and Jakub Kubrynski +(http://codearte.io[codearte.io]) -Just to make long story short - Spring Cloud Contract Verifier is a tool that enables Consumer Driven Contract (CDC) development of JVM-based applications. It is shipped -with __Contract Definition Language__ (DSL). Contract definitions are used to produce following resources: +Spring Cloud Contract Verifier enables Consumer Driven Contract (CDC) development of +JVM-based applications. It moves TDD to the level of software architecture. -* JSON stub definitions to be used by WireMock when doing integration testing on the client code (__client tests__). -Test code must still be written by hand, test data is produced by Spring Cloud Contract Verifier. -* Messaging routes if you're using one. We're integrating with Spring Integration, Spring Cloud Stream, Spring AMQP and Apache Camel. You can however set your own integrations if you want to -* Acceptance tests (in JUnit or Spock) used to verify if server-side implementation of the API is compliant with the contract (__server tests__). -Full test is generated by Spring Cloud Contract Verifier. +Spring Cloud Contract Verifier ships with _Contract Definition Language_ (CDL). Contract +definitions are used to produce the following resources: -Spring Cloud Contract Verifier moves TDD to the level of software architecture. +* JSON stub definitions to be used by WireMock when doing integration testing on the +client code (_client tests_). Test code must still be written by hand, and test data is +produced by Spring Cloud Contract Verifier. +* Messaging routes, if you're using a messaging service. We integrate with Spring +Integration, Spring Cloud Stream, Spring AMQP, and Apache Camel. You can also set your +own integrations. +* Acceptance tests (in JUnit or Spock) are used to verify if server-side implementation +of the API is compliant with the contract (__server tests__). A full test is generated by +Spring Cloud Contract Verifier. -=== Why? +=== Why a Contract Verifier? -Let us assume that we have a system comprising of multiple microservices: +Assume that we have a system consisting of multiple microservices: image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Deps.png[Microservices Architecture] ==== Testing issues -If we wanted to test the application in top left corner if it can communicate with other services then we could do one of two things: +If we wanted to test the application in top left corner to determine whether it can +communicate with other services, we could do one of two things: -- deploy all microservices and perform end to end tests -- mock other microservices in unit / integration tests +- Deploy all microservices and perform end-to-end tests. +- Mock other microservices in unit/integration tests. -Both have their advantages but also a lot of disadvantages. Let's focus on the latter. +Both have their advantages but also a lot of disadvantages. *Deploy all microservices and perform end to end tests* Advantages: -- simulates production -- tests real communication between services +- Simulates production. +- Tests real communication between services. Disadvantages: -- to test one microservice we would have to deploy 6 microservices, a couple of databases etc. -- the environment where the tests would be conducted would be locked for a single suite of tests (i.e. nobody else would be able to run the tests in the meantime). -- long to run -- very late feedback -- extremely hard to debug +- To test one microservice, we have to deploy 6 microservices, a couple of databases, +etc. +- The environment where the tests run is locked for a single suite of tests (nobody else +would be able to run the tests in the meantime). +- They take a long time to run. +- The feedback comes very late in the process. +- They are extremely hard to debug. -*Mock other microservices in unit / integration tests* +*Mock other microservices in unit/integration tests* Advantages: -- very fast feedback -- no infrastructure requirements +- They provide very fast feedback. +- They have no infrastructure requirements. Disadvantages: -- the implementor of the service creates stubs thus they might have nothing to do with the reality -- you can go to production with passing tests and failing production +- The implementor of the service creates stubs that might have nothing to do with +reality. +- You can go to production with passing tests and failing production. -To solve the aforementioned issues Spring Cloud Contract Verifier with Stub Runner were created. Their main idea is to give you very fast feedback, without the need -to set up the whole world of microservices. If you work on stubs then the only applications you need are those that your application is using directly. +To solve the aforementioned issues, Spring Cloud Contract Verifier with Stub Runner was +created. The main idea is to give you very fast feedback, without the need to set up the +whole world of microservices. If you work on stubs, then the only applications you need +are those that your application directly uses. image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/Stubs2.png[Stubbed Services] -Spring Cloud Contract Verifier gives you the certainty that the stubs that you're using were created by the service that you're calling. Also if you can use them it means that they were -tested against the producer's side. In other words - you can trust those stubs. +Spring Cloud Contract Verifier gives you the certainty that the stubs that you use were +created by the service that you're calling. Also, if you can use them, it means that they +were tested against the producer's side. In short, you can trust those stubs. === Purposes The main purposes of Spring Cloud Contract Verifier with Stub Runner are: - - to ensure that WireMock / Messaging stubs (used when developing the client) are doing exactly what actual server-side implementation will do, - - to promote ATDD method and Microservices architectural style, - - to provide a way to publish changes in contracts that are immediately visible on both sides, - - to generate boilerplate test code used on the server side. +- To ensure that WireMock/Messaging stubs (used when developing the client) do exactly +what the actual server-side implementation does. +- To promote ATDD method and Microservices architectural style. +- To provide a way to publish changes in contracts that are immediately visible on both +sides. +- To generate boilerplate test code to be used on the server side. -IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business features in the contracts. -Let's 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 and one for the negative fraud case. -Contract tests are used to test contracts between applications and not to simulate full behaviour. +IMPORTANT: Spring Cloud Contract Verifier's purpose is NOT to start writing business +features in the contracts. Assume that we have a business use case of fraud check. If a +user can be a fraud for 100 different reasons, we would assume that you would create 2 +contracts, one for the positive case and one for the negative case. Contract tests are +used to test contracts between applications and not to simulate full behavior. -=== How +=== How It Works -==== Define the contract +This section explores how Spring Cloud Contract Verifier with Stub Runner works. -As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract. +==== Defining the contract -Let’s assume that we’d like to send the request containing the id of the client and the amount he wants to borrow from us. We’d like to send it to the /fraudcheck url via the PUT method. +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. [source,groovy,indent=0] ---- @@ -92,11 +113,11 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resource ==== Client Side -Spring Cloud Contract will generate stubs, which you can use during client side testing. -You will have a WireMock instance / Messaging route up and running that simulates the service Y. +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. +At some point in time, you need to send a request to the Fraud Detection service. [source,groovy,indent=0] ---- @@ -110,18 +131,20 @@ Annotate your test class with `@AutoConfigureStubRunner`. In the annotation prov include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ---- -After that, during the tests Spring Cloud Contract will automatically find the stubs (simulating the real service) in Maven repository and expose them on configured (or random) port. +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. ==== Server Side -Being a service Y since you are developing your stub, you need to be sure that it's actually resembling your -concrete implementation. You can't have a situation where your stub acts in one way and your application on -production behaves in a different way. +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. -That's why from the provided stub acceptance tests will be generated that will ensure -that your application behaves in the same way as you define in your stub. +To ensure that your application behaves the way you define in your stub, tests are +generated from the stub you provide. -The autogenerated test would look like this: +The autogenerated test looks like this: [source,java,indent=0] ---- @@ -146,26 +169,33 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -=== Step by step guide to CDC +=== Step-by-step Guide to Consumer Driven Contracts (CDC) -Let's take an example of Fraud Detection and Loan Issuance process. The business scenario is such that we want to issue loans to people but don't want them to steal the money from us. The current implementation of our system grants loans to everybody. +Consider an example of Fraud Detection and the Loan Issuance process. The business +scenario is such that we want to issue loans to people but do not want them to steal from +us. The current implementation of our system grants loans to everybody. -Let's assume that the `Loan Issuance` is a client to the -`Fraud Detection` server. In the current sprint we are required to develop a new feature - if a client wants to borrow too much money then we mark him as fraud. +Assume that `Loan Issuance` is a client to the `Fraud Detection` server. In the current +sprint, we must develop a new feature: if a client wants to borrow too much money, then +we mark the client as a fraud. -Technical remark - Fraud Detection will have artifact id `http-server`, Loan Issuance `http-client` and both have group id `com.example`. +Technical remark - Fraud Detection has an `artifact-id` of `http-server`, while Loan +Issuance has an artifact-id of `http-client`, and both have a `group-id` of `com.example`. -Social remark - both client and server development teams need to communicate directly and discuss changes while -going through the process. CDC is all about communication. +Social remark - both client and server development teams need to communicate directly and +discuss changes while going through the process. CDC is all about communication. -The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the client side code here]. +The https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-server[server +side code is available here] and https://github.com/spring-cloud/spring-cloud-contract/tree/{branch}/samples/standalone/dsl/http-client[the +client code here]. -TIP: In this case the ownership of the contracts lays on the producer side. It means that physically -all the contract are present in the producer's repository +TIP: In this case, the producer owns the contracts. Physically, all the contract are +in the producer's repository. ==== Technical note -If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the following section to your +If using the *SNAPSHOT* / *Milestone* / *Release Candidate* versions please add the +following section to your build: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -181,98 +211,125 @@ include::{introduction_url}/samples/standalone/dsl/http-server/build.gradle[tags ==== Consumer side (Loan Issuance) -As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): +As a developer of the Loan Issuance service (a consumer of the Fraud Detection server), you might do the following steps: -*start doing TDD by writing a test to your feature* +. Start doing TDD by writing a test for your feature. +. Write the missing implementation. +. Clone the Fraud Detection service repository locally. +. Define the contract locally in the repo of Fraud Detection service. +. Add the Spring Cloud Contract Verifier plugin. +. Run the integration tests. +. File a pull request. +. Create an initial implementation. +. Take over the pull request. +. Write the missing implementation. +. Deploy your app. +. Work online. + +*Start doing TDD by writing a test for your feature.* [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=client_tdd,indent=0] ---- -We've just written a test of our new feature. If a loan application for a big amount is received we should reject that loan application with some description. +Assume that you have written a test of your new feature. If a loan application for a big +amount is received, the system should reject that loan application with some description. -*write the missing implementation* +*Write the missing implementation.* -At some point in time you need to send a request to the Fraud Detection service. Let's assume that we'd like to send the request containing the id of the client and the amount he wants to borrow from us. We'd like to send it to the `/fraudcheck` url via the `PUT` method. +At some point in time, you need to send a request to the Fraud Detection service. Assume +that you need to send the request containing the ID of the client and the amount the +client wants to borrow. You want to send it to the `/fraudcheck` url via the `PUT` method. [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/main/java/com/example/loan/LoanApplicationService.java[tags=client_call_server,indent=0] ---- -For simplicity we've hardcoded the port of the Fraud Detection service at `8080` and our application is running on `8090`. +For simplicity, the port of the Fraud Detection service is set to `8080`, and the +application runs on `8090`. -If we'd start the written test it would obviously break since we have no service running on port `8080`. +If you start the test at this point, it breaks, because no service currently runs on port +`8080`. -*clone the Fraud Detection service repository locally* +*Clone the Fraud Detection service repository locally.* -We'll start playing around with the server side contract. That's why we need to first clone it. +You can start by playing around with the server side contract. To do so, you must first +clone it. [source,bash,indent=0] ---- git clone https://your-git-server.com/server-side.git local-http-server-repo ---- -*define the contract locally in the repo of Fraud Detection service* +*Define the contract locally in the repo of Fraud Detection service.* -As consumers we need to define what exactly we want to achieve. We need to formulate our expectations. That's why we write the following contract. +As a consumer, you need to define what exactly you want to achieve. You need to formulate +your expectations. To do so, write the following contract: -IMPORTANT: We're placing the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder -is important cause we'll reference that folder in the producer's test base class name. +IMPORTANT: Place the contract under `src/test/resources/contracts/fraud` folder. The `fraud` folder +is important because the producer's test base class name references that folder. [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/test/resources/contracts/fraud/shouldMarkClientAsFraud.groovy[] ---- -The Contract is written using a statically typed Groovy DSL. You might be wondering what are those -`value(client(...), server(...))` parts. By using this notation Spring Cloud Contract allows you to -define parts of a JSON / URL / etc. which are dynamic. In case of an identifier or a timestamp you -don't want to hardcode a value. You want to allow some different ranges of values. That's why for -the consumer side you can set regular expressions matching those values. You can provide the body -either by means of a map notation or String with interpolations. +The Contract is written using a statically typed Groovy DSL. You might wonder what about +those `value(client(...), server(...))` parts. By using this notation, Spring Cloud +Contract lets you define parts of a JSON block, a URL, etc., which are dynamic. In case +of an identifier or a timestamp, you need not hardcode a value. You want to allow some +different ranges of values. To enable ranges of values, you can set regular expressions +matching those values for the consumer side. You can provide the body by means of either +a map notation or String with interpolations. https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html#_contract_dsl[Consult the docs for more information.] We highly recommend using the map notation! -TIP: It's really important that you understand the map notation to set up contracts. Please read the -http://groovy-lang.org/json.html[Groovy docs regarding JSON] +TIP: You must understand the map notation in order to set up contracts. Please read the +http://groovy-lang.org/json.html[Groovy docs regarding JSON]. -The aforementioned contract is an agreement between two sides that: +The previously shown contract is an agreement between two sides that: -- if an HTTP request is sent with -** a method `PUT` on an endpoint `/fraudcheck` -** JSON body with `client.id` matching the regular expression `[0-9]{10}` and `loanAmount` equal to `99999` -** and with a header `Content-Type` equal to `application/vnd.fraud.v1+json` -- then an HTTP response would be sent to the consumer that -** has status `200` -** contains JSON body with the `fraudCheckStatus` field containing a value `FRAUD` and the `rejectionReason` field having value `Amount too high` -** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json` +- 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 +the `rejectionReason` field having value `Amount too high`, +** and a `Content-Type` header with a value of `application/vnd.fraud.v1+json`. -Once we're ready to check the API in practice in the integration tests we need to just install the stubs locally +Once you are ready to check the API in practice in the integration tests, you need to +install the stubs locally. -*add the Spring Cloud Contract Verifier plugin* +*Add the Spring Cloud Contract Verifier plugin.* -We can add either Maven or Gradle plugin - in this example we'll show how to add Maven. First we need to add the `Spring Cloud Contract` BOM. +We can add either a Maven or a Gradle plugin. In this example, you see how to add Maven. +First, add the `Spring Cloud Contract` BOM. [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_bom,indent=0] ---- -Next, the `Spring Cloud Contract Verifier` Maven plugin +Next, add the `Spring Cloud Contract Verifier` Maven plugin [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- -Since the plugin was added we get the `Spring Cloud Contract Verifier` features which from the provided contracts: +Since the plugin was added, you get the `Spring Cloud Contract Verifier` features which, +from the provided contracts: - generate and run tests - produce and install stubs -We don't want to generate tests since we, as consumers, want only to play with the stubs. That's why we need to skip the tests generation and execution. When we execute: +You do not want to generate tests since you, as the consumer, want only to play with the +stubs. You need to skip the test generation and execution. When you execute: [source,bash,indent=0] ---- @@ -280,7 +337,7 @@ cd local-http-server-repo ./mvnw clean install -DskipTests ---- -In the logs we'll see something like this: +In the logs, you see something like this: [source,bash,indent=0] ---- @@ -298,41 +355,47 @@ In the logs we'll see something like this: [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 ---- -This line is extremely important +The following line is extremely important: [source,bash,indent=0] ---- [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 ---- -It's confirming that the stubs of the `http-server` have been installed in the local repository. +It confirms that the stubs of the `http-server` have been installed in the local +repository. -*run the integration tests* +*Run the integration tests.* -In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic stub downloading you have to do the following in our consumer side project (`Loan Application service`). +In order to profit from the Spring Cloud Contract Stub Runner functionality of automatic +stub downloading, you must do the following in your consumer side project (`Loan +Application service`): -Add the `Spring Cloud Contract` BOM +Add the `Spring Cloud Contract` BOM: [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=contract_bom,indent=0] ---- -Add the dependency to `Spring Cloud Contract Stub Runner` +Add the dependency to `Spring Cloud Contract Stub Runner`: [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/pom.xml[tags=stub_runner,indent=0] ---- -Annotate your test class with `@AutoConfigureStubRunner`. In the annotation provide the group id and artifact id for the Stub Runner to download stubs of your collaborators. Also provide the offline work switch since you're playing with the collaborators offline (optional step). +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. [source,groovy,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-client/src/test/java/com/example/loan/LoanApplicationServiceTests.java[tags=autoconfigure_stubrunner,indent=0] ---- -Now if you run your tests you'll see sth like this: +Now, when you run your tests, you see something like this: [source,bash,indent=0] ---- @@ -345,21 +408,26 @@ Now if you run your tests you'll see sth like this: 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}] ---- -Which means that Stub Runner has found your stubs and started a server for app with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of the stubs and with `stubs` classifier on port `8080`. +This output means that Stub Runner has found your stubs and started a server for your app +with group id `com.example`, artifact id `http-server` with version `0.0.1-SNAPSHOT` of +the stubs and with `stubs` classifier on port `8080`. -*file a PR* +*File a pull request.* -What we did until now is an iterative process. We can play around with the contract, install it locally and work on the consumer side until we're happy with the contract. +What you have done until now is an iterative process. You can play around with the +contract, install it locally, and work on the consumer side until the contract works as +you wish. -Once we're satisfied with the results and the test passes publish a PR to the server side. Currently the consumer side work is done. +Once you are satisfied with the results and the test passes, publish a pull request to +the server side. Currently, the consumer side work is done. ==== Producer side (Fraud Detection server) As a developer of the Fraud Detection server (a server to the Loan Issuance service): -*initial implementation* +*Create an initial implementation.* -As a reminder here you can see the initial implementation +As a reminder, you can see the initial implementation here: [source,java,indent=0] ---- @@ -368,7 +436,7 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com } ---- -*take over the PR* +*Take over the pull request.* [source,bash,indent=0] ---- @@ -376,35 +444,37 @@ git checkout -b contract-change-pr master git pull https://your-git-server.com/server-side-fork.git contract-change-pr ---- -You have to add the dependencies needed by the autogenerated tests +You must add the dependencies needed by the autogenerated tests: [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=verifier_test_dependencies,indent=0] ---- -In the configuration of the Maven plugin we passed the `packageWithBaseClasses` property +In the configuration of the Maven plugin, pass the `packageWithBaseClasses` property [source,xml,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- -IMPORTANT: We've decided to use the "convention based" naming by setting the `packageWithBaseClasses` property. -That means that 2 last packages will be combined into a name of the base test class. In our case the contracts -were placed under `src/test/resources/contracts/fraud`. Since we don't have 2 packages starting from the `contracts` -folder we're picking only one which is `fraud`. We're adding the `Base` suffix and we're capitalizing `fraud`. -That gives us the `FraudBase` test class name. +IMPORTANT: This example uses "convention based" naming by setting the +`packageWithBaseClasses` property. Doing so means that the two last packages combine to +make the name of the base test class. In our case, the contracts were placed under +`src/test/resources/contracts/fraud`. Since you do not have two packages starting from +the `contracts` folder, pick only one, which should be `fraud`. Add the `Base` suffix and +capitalize `fraud`. That gives you the `FraudBase` test class name. -That's because all the generated tests will extend that class. Over there you can set up your Spring Context or -whatever is necessary. In our case we're using http://rest-assured.io/[Rest Assured MVC] to start the server side `FraudDetectionController`. +All the generated tests extend that class. Over there, you can set up your Spring Context +or whatever is necessary. In this case, use http://rest-assured.io/[Rest Assured MVC] to +start the server side `FraudDetectionController`. [source,java,indent=0] ---- include::{introduction_url}/samples/standalone/dsl/http-server/src/test/java/com/example/fraud/FraudBase.java[] ---- -Now, if you run the `./mvnw clean install` you would get sth like this: +Now, if you run the `./mvnw clean install`, you get something like this: [source,bash,indent=0] ---- @@ -414,7 +484,9 @@ Tests in error: ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed... ---- -That's because you have a new contract from which a test was generated and it failed since you haven't implemented the feature. The autogenerated test would look like this: +This error occurs because you have a new contract from which a test was generated and it +failed since you have not implemented the feature. The auto-generated test would look +like this: [source,java,indent=0] ---- @@ -439,13 +511,19 @@ public void validate_shouldMarkClientAsFraud() throws Exception { } ---- -As you can see all the `producer()` parts of the Contract that were present in the `value(consumer(...), producer(...))` blocks got injected into the test. +As you can see, all the `producer()` parts of the Contract that were present in the +`value(consumer(...), producer(...))` blocks got injected into the test. -What's important here to note is that on the producer side we also are doing TDD. We have expectations in form of a test. This test is shooting a request to our own application to an URL, headers and body defined in the contract. It also is expecting very precisely defined values in the response. In other words you have is your `red` part of `red`, `green` and `refactor`. Time to convert the `red` into the `green`. +Note that, on the producer side, you are also doing TDD. The expectations are expressed +in the form of a test. This test sends a request to our own application with the URL, +headers, and body defined in the contract. It also is expecting precisely defined values +in the response. In other words, you have the `red` part of `red`, `green`, and +`refactor`. It is time to convert the `red` into the `green`. -*write the missing implementation* +*Write the missing implementation.* -Now since we now what is the expected input and expected output let's write the missing implementation. +Because you know the expected input and expected output, you can write the missing +implementation: [source,java,indent=0] ---- @@ -455,11 +533,13 @@ include::{introduction_url}/samples/standalone/dsl/http-server/src/main/java/com } ---- -If we execute `./mvnw clean install` again the tests will pass. Since the `Spring Cloud Contract Verifier` plugin adds the tests to the `generated-test-sources` you can actually run those tests from your IDE. +When you execute `./mvnw clean install` again, the tests pass. Since the `Spring Cloud +Contract Verifier` plugin adds the tests to the `generated-test-sources`, you can +actually run those tests from your IDE. -*deploy your app* +*Deploy your app.* -Once you've finished your work it's time to deploy your change. First merge the branch +Once you finish your work, you can deploy your change. First, merge the branch: [source,bash,indent=0] ---- @@ -468,13 +548,14 @@ git merge --no-ff contract-change-pr git push origin master ---- -Then we assume that your CI would run sth like `./mvnw clean deploy` which would publish both the application and the stub artifcats. +Your CI might run something like `./mvnw clean deploy`, which would publish both the +application and the stub artifacts. -==== Consumer side (Loan Issuance) final step +==== Consumer Side (Loan Issuance) Final Step As a developer of the Loan Issuance service (a consumer of the Fraud Detection server): -*merge branch to master* +*Merge branch to master.* [source,bash,indent=0] ---- @@ -482,30 +563,33 @@ git checkout master git merge --no-ff contract-change-pr ---- -*work online* +*Work online.* -Now you can disable the offline work for Spring Cloud Contract Stub Runner and provide where the repository with your stubs is placed. At this moment the stubs of the server side will be automatically downloaded from Nexus / Artifactory. -You can switch off the value of the `workOffline` parameter in your annotation. Below you can see an -example of achieving the same by changing the properties. +Now you can disable the offline work for Spring Cloud Contract Stub Runner and indicate +where the repository with your stubs is located. At this moment the stubs of the server +side are automatically downloaded from Nexus/Artifactory. You can switch off the value of +the `workOffline` parameter in your annotation. The following code shows an example of +achieving the same thing by changing the properties. [source,yaml,indent=0] ---- include::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/samples/standalone/dsl/http-client/src/test/resources/application-test-repo.yaml[] ---- -And that's it! +That's it! === Dependencies -The best way to add the dependencies is to just use the proper `starter` dependency. +The best way to add dependencies is to use the proper `starter` dependency. -For `stub-runner` use `spring-cloud-starter-stub-runner` and when you're using a plugin just add +For `stub-runner`, use `spring-cloud-starter-stub-runner`. When you use a plugin, add `spring-cloud-starter-contract-verifier`. -=== Additional links +=== Additional Links -Below you can find some resources related to Spring Cloud Contract Verifier and Stub Runner. Note that some can be outdated since the Spring Cloud Contract Verifier project -is under constant development. +Here are some resources related to Spring Cloud Contract Verifier and Stub Runner. Note +that some may be outdated, because the Spring Cloud Contract Verifier project is under +constant development. ==== Spring Cloud Contract video @@ -522,4 +606,5 @@ video::sAAklvxmPmk[youtube,start=538,width=640,height=480] === Samples -Here you can find some https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. \ No newline at end of file +You can find some samples at +https://github.com/spring-cloud-samples/spring-cloud-contract-samples[samples]. diff --git a/docs/src/main/asciidoc/verifier_messaging.adoc b/docs/src/main/asciidoc/verifier_messaging.adoc index e599efa338..911429fdef 100644 --- a/docs/src/main/asciidoc/verifier_messaging.adoc +++ b/docs/src/main/asciidoc/verifier_messaging.adoc @@ -1,25 +1,27 @@ == Spring Cloud Contract Verifier Messaging -Spring Cloud Contract Verifier allows you to verify your application that uses messaging as means of communication. -All of our integrations are working with Spring but you can also create one yourself and use it. +Spring Cloud Contract Verifier lets you verify applications that uses 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. === Integrations -You can use one of the four integration configurations: +You can use one of the following four integration configurations: -- Apache Camel -- Spring Integration -- Spring Cloud Stream -- Spring AMQP +* Apache Camel +* Spring Integration +* Spring Cloud Stream +* Spring AMQP -Since we're using Spring Boot then if you have added one of the aforementioned libraries -to the classpath then automatically all the messaging configuration will be set up. +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: Remember to put `@AutoConfigureMessageVerifier` on the base class of your -generated tests. Otherwise messaging part of Spring Cloud Contract Verifier will not work. +generated tests. Otherwise, messaging part of Spring Cloud Contract Verifier does not +work. -IMPORTANT: If you want to use Spring Cloud Stream remember to add a -`org.springframework.cloud:spring-cloud-stream-test-support` dependency. +IMPORTANT: If you want to use Spring Cloud Stream, remember to add a dependency on +`org.springframework.cloud:spring-cloud-stream-test-support`, as shown here: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -37,15 +39,16 @@ IMPORTANT: If you want to use Spring Cloud Stream remember to add a testCompile "org.springframework.cloud:spring-cloud-stream-test-support" ---- - === Manual Integration Testing -The main interface used by the tests is the `org.springframework.cloud.contract.verifier.messaging.MessageVerifier`. -It defines how to send and receive messages. You can create your own implementation to achieve the -same goal. +The main interface used by the tests is +`org.springframework.cloud.contract.verifier.messaging.MessageVerifier`. +It defines how to send and receive messages. You can create your own implementation to +achieve the same goal. -In the a test you can inject a `ContractVerifierMessageExchange` to send and receive messages that follow the contract. -Then add `@AutoConfigureMessageVerifier` to your test, e.g. +In a test, you can inject a `ContractVerifierMessageExchange` to send and receive +messages that follow the contract. Then add `@AutoConfigureMessageVerifier` to your test. +Here's an example: [source,java,indent=0] ---- @@ -60,38 +63,38 @@ public static class MessagingContractTests { } ---- -NOTE: If your tests require stubs as well, then -`@AutoConfigureStubRunner` includes the messaging configuration, so -you only need the one annotation. +NOTE: If your tests require stubs as well, then `@AutoConfigureStubRunner` includes the +messaging configuration, so you only need the one annotation. -=== Publisher side test generation +=== Publisher-Side Test Generation -Having the `input` or `outputMessage` sections in your DSL will result in creation of tests on the publisher's side. By default -JUnit tests will be created, however there is also a possibility to create Spock tests. +Having the `input` or `outputMessage` sections in your DSL results in creation of tests +on the publisher's side. By default, JUnit tests are created. However, there is also a +possibility to create Spock tests. There are 3 main scenarios that we should take into consideration: -- Scenario 1: there is no input message that produces an output one. The output message is triggered by a component -inside the application (e.g. scheduler) -- Scenario 2: the input message triggers an output message -- Scenario 3: the input message is consumed and there is no output message +* Scenario 1: There is no input message that produces an output message. The output +message is triggered by a component inside the application (for example, scheduler). +* Scenario 2: The input message triggers an output message. +* Scenario 3: The input message is consumed and there is no output message. -IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different meanings for different - messaging implementations. For *Stream* and *Integration* it's first resolved as a `destination` of a channel, and then if - there is no such `destination` it's resolved as a channel name. For *Camel* that's a certain component (e.x. `jms`). +IMPORTANT: The destination passed to `messageFrom` or `sentTo` can have different +meanings for different messaging implementations. For *Stream* and *Integration* it is +first resolved as a `destination` of a channel. Then, if there is no such `destination` +it is resolved as a channel name. For *Camel*, that's a certain component (for example, +`jms`). -Example for Camel: +==== Scenario 1: No Input Message -==== Scenario 1 (no input message) - -For the given contract: +Here is an example for Camel. For the given contract: [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_dsl] ---- -The following JUnit test will be created: +The following JUnit test is created: [source,groovy] ---- @@ -105,16 +108,16 @@ And the following Spock test would be created: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_method_test] ---- -==== Scenario 2 (output triggered by input) +==== Scenario 2: Output Triggered by Input -For the given contract: +Here is an example for Camel. For the given contract: [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_dsl] ---- -The following JUnit test will be created: +The following JUnit test is created: [source,groovy] ---- @@ -128,16 +131,16 @@ And the following Spock test would be created: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_message_spock] ---- -==== Scenario 3 (no output message) +==== Scenario 3: No Output Message -For the given contract: +Here is an example for Camel. For the given contract: [source,groovy] ---- include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_dsl] ---- -The following JUnit test will be created: +The following JUnit test is created: [source,groovy] ---- @@ -151,12 +154,14 @@ And the following Spock test would be created: include::{verifier_core_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MessagingMethodBodyBuilderSpec.groovy[tags=trigger_no_output_spock] ---- -=== Consumer Stub Side generation +=== Consumer Stub Generation -Unlike the HTTP part - in Messaging we need to publish the Groovy DSL inside the JAR with a stub. Then it's parsed on the consumer side -and proper stubbed routes are created. +Unlike the HTTP part, in messaging, we need to publish the Groovy DSL inside the JAR with +a stub. Then it is parsed on the consumer side and proper stubbed routes are created. -For more information please consult the Stub Runner Messaging sections. +For more information, see +https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html/#stub-runner-for-messaging[the +Stub Runner Messaging sections]. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven diff --git a/docs/src/main/asciidoc/verifier_setup.adoc b/docs/src/main/asciidoc/verifier_setup.adoc index 63e0982114..383c9d3eed 100644 --- a/docs/src/main/asciidoc/verifier_setup.adoc +++ b/docs/src/main/asciidoc/verifier_setup.adoc @@ -1,15 +1,43 @@ == Spring Cloud Contract Verifier Setup +You can set up Spring Cloud Contract Verifier in either of two ways + +* <> +* <> + +[[gradle-project]] === Gradle Project +To learn how to set up the Gradle project for Spring Cloud Contract Verifier, read the +following sections: + +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> + +[[gradle-prerequisites]] ==== Prerequisites -In order to use Spring Cloud Contract Verifier with WireMock you have to use Gradle or Maven plugin. +In order to use Spring Cloud Contract Verifier with WireMock, you muse use either a +Gradle or a Maven plugin. -WARNING: If you want to use Spock in your projects you have to add separately -the `spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock docs for more information] +WARNING: If you want to use Spock in your projects, you must add separately the +`spock-core` and `spock-spring` modules. Check http://spockframework.github.io/[Spock +docs for more information] -==== Add gradle plugin with dependencies +[[gradle-add-gradle-plugin]] +==== Add Gradle Plugin with Dependencies + +To add a Gradle plugin with dependencies, use code similar to this: [source,groovy,indent=0] ---- @@ -41,10 +69,11 @@ dependencies { } ---- +[[gradle-and-rest-assured]] ==== Gradle and Rest Assured 2.0 -By default Rest Assured 3.x is added to the classpath. However in order to give the users the -opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath. +By default, Rest Assured 3.x is added to the classpath. However, to use Rest Assured 2.x +you can add it to the plugins classpath, as shown here: [source,groovy,indent=0] ---- @@ -68,26 +97,31 @@ depenendencies { } ---- -That way the plugin will automatically see that Rest Assured 2.x is present on the classpath -and will modify the imports accordingly. +That way, the plugin automatically sees that Rest Assured 2.x is present on the classpath +and modifies the imports accordingly. -==== Snapshot versions for Gradle +[[gradle-snapshot-versions]] +==== Snapshot Versions for Gradle -Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build: +Add the additional snapshot repository to your build.gradle to use snapshot versions, +which are automatically uploaded after every successful build, as shown here: [source,groovy,indent=0] ---- include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] } ---- - +[[gradle-add-stubs]] ==== Add stubs -By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory. +By default, Spring Cloud Contract Verifier is looking for stubs in the +`src/test/resources/contracts` directory. -Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test. -We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name. -So with following structure +The directory containing stub definitions is treated as a class name, and each stub +definition is treated as a single test. Spring Cloud Contract Verifier assumes that it +contains at least one level of directories that are to be used as the test class name. +If more than one level of nested directories is present, all except the last one is used +as the package name. For example, with following structure: [source,groovy,indent=0] ---- @@ -95,18 +129,24 @@ src/test/resources/contracts/myservice/shouldCreateUser.groovy src/test/resources/contracts/myservice/shouldReturnUser.groovy ---- -Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods +Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` +with two methods: - `shouldCreateUser()` - `shouldReturnUser()` -==== Run plugin +[[gradle-run-plugin]] +==== Run the Plugin -Plugin registers itself to be invoked before `check` task. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateContractTests` task. +The plugin registers itself to be invoked before a `check` task. If you want it to be +part of your build process, you need to do nothing more. If you just want to generate +tests, invoke the `generateContractTests` task. -==== Default setup +[[gradle-default-setup]] +==== Default Setup -Default Gradle Plugin setup creates the following Gradle part of the build (it's a pseudocode) +The default Gradle Plugin setup creates the following Gradle part of the build (in +pseudocode): [source,groovy,indent=0] ---- @@ -156,9 +196,11 @@ publishing { } ---- -==== Configure plugin +[[gradle-configure-plugin]] +==== Configure Plugin -To change default configuration just add `contracts` snippet to your Gradle config +To change the default configuration, add a `contracts` snippet to your Gradle config, as +shown here: [source,groovy,indent=0] ---- @@ -169,100 +211,141 @@ contracts { } ---- -==== Configuration options +[[gradle-configuration-options]] +==== Configuration Options - - **testMode** - defines mode for acceptance tests. By default MockMvc which is based on Spring's MockMvc. It can also be changed to **JaxRsClient** or to **Explicit** for real HTTP calls. - - **imports** - array with imports that should be included in generated tests (for example ['org.myorg.Matchers']). By default empty array [] - - **staticImports** - array with static imports that should be included in generated tests(for example ['org.myorg.Matchers.*']). By default empty array [] - - **basePackageForTests** - specifies base package for all generated tests. If not set the value will be picked from `baseClassForTests`'s package and from - `packageWithBaseClasses`. If neither of these are set then the value will be set to `org.springframework.cloud.contract.verifier.tests` - - **baseClassForTests** - base class for all generated tests. By default `spock.lang.Specification` if using Spock tests. - - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay. Takes precedence over **baseClassForTests**. - - **baseClassMappings** - explicitly map contract package to a FQN of a base class. Takes precedence over **packageWithBaseClasses** and **baseClassForTests**. - - **ruleClassForTests** - specifies Rule which should be added to generated test classes. - - **ignoredFiles** - Ant matcher allowing defining stub files for which processing should be skipped. By default empty array [] - - **contractsDslDir** - directory containing contracts written using the GroovyDSL. By default `$rootDir/src/test/resources/contracts` - - **generatedTestSourcesDir** - test source directory where tests generated from Groovy DSL should be placed. By default `$buildDir/generated-test-sources/contractVerifier` - - **stubsOutputDir** - dir where the generated WireMock stubs from Groovy DSL should be placed - - **targetFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework +* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring's MockMvc. It can also be changed to *JaxRsClient* or to +*Explicit* for real HTTP calls. +* *imports*: Creates an array with imports that should be included in generated tests +(for example ['org.myorg.Matchers']). By default, it creates an empty array. +* *staticImports*: Creates an array with static imports that should be included in +generated tests(for example ['org.myorg.Matchers.*']). By default, it creates an empty +array. +* *basePackageForTests*: Specifies the base package for all generated tests. If not set, +the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. +If neither of these values are set, then the value is set to +`org.springframework.cloud.contract.verifier.tests`. +* *baseClassForTests*: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is `spock.lang.Specification`. +* *packageWithBaseClasses*: Defines a package where all the base classes reside. This +setting takes precedence over *baseClassForTests*. +* *baseClassMappings*: Explicitly maps a contract package to a FQN of a base class. This +setting takes precedence over *packageWithBaseClasses* and *baseClassForTests*. +* *ruleClassForTests*: Specifies a rule that should be added to the generated test +classes. +* *ignoredFiles*: Uses an `Antmatcher` to allow defining stub files for which processing +should be skipped. By default, it is an empty array. +* *contractsDslDir*: Specifies the directory containing contracts written using the +GroovyDSL. By default, its value is `$rootDir/src/test/resources/contracts`. +* *generatedTestSourcesDir*: Specifies the test source directory where tests generated +from the Groovy DSL should be placed. By default its value is +`$buildDir/generated-test-sources/contractVerifier`. +* *stubsOutputDir*: Specifies the directory where the generated WireMock stubs from +the Groovy DSL should be placed. +* *targetFramework*: Specifies the target test framework to be used. Currently, Spock and +JUnit are supported with JUnit being the default framework. -The following properties are used when you want to provide where the JAR with contract lays +The following properties are used when you want to specify the location of the JAR +containing the contracts: +* *contractDependency*: Specifies the Dependency that provides +`groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` +closure to set it up. +* *contractsPath*: Specifies the path to the jar. If contract dependencies are + downloaded, the path defaults to `groupid/artifactid` where `groupid` is slash + separated. Otherwise, it scans contracts under the provided directory. +* *contractsWorkOffline*: Specifies whether to download the dependencies each time, so +that you can work online. In other words, it specifies whether to reuses the local Maven +repo. - - **contractDependency** - the Dependency that provides `groupid:artifactid:version:classifier` coordinates. You can use the `contractDependency` closure to set it up - - **contractsPath** - if contract deps are downloaded will default to `groupid/artifactid` where `groupid` will be slash separated. Otherwise will scan contracts under provided directory - - **contractsWorkOffline** - in order not to download the dependencies each time you can download them once and work offline afterwards (reuse local Maven repo) +[[gradle-single-base-class]] +==== Single Base Class for All Tests -==== Single base class for all tests - -When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. In this class you need to point to endpoint which should be verified. +When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified. [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/resources/functionalTest/bootSimple/src/test/groovy/org/springframework/cloud/contract/verifier/twitter/places/BaseMockMvcSpec.groovy[tags=base_class,indent=0] ---- -In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class -should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server. +If you use `Explicit` mode, you can use a base class to initialize the whole tested app +as you might see in regular integration tests. If you use the `JAXRSCLIENT` mode, this +base class should also contain a `protected WebTarget webTarget` field. Right now, the +only option to test the JAX-RS API is to start a web server. -==== Different base classes for contracts +[[gradle-different-base-classes]] +==== Different Base Classes for Contracts -If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get -extended by the autogenerated tests. You have two options: +If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options: - - follow a convention by providing the `packageWithBaseClasses` - - provide explicit mapping via `baseClassMappings` +* Follow a convention by providing the `packageWithBaseClasses` +* Provide explicit mapping via `baseClassMappings` -*Convention* +*By Convention* -The convention is such that if you have a contract under e.g. `src/test/resources/contract/foo/bar/baz/` and provide the value of the `packageWithBaseClasses` property -to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. In other words we take last two parts of package -if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage in the `contracts` closure: +The convention is such that if you have a contract under (for example) +`src/test/resources/contract/foo/bar/baz/` and set the value of the +`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract +Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. +Here is an example of how it works in the `contracts` closure: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=package_with_base_classes,indent=0] ---- -*Mapping* +*By Mapping* -You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract. -Let's take a look at the following example: +You can manually map a regular expression of the contract's package to fully qualified +name of the base class for the matched contract. You have to provide a list called +`baseClassMappings` that consists `baseClassMapping` objects that takes a +`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: [source,groovy,indent=0] ---- include::{plugins_path}/spring-cloud-contract-gradle-plugin/src/test/groovy/org/springframework/cloud/contract/verifier/plugin/ContractVerifierSpec.groovy[tags=base_class_mappings,indent=0] ---- -Let's assume that you have contracts under +Let's assume that you have contracts under - `src/test/resources/contract/com/` - `src/test/resources/contract/foo/` - -By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide -the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts -will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`. -==== Invoking generated tests +By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed. +(You could also provide the `packageWithBaseClasses` as a fallback.) That way, the tests +generated from `src/test/resources/contract/com/` contracts extend the +`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. -To ensure that provider side is complaint with defined contracts, you need to invoke: +[[gradle-invoking-generated-tests]] +==== Invoking Generated Tests + +To ensure that the provider side is compliant with defined contracts, you need to invoke: [source,bash,indent=0] ---- ./gradlew generateContractTests test ---- -==== Spring Cloud Contract Verifier on consumer side +[[gradle-consumer]] +==== Spring Cloud Contract Verifier on the Consumer Side -In consumer service you need to configure Spring Cloud Contract Verifier plugin in exactly the same way as in case of provider. If you don't want to use Stub Runner then you need to copy contracts stored in -`src/test/resources/contracts` and generate WireMock json stubs using: +In a consuming service, you need to configure the Spring Cloud Contract Verifier plugin +in exactly the same way as in case of provider. If you do not want to use Stub Runner +then you need to copy contracts stored in `src/test/resources/contracts` and generate +WireMock JSON stubs using: [source,bash,indent=0] ---- ./gradlew generateClientStubs ---- -Note that `stubsOutputDir` option has to be set for stub generation to work. +NOTE: The `stubsOutputDir` option has to be set for stub generation to work. -When present, json stubs can be used in consumer automated tests. +When present, JSON stubs can be used in automated tests of consuming a service. [source,groovy,indent=0] ---- @@ -289,32 +372,54 @@ class LoanApplicationServiceSpec extends Specification { } ---- -Underneath LoanApplication makes a call to FraudDetection service. This request is handled by WireMock server configured using stubs generated by Spring Cloud Contract Verifier. +`LoanApplication` makes a call to `FraudDetection` service. This request is handled by a +WireMock server configured with stubs generated by Spring Cloud Contract Verifier. -=== Using in your Maven project +[[maven-project]] +=== Maven Project +To learn how to set up the Maven project for Spring Cloud Contract Verifier, read the +following sections: + +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> +* <> + +[[maven-add-plugin]] ==== Add maven plugin -Add the Spring Cloud Contract BOM +Add the Spring Cloud Contract BOM in a fashion similar to this: [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=contract_bom,indent=0] ---- -Next, the `Spring Cloud Contract Verifier` Maven plugin +Next, add the `Spring Cloud Contract Verifier` Maven plugin: [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=contract_maven_plugin,indent=0] ---- -You can read more in the https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring Cloud Contract Maven Plugin Docs] +You can read more in the +https://cloud.spring.io/spring-cloud-contract/spring-cloud-contract-maven-plugin/[Spring +Cloud Contract Maven Plugin Documentation]. +[[maven-rest-assured]] ==== Maven and Rest Assured 2.0 -By default Rest Assured 3.x is added to the classpath. However in order to give the users the -opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpath. +By default, Rest Assured 3.x is added to the classpath. However, you can use Rest +Assured 2.x by adding it to the plugins classpath, as shown here: [source,groovy,indent=0] ---- @@ -365,24 +470,29 @@ opportunity to use Rest Assured 2.x it's enough to add it to the plugins classpa ---- -That way the plugin will automatically see that Rest Assured 3.x is present on the classpath -and will modify the imports accordingly. +That way, the plugin automatically sees that Rest Assured 3.x is present on the classpath +and modifies the imports accordingly. +[[maven-snapshot-versions]] ==== Snapshot versions for Maven -For Snapshot / Milestone versions you have to add the following section to your `pom.xml` +For Snapshot and Milestone versions, you have to add the following section to your +`pom.xml`, as shown here: [source,xml,indent=0] ---- include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] ---- +[[maven-add-stubs]] ==== Add stubs -By default Spring Cloud Contract Verifier is looking for stubs in `src/test/resources/contracts` directory. -Directory containing stub definitions is treated as a class name, and each stub definition is treated as a single test. -We assume that it contains at least one directory which will be used as test class name. If there is more than one level of nested directories all except the last one will be used as package name. -So with following structure +By default, Spring Cloud Contract Verifier is looking for stubs in the +`src/test/resources/contracts` directory. The directory containing stub definitions is +treated as a class name, and each stub definition is treated as a single test. We assume +that it contains at least one directory to be used as test class name. If there is more +than one level of nested directories, all except the last one is used as package name. +For example, with following structure: [source,groovy,indent=0] ---- @@ -390,17 +500,24 @@ src/test/resources/contracts/myservice/shouldCreateUser.groovy src/test/resources/contracts/myservice/shouldReturnUser.groovy ---- -Spring Cloud Contract Verifier will create test class `defaultBasePackage.MyService` with two methods - - `shouldCreateUser()` - - `shouldReturnUser()` +Spring Cloud Contract Verifier creates a test class named `defaultBasePackage.MyService` +with two methods +* `shouldCreateUser()` +* `shouldReturnUser()` + +[[maven-run-plugin]] ==== Run plugin -Plugin goal `generateTests` is assigned to be invoked in phase `generate-test-sources`. You have nothing to do as long as you want it to be part of your build process. If you just want to generate tests please invoke `generateTests` goal. +The plugin goal `generateTests` is assigned to be invoked in the phase called +`generate-test-sources`. If you want it to be part of your build process, you need not do +anything. If you just want to generate tests, invoke the `generateTests` goal. +[[maven-configure-plugin]] ==== Configure plugin -To change default configuration just add `configuration` section to plugin definition or `execution` definition. +To change the default configuration, just add a `configuration` section to the plugin +definition or the `execution` definition, as shown here: [source,xml,indent=0] ---- @@ -423,44 +540,69 @@ To change default configuration just add `configuration` section to plugin defin ---- -==== Important configuration options +[[maven-configuration-options]] +==== Configuration Options - - **testMode** - defines mode for acceptance tests. By default `MockMvc` which is based on Spring's MockMvc. It can also be changed to `JaxRsClient` or to `Explicit` for real HTTP calls. - - **basePackageForTests** - specifies base package for all generated tests. If not set the value will be picked from `baseClassForTests`'s package and from - `packageWithBaseClasses`. If neither of these are set then the value will be set to `org.springframework.cloud.contract.verifier.tests` - - **ruleClassForTests** - specifies Rule which should be added to generated test classes. - - **baseClassForTests** - base class for generated tests. By default `spock.lang.Specification` if using Spock tests. - - **contractsDirectory** - directory containing contracts written using the GroovyDSL. By default `/src/test/resources/contracts`. - - **testFramework** - the target test framework to be used; currently Spock and JUnit are supported with JUnit being the default framework - - **packageWithBaseClasses** - instead of providing a fixed value for base class you can provide a package where all the base classes lay. - The convention is such that if you have a contract under `src/test/resources/contract/foo/bar/baz/` and provide the value of this property - to `com.example.base` then we will assume that there is a `BarBazBase` class under `com.example.base` package. Takes precedence - over **baseClassForTests** - - **baseClassMappings** - list of base class mappings that where you have to provide `contractPackageRegex` which is checked - against the package in which the contract lays and `baseClassFQN` that maps to fully qualified name of the base class for the matched - contract. If you have a contract under `src/test/resources/contract/foo/bar/baz/` and map the property `.*` -> `com.example.base.BaseClass` then - the test class generated from these contracts will extend `com.example.base.BaseClass`. Takes precedence over **packageWithBaseClasses** - and **baseClassForTests**. +* *testMode*: Defines the mode for acceptance tests. By default, the mode is MockMvc, +which is based on Spring's MockMvc. It can also be changed to *JaxRsClient* or to +*Explicit* for real HTTP calls. +* *basePackageForTests*: Specifies the base package for all generated tests. If not set, +the value is picked from `baseClassForTests`'s package and from `packageWithBaseClasses`. +If neither of these values are set, then the value is set to +`org.springframework.cloud.contract.verifier.tests`. +* *ruleClassForTests*: Specifies a rule that should be added to the generated test +classes. +* *baseClassForTests*: Creates a base class for all generated tests. By default, if you +use Spock classes, the class is `spock.lang.Specification`. +* *contractsDirectory*: Specifies a directory containing contracts written with the +GroovyDSL. The default directory is `/src/test/resources/contracts`. +* *testFramework*: Specifies the target test framework to be used. Currently, Spock and +JUnit are supported with JUnit being the default framework +* *packageWithBaseClasses*: Defines a package where all the base classes reside. This +setting takes precedence over *baseClassForTests*. The convention is such that, if you +have a contract under (for example) `src/test/resources/contract/foo/bar/baz/` and set +the value of the `packageWithBaseClasses` property to `com.example.base`, then Spring +Cloud Contract Verifier assumes that there is a `BarBazBase` class under the +`com.example.base` package. In other words, the system takes the last two parts of the +package, if they exist, and forms a class with a `Base` suffix. +* *baseClassMappings*: Specifies a list of base class mappings that provide +`contractPackageRegex`, which is checked against the package where the contract is +located, and `baseClassFQN`, which maps to the fully qualified name of the base class for +the matched contract. For example, if you have a contract under +`src/test/resources/contract/foo/bar/baz/` and map the property +`.* -> com.example.base.BaseClass`, then the test class generated from these contracts +extends `com.example.base.BaseClass`. This setting takes precedence over +*packageWithBaseClasses* and *baseClassForTests*. -If you want to download your contract definitions from a Maven repository you can use +If you want to download your contract definitions from a Maven repository, you can use +the following options: - - **contractDependency** - the contract dependency that contains all the packaged contracts - - **contractsPath** - path to concrete contracts in the JAR with packaged contracts. Defaults to `groupid/artifactid` where `gropuid` is slash separated. - - **contractsWorkOffline** - if the dependencies should be downloaded or local Maven only should be reused - - **contractsRepositoryUrl** - *DEPRECATED PROPERTY - please use the `contractRepository` closure* - URL to a repo with the artifacts with contracts, if not provided should use the current Maven ones - - **contractRepository** - closure where you can define properties related to repository with contracts - * **username** - username to be used to connect to the repo - * **password** - username to be used to connect to the repo - * **proxyHost** - proxy host to be used to connect to the repo - * **proxyPort** - proxy port to be used to connect to the repo - * **cacheDownloadedContracts** - if you want to reuse download JARs that contain contract definitions. - We cache only non-snapshot, explicitly provided versions (e.g. `+` or `1.0.0.BUILD-SNAPSHOT` won't get cached). - By default this feature is turned on. +* *contractDependency*: The contract dependency that contains all the packaged contracts. +* *contractsPath*: The path to the concrete contracts in the JAR with packaged contracts. +Defaults to `groupid/artifactid` where `gropuid` is slash separated. +* *contractsWorkOffline*: Dictates whether the dependencies should be downloaded or the +local Maven artifacts should be reused. +* *contractsRepositoryUrl*: *DEPRECATED PROPERTY - please use the `contractRepository` +closure*: URL to a repo with the artifacts that have contracts. If it is not provided, +use the current Maven ones. +* *contractRepository* - Lets you use a closure where you can define properties related +to repository with contracts. +* *username*: The user name to be used to connect to the repo. +* *password*: The password to be used to connect to the repo. +* *proxyHost*: The proxy host to be used to connect to the repo. +* *proxyPort*: The proxy port to be used to connect to the repo. +* *cacheDownloadedContracts* - Specifies whether to reuse downloaded JARs that contain +contract definitions. -==== Single base class for all tests +We cache only non-snapshot, explicitly provided versions (for example +`+` or `1.0.0.BUILD-SNAPSHOT` won't get cached). By default, this feature is turned on. -When using Spring Cloud Contract Verifier in default MockMvc you need to create a base specification for all generated acceptance tests. -In this class you need to point to endpoint which should be verified. +[[maven-single-base]] +==== Single Base Class for All Tests + +When using Spring Cloud Contract Verifier in default MockMvc, you need to create a base +specification for all generated acceptance tests. In this class, you need to point to an +endpoint, which should be verified. [source,groovy,indent=0] ---- @@ -477,51 +619,64 @@ class MvcSpec extends Specification { } ---- -In case of using `Explicit` mode, you can use base class to initialize the whole tested app similarly as in regular integration tests. In case of `JAXRSCLIENT` mode this base class should also contain `protected WebTarget webTarget` field, right now the only option to test JAX-RS API is to start a web server. +If you use `Explicit` mode, you can use a base class to initialize the whole tested app +similarly, as you might find in regular integration tests. If you use the `JAXRSCLIENT` +mode, this base class should also contain a `protected WebTarget webTarget` field. Right +now, the only option to test the JAX-RS API is to start a web server. +[[maven-different-base]] ==== Different base classes for contracts -If your base classes differ between contracts you can tell the Spring Cloud Contract plugin which class should get -extended by the autogenerated tests. You have two options: +If your base classes differ between contracts, you can tell the Spring Cloud Contract +plugin which class should get extended by the autogenerated tests. You have two options: - - follow a convention by providing the `packageWithBaseClasses` - - provide explicit mapping via `baseClassMappings` +* Follow a convention by providing the `packageWithBaseClasses` +* provide explicit mapping via `baseClassMappings` -*Convention* +*By Convention* -The convention is such that if you have a contract under e.g. `src/test/resources/contract/hello/v1/` and provide the value of the `packageWithBaseClasses` property -to `hello` then we will assume that there is a `HelloV1Base` class under `hello` package. In other words we take last two parts of package -if they exist and form a class with a `Base` suffix. Takes precedence over **baseClassForTests**. Example of usage: +The convention is such that if you have a contract under (for example) +`src/test/resources/contract/foo/bar/baz/` and set the value of the +`packageWithBaseClasses` property to `com.example.base`, then Spring Cloud Contract +Verifier assumes that there is a `BarBazBase` class under the `com.example.base` package. +In other words, the system takes the last two parts of the package, if they exist, and +forms a class with a `Base` suffix. This rule takes precedence over *baseClassForTests*. +Here is an example of how it works in the `contracts` closure: [source,xml,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-generated-baseclass/pom.xml[tags=convention,indent=0] ---- -*Mapping* +*By Mapping* -You can manually map a regular expression of the contract's package to fully qualified name of the base class for the matched contract. -You have to provide a list `baseClassMappings` of `baseClassMapping` that takes a `contractPackageRegex` to `baseClassFQN` mapping. -Let's take a look at the following example: +You can manually map a regular expression of the contract's package to fully qualified +name of the base class for the matched contract. You have to provide a list called +`baseClassMappings` that consists `baseClassMapping` objects that takes a +`contractPackageRegex` to `baseClassFQN` mapping. Consider the following example: [source,xml,indent=0] ---- include::{plugins_path}/spring-cloud-contract-maven-plugin/src/test/projects/basic-baseclass-from-mappings/pom.xml[tags=mapping,indent=0] ---- -Let's assume that you have contracts under - - `src/test/resources/contract/com/` - - `src/test/resources/contract/foo/` - -By providing the `baseClassForTests` we have a fallback in case mapping didn't succeed (you could also provide -the `packageWithBaseClasses` as fallback). That way the tests generated from `src/test/resources/contract/com/` contracts -will be extending the `com.example.ComBase` whereas the rest of tests will extend `com.example.FooBase`. +Assume that you have contracts under these two locations: +* `src/test/resources/contract/com/` +* `src/test/resources/contract/foo/` +By providing the `baseClassForTests`, we have a fallback in case mapping did not succeed. +(You can also provide the `packageWithBaseClasses` as a fallback.) That way, the tests +generated from `src/test/resources/contract/com/` contracts extend the +`com.example.ComBase`, whereas the rest of the tests extend `com.example.FooBase`. + +[[maven-invoking-generated-tests]] ==== Invoking generated tests -Spring Cloud Contract Maven Plugin generates verification code into directory `/generated-test-sources/contractVerifier` and attach this directory to `testCompile` goal. +The Spring Cloud Contract Maven Plugin generates verification code in a directory called +`/generated-test-sources/contractVerifier` and attaches this directory to `testCompile` +goal. -For Groovy Spock code use: +For Groovy Spock code, use the following: [source,xml,indent=0] ---- @@ -555,17 +710,17 @@ For Groovy Spock code use: ---- -To ensure that provider side is complaint with defined contracts, you need to invoke `mvn generateTest test` - -==== FAQ with Maven Plugin +To ensure that provider side is compliant with defined contracts, you need to invoke +`mvn generateTest test`. +[[maven-sts]] ==== Maven Plugin and STS -In case you see the following exception while using STS +If you see the following exception while using STS: image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-contract/{branch}/docs/src/main/asciidoc/images/sts_exception.png[STS Exception] -when you click on the marker you should see sth like this +When you click on the error marker you should see something like this: [source,bash] ---- @@ -578,7 +733,7 @@ when you click on the marker you should see sth like this org.sonatype.plexus.build.incremental.ThreadBuildContext.hasDelta(ThreadBuildContext.java:59) at ---- -In order to fix this issue just provide the following section in your `pom.xml` +In order to fix this issue, provide the following section in your `pom.xml`: [source,xml] ---- @@ -616,19 +771,20 @@ In order to fix this issue just provide the following section in your `pom.xml` ---- -==== Spring Cloud Contract Verifier on consumer side +[[maven-consumer]] +==== Spring Cloud Contract Verifier on the Consumer Side -You can actually use the Spring Cloud Contract Verifier also for the consumer side! -You can use the plugin so that it only converts the contracts and generates the stubs. -To achieve that you need to configure Spring Cloud Contract Verifier plugin in exactly -the same way as in case of provider. You need to copy contracts stored in -`src/test/resources/contracts` and generate WireMock json stubs using: -`mvn generateStubs` command. By default generated WireMock mapping is -stored in directory `target/mappings`. Your project should create from -this generated mappings additional artifact with classifier `stubs` for -easy deploy to maven repository. +You can also use the Spring Cloud Contract Verifier for the consumer side. To do so, use +the plugin so that it only converts the contracts and generates the stubs. To achieve +that, you need to configure Spring Cloud Contract Verifier plugin in exactly the same way +as you would for a provider. You need to copy contracts stored in +`src/test/resources/contracts` and generate WireMock JSON stubs using the +`mvn generateStubs` command. By default, the generated WireMock mapping is stored in a +directory named `target/mappings`. From these generated mappings, your project should +create additional artifacts with a classifier of `stubs` for easy deployment to the maven +repository. -Sample configuration: +Here is a sample configuration: [source,xml,indent=0] ---- @@ -647,7 +803,7 @@ Sample configuration: ---- -When present, json stubs can be used in consumer automated tests. +When present, JSON stubs can be used in consumer automated tests, as shown here: [source,groovy,indent=0] ---- @@ -672,38 +828,16 @@ public class LoanApplicationServiceTests { } } ---- +`LoanApplication` makes a call to the `FraudDetection` service. This request is handled +by a WireMock server configured with stubs generated by the Spring Cloud Contract +Verifier. -Underneath `LoanApplication` makes a call to the `FraudDetection` service. This request is handled by -a WireMock server configured using stubs generated by Spring Cloud Contract Verifier. +=== Stubs and Transitive Dependencies -=== Scenarios - -It's possible to handle scenarios with Spring Cloud Contract Verifier. All you need to do is to stick to proper naming convention while creating your contracts. The convention requires to include order number followed by the underscore. - -[source,indent=0] ----- -my_contracts_dir\ - scenario1\ - 1_login.groovy - 2_showCart.groovy - 3_logout.groovy ----- - -Such tree will cause Spring Cloud Contract Verifier generating WireMock's scenario with name `scenario1` and three steps: - - - login marked as `Started` pointing to: - - showCart marked as `Step1` pointing to: - - logout marked as `Step2` which will close the scenario. - -More details about WireMock scenarios can be found under http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html] - -Spring Cloud Contract Verifier will also generate tests with guaranteed order of execution. - -=== Stubs and transitive dependencies - -The Maven and Gradle plugin that we're created are adding the tasks that create the stubs jar for you. What can be problematic -is that when reusing the stubs you can by mistake import all of that stub dependencies! When building a Maven artifact -even though you have a couple of different jars, all of them share one pom: +The Maven and Gradle plugin that add the tasks that create the stubs jar for you. One +problem that arises is that, when reusing the stubs, you can mistakenly import all of +that stub's dependencies. When building a Maven artifact, even though you have a couple +of different jars, all of them share one pom: [source,bash,indent=0] ---- @@ -718,18 +852,53 @@ even though you have a couple of different jars, all of them share one pom: └── ... ---- -There are three possibilities of working with those dependencies so as not to have any issues with transitive dependencies. +There are three possibilities of working with those dependencies so as not to have any +issues with transitive dependencies: + +* Mark all application dependencies as optional +* Create a separate artifactid for the stubs +* Exclude dependencies on the consumer side *Mark all application dependencies as optional* -If in the `github-webhook` application we would mark all of our dependencies as optional, when you include the -`github-webhook` stubs in another application (or when that dependency gets downloaded by Stub Runner) then, since -all of the depenencies are optional, they will not get downloaded. +If, in the `github-webhook` application, you mark all of your dependencies as optional, +when you include the `github-webhook` stubs in another application (or when that +dependency gets downloaded by Stub Runner) then, since all of the dependencies are +optional, they will not get downloaded. -*Create a separate artifactid for stubs* +*Create a separate `artifactid` for the stubs* -If you create a separate artifactid then you can set it up in whatever way you wish. For example by having no dependencies at all. +If you create a separate `artifactid`, then you can set it up in whatever way you wish. +For example, you might decide to have no dependencies at all. *Exclude dependencies on the consumer side* -As a consumer, if you add the stub dependency to your classpath you can explicitly exclude the unwanted dependencies. \ No newline at end of file +As a consumer, if you add the stub dependency to your classpath, you can explicitly +exclude the unwanted dependencies. + +=== Scenarios + +You can handle scenarios with Spring Cloud Contract Verifier. All you need to do is to +stick to the proper naming convention while creating your contracts. The convention +requires including an order number followed by an underscore, as shown in this example: + +[source,indent=0] +---- +my_contracts_dir\ + scenario1\ + 1_login.groovy + 2_showCart.groovy + 3_logout.groovy +---- + +Such a tree causes Spring Cloud Contract Verifier to generate WireMock's scenario with a +name of `scenario1` and the three following steps: + +. login marked as `Started` pointing to... +. showCart marked as `Step1` pointing to... +. logout marked as `Step2` which will close the scenario. + +More details about WireMock scenarios can be found at +http://wiremock.org/stateful-behaviour.html[http://wiremock.org/stateful-behaviour.html] + +Spring Cloud Contract Verifier also generates tests with a guaranteed order of execution. diff --git a/docs/src/main/asciidoc/verifier_stubrunner.adoc b/docs/src/main/asciidoc/verifier_stubrunner.adoc index 4355ee772a..5962cf615f 100644 --- a/docs/src/main/asciidoc/verifier_stubrunner.adoc +++ b/docs/src/main/asciidoc/verifier_stubrunner.adoc @@ -1,16 +1,17 @@ == Spring Cloud Contract Stub Runner -One of the issues that you could have encountered while using Spring Cloud Contract Verifier was to pass the generated WireMock JSON stubs from the server side to the client side (or various clients). - The same takes place in terms of client side generation for messaging. +One of the issues that you might encounter while using Spring Cloud Contract Verifier is +passing the generated WireMock JSON stubs from the server side to the client side (or to +various clients). The same takes place in terms of client-side generation for messaging. -Copying the JSON files / setting the client side for messaging manually is out of the question. - -That's why we'll introduce Spring Cloud Contract Stub Runner that can download and run the stubs -automatically for you. +Copying the JSON files and setting the client side for messaging manually is out of the +question. That is why we introduced Spring Cloud Contract Stub Runner. It can +automatically download and run the stubs for you. === Snapshot versions -Add the additional snapshot repository to your build.gradle to use snapshot versions which are automatically uploaded after every successful build: +Add the additional snapshot repository to your `build.gradle` file to use snapshot +versions, which are automatically uploaded after every successful build: [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -24,16 +25,18 @@ include::{standalone_samples_path}/http-server/pom.xml[tags=repos,indent=0] include::{standalone_samples_path}/http-server/build.gradle[tags=repos,indent=0] ---- -=== Publishing stubs as JARs +=== Publishing Stubs as JARs -The easiest approach would be to centralize the way stubs are kept. For example you can keep them as JARs in a Maven repository. +The easiest approach would be to centralize the way stubs are kept. For example, you can +keep them as jars in a Maven repository. -TIP: For both Maven and Gradle the setup comes out of the box. But you can customize it if you want to. +TIP: For both Maven and Gradle, the setup comes ready to work. However, you can customize +it if you want to. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven ---- - + include::{samples_url}/producer_with_restdocs/pom.xml[tags=skip_jar,indent=0] @@ -53,56 +56,59 @@ include::{stubrunner_core_path}/README.adoc[] === Common -==== Common properties for JUnit and Spring +This section briefly describes common properties, including: -Some of the properties that are repetitive can be set using system properties or configuration properties (for Spring). Here are their names with their default values: +* <> +* <> + +[[common-properties-junit-spring]] +==== Common Properties for JUnit and Spring + +You can set repetitive properties by using system properties or Spring configuration +properties. Here are their names with their default values: [frame="topbot",options="header"] |=============== | Property name | Default value | Description -|stubrunner.minPort|10000| Minimal value of a port for a started WireMock with stubs -|stubrunner.maxPort|15000| Minimal value of a port for a started WireMock with stubs -|stubrunner.repositoryRoot|| Maven repo url. If blank then will call the local maven repo -|stubrunner.classifier|stubs| Default classifier for the stub artifacts -|stubrunner.workOffline|false| If true then will not contact any remote repositories to download stubs -|stubrunner.ids|| Array of Ivy notation stubs to download -|stubrunner.username|| Optional username to access the tool that stores the JARs with stubs -|stubrunner.password|| Optional password to access the tool that stores the JARs with stubs -|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs per each consumer instead of registering all stubs for every consumer -|stubrunner.consumerName|| If you want to use stubs per consumer and want to override the consumer name just change this value +|stubrunner.minPort|10000| Minimum value of a port for a started WireMock with stubs. +|stubrunner.maxPort|15000| Maximum value of a port for a started WireMock with stubs. +|stubrunner.repositoryRoot|| Maven repo URL. If blank, then call the local maven repo. +|stubrunner.classifier|stubs| Default classifier for the stub artifacts. +|stubrunner.workOffline|false| If true, then do not contact any remote repositories to +download stubs. +|stubrunner.ids|| Array of Ivy notation stubs to download. +|stubrunner.username|| Optional username to access the tool that stores the JARs with +stubs. +|stubrunner.password|| Optional password to access the tool that stores the JARs with +stubs. +|stubrunner.stubsPerConsumer|false| Set to `true` if you want to use different stubs for +each consumer instead of registering all stubs for every consumer. +|stubrunner.consumerName|| If you want to use a stub for each consumer and want to +override the consumer name just change this value. |=============== -==== Stub runner stubs ids +[[stub-runner-stub-ids]] +==== Stub Runner Stubs IDs -You can provide the stubs to download via the `stubrunner.ids` system property. They follow the following pattern: +You can provide the stubs to download via the `stubrunner.ids` system property. They +follow this pattern: [source,java,indent=0] ---- groupId:artifactId:version:classifier:port ---- -`version`, `classifier` and `port` are optional. +Note that `version`, `classifier` and `port` are optional. -* If you don't provide the `port` then a random one will be picked -* If you don't provide the `classifier` then the default one will be taken. (NOTE that you can pass an empty classifier like this `groupId:artifactId:version:`) -* If you don't provide the `version` then the `+` will be passed and the latest one will be downloaded +* If you do not provide the `port`, a random one will be picked. +* If you do not provide the `classifier`, the default is used. (Note that you can +pass an empty classifier this way: `groupId:artifactId:version:`). +* If you do not provide the `version`, then the `+` will be passed and the latest one is +downloaded. -Where `port` means the port of the WireMock server. +`port` means the port of the WireMock server. -IMPORTANT: Starting from version 1.0.4 as a version you can provide a range of versions that you would like -the Stub Runner to take into consideration. You can read more about the https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning ranges here]. - -Taken from http://download.eclipse.org/aether/aether-core/0.9.0/apidocs/org/eclipse/aether/util/version/GenericVersionScheme.html[Aether Docs]: - -> This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments. The characters '-', '_', and '.' as well as the mere -> transitions from digit to letter and vice versa delimit the version segments. Delimiters are treated as equivalent. -> -> Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and case-insensitively. However, the following qualifier strings are -> recognized and treated specially: "alpha" = "a" < "beta" = "b" < "milestone" = "m" < "cr" = "rc" < "snapshot" < "final" = "ga" < "sp". All of those well-known qualifiers -> are considered smaller/older than other strings. An empty segment/string is equivalent to 0. -> -> In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to denote the smallest/greatest version having a given prefix. -> For example, "1.2.min" denotes the smallest version in the 1.2 line, "1.2.max" denotes the greatest version in the 1.2 line. A version range of the form "[M.N.*]" is short for "[M.N.min, M.N.max]". -> -> Numbers and strings are considered incomparable against each other. Where version segments of different kind would collide, comparison will instead assume that the previous -> segments are padded with trailing 0 or "ga" segments, respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1". \ No newline at end of file +IMPORTANT: Starting with version 1.0.4, you can provide a range of versions that you +would like the Stub Runner to take into consideration. You can read more about the +https://wiki.eclipse.org/Aether/New_and_Noteworthy#Version_Ranges[Aether versioning +ranges here]. diff --git a/docs/src/main/asciidoc/verifier_stubrunner_msg.adoc b/docs/src/main/asciidoc/verifier_stubrunner_msg.adoc index 65744013a4..5402d775ec 100644 --- a/docs/src/main/asciidoc/verifier_stubrunner_msg.adoc +++ b/docs/src/main/asciidoc/verifier_stubrunner_msg.adoc @@ -1,12 +1,13 @@ == Stub Runner for Messaging -Stub Runner has the functionality to run the published stubs in memory. It can integrate with the following frameworks out of the box +Stub Runner can run the published stubs in memory. It can integrate with the following +frameworks: -- Spring Integration -- Spring Cloud Stream -- Spring AMQP +* Spring Integration +* Spring Cloud Stream +* Spring AMQP -It also provides points of entry to integrate with any other solution on the market. +It also provides entry points to integrate with any other solution on the market. IMPORTANT: If you have multiple frameworks on the classpath Stub Runner will need to define which one should be used. Let's assume that you have both AMQP, Spring Cloud Stream and Spring Integration @@ -15,39 +16,48 @@ That way the only remaining framework is Spring AMQP. === Stub triggering -To trigger a message it's enough to use the `StubTrigger` interface: +To trigger a message, use the `StubTrigger` interface: [source,groovy] ---- include::{stubrunner_core_path}/src/main/java/org/springframework/cloud/contract/stubrunner/StubTrigger.java[lines=16..-1] ---- -For convenience the `StubFinder` interface extends `StubTrigger` so it's enough to use only one in your tests. +For convenience, the `StubFinder` interface extends `StubTrigger`, so you only need one +or the other in your tests. `StubTrigger` gives you the following options to trigger a message: -==== Trigger by label +* <> +* <> +* <> +* <> + +[[trigger-label]] +==== Trigger by Label [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- - -==== Trigger by group and artifact ids +[[trigger-group-artifact-ids]] +==== Trigger by Group and Artifact Ids [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_group_artifact,indent=0] ---- -==== Trigger by artifact ids +[[trigger-artifact-ids]] +==== Trigger by Artifact Ids [source,groovy] ---- include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=trigger_artifact,indent=0] ---- -==== Trigger all messages +[[trigger-all-messages]] +==== Trigger All Messages [source,groovy] ---- @@ -58,4 +68,4 @@ include::{tests_path}/spring-cloud-contract-stub-runner-integration/README.adoc[ include::{tests_path}/spring-cloud-contract-stub-runner-stream/README.adoc[] -include::{tests_path}/spring-cloud-contract-stub-runner-amqp/README.adoc[] \ No newline at end of file +include::{tests_path}/spring-cloud-contract-stub-runner-amqp/README.adoc[] diff --git a/tests/spring-cloud-contract-stub-runner-amqp/README.adoc b/tests/spring-cloud-contract-stub-runner-amqp/README.adoc index 40476c4c0d..ab5fb80b95 100644 --- a/tests/spring-cloud-contract-stub-runner-amqp/README.adoc +++ b/tests/spring-cloud-contract-stub-runner-amqp/README.adoc @@ -1,35 +1,36 @@ === Stub Runner Spring AMQP -Spring Cloud Contract Verifier Stub Runner's messaging module provides an easy way to integrate with Spring AMQP's Rabbit Template. -For the provided artifacts it will automatically download the stubs and register the required -routes. +Spring Cloud Contract Verifier Stub Runner's messaging module provides an easy way to +integrate with Spring AMQP's Rabbit Template. For the provided artifacts, it +automatically downloads the stubs and registers the required routes. -The integration tries to work standalone, that is without interaction with a running RabbitMQ message broker. -It expects a `RabbitTemplate` on the application context and uses it as a spring boot test `@SpyBean`. -Thus it can use the mockito spy functionality to verify and introspect messages sent by the application. +The integration tries to work standalone (that is, without interaction with a running +RabbitMQ message broker). It expects a `RabbitTemplate` on the application context and +uses it as a spring boot test named `@SpyBean`. As a result, it can use the mockito spy +functionality to verify and inspect messages sent by the application. -On the message consumer side, it considers all `@RabbitListener` annotated endpoints as well as all `SimpleMessageListenerContainer`s on the application context. +On the message consumer side, the stub runner considers all `@RabbitListener` annotated +endpoints and all `SimpleMessageListenerContainer` objects on the application context. -As messages are usually sent to exchanges in AMQP the message contract contains the exchange name as the destination. -Message listeners on the other side are bound to queues. Bindings connect an exchange to a queue. -If message contracts are triggered the Spring AMQP stub runner integration will look for bindings on the application context that match this exchange. -Then it collects the queues from the Spring exchanges and tries to find messages listeners bound to these queues. -The message is triggered to all matching message listeners. +As messages are usually sent to exchanges in AMQP, the message contract contains the +exchange name as the destination. Message listeners on the other side are bound to +queues. Bindings connect an exchange to a queue. If message contracts are triggered, the +Spring AMQP stub runner integration looks for bindings on the application context that +match this exchange. Then it collects the queues from the Spring exchanges and tries to +find message listeners bound to these queues. The message is triggered for all matching +message listeners. -==== Adding it to the project +==== Adding the Runner to the Project -It's enough to have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and set the property `stubrunner.amqp.enabled=true`. -Remember to annotate your test class with `@AutoConfigureStubRunner`. +You can have both Spring AMQP and Spring Cloud Contract Stub Runner on the classpath and +set the property `stubrunner.amqp.enabled=true`. Remember to annotate your test class +with `@AutoConfigureStubRunner`. -IMPORTANT: If you already have Stream and Integration on the classpath you need -to disable them explicitly via `stubrunner.stream.enabled=false` and `stubrunner.integration.enabled=false` -properties +IMPORTANT: If you already have Stream and Integration on the classpath, you need +to disable them explicitly by setting the `stubrunner.stream.enabled=false` and +`stubrunner.integration.enabled=false` properties. -==== Examples - -===== Stubs structure - -Let us assume that we have the following Maven repository with a deployed stubs for the +Assume that you have the following Maven repository with a deployed stubs for the `spring-cloud-contract-amqp-test` application. [source,bash,indent=0] @@ -46,7 +47,7 @@ Let us assume that we have the following Maven repository with a deployed stubs └── maven-metadata-local.xml ---- -And the stubs contain the following structure: +Further assume that the stubs contain the following structure: [source,bash,indent=0] ---- @@ -56,14 +57,14 @@ And the stubs contain the following structure: └── shouldProduceValidPersonData.groovy ---- -Let's consider the following contract: +Consider the following contract: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=amqp_contract,indent=0] ---- -and the following Spring configuration: +Now consider the following Spring configuration: [source,yaml] ---- @@ -72,41 +73,46 @@ include::src/test/resources/application.yml[] ===== Triggering the message -So to trigger a message using the contract above we'll use the `StubTrigger` interface as follows. +To trigger a message using the contract above, use the `StubTrigger` interface as +follows: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- -The message has the destination `contract-test.exchange` so the Spring AMQP stub runner integration looks for bindings related to this exchange. +The message has a destination of `contract-test.exchange`, so the Spring AMQP stub runner +integration looks for bindings related to this exchange. [source,java] ---- include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_binding,indent=0] ---- -The binding definition binds the queue `test.queue`. -So the following listener definition is a match and is invoked with the contract message. +The binding definition binds the queue `test.queue`. As a result, the following listener +definition is matched and invoked with the contract message. [source,java] ---- include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/AmqpMessagingApplication.java[tags=amqp_listener,indent=0] ---- -Also, the following annotated listener represents a match and would be invoked. +Also, the following annotated listener matches and is invoked: [source,java] ---- include::src/main/java/org/springframework/cloud/contract/stubrunner/messaging/amqp/MessageSubscriberRabbitListener.java[tags=amqp_annotated_listener,indent=0] ---- -NOTE: The message is directly handed over to the `onMessage` method of the `MessageListener` associated with the matching `SimpleMessageListenerContainer`. +NOTE: The message is directly handed over to the `onMessage` method of the +`MessageListener` associated with the matching `SimpleMessageListenerContainer`. ===== Spring AMQP Test Configuration -In order to avoid that Spring AMQP is trying to connect to a running broker during our tests we configure a mock `ConnectionFactory`. +In order to avoid Spring AMQP trying to connect to a running broker during our tests +configure a mock `ConnectionFactory`. -To disable the mocked ConnectionFactory set the property `stubrunner.amqp.mockConnection=false` +To disable the mocked ConnectionFactory, set the following property: +`stubrunner.amqp.mockConnection=false` [source,yaml] ---- diff --git a/tests/spring-cloud-contract-stub-runner-integration/README.adoc b/tests/spring-cloud-contract-stub-runner-integration/README.adoc index c8bcb9fb46..baba7e3ab3 100644 --- a/tests/spring-cloud-contract-stub-runner-integration/README.adoc +++ b/tests/spring-cloud-contract-stub-runner-integration/README.adoc @@ -3,25 +3,22 @@ === Stub Runner Integration -Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to integrate with Spring Integration. -For the provided artifacts it will automatically download the stubs and register the required -routes. +Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to +integrate with Spring Integration. For the provided artifacts, it automatically downloads +the stubs and registers the required routes. -==== Adding it to the project +==== Adding the Runner to the Project -It's enough to have both Spring Integration and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with `@AutoConfigureStubRunner`. +You can have both Spring Integration and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. ==== Disabling the functionality -If you need to disable this functionality just pass `stubrunner.integration.enabled=false` property. +If you need to disable this functionality, set the +`stubrunner.integration.enabled=false` property. -==== Examples - -===== Stubs structure - -Let us assume that we have the following Maven repository with a deployed stubs for the -`integrationService` application. +Assume that you have the following Maven repository with deployed stubs for the +`integrationService` application: [source,bash,indent=0] ---- @@ -39,7 +36,7 @@ Let us assume that we have the following Maven repository with a deployed stubs └── maven-metadata-local.xml ---- -And the stubs contain the following structure: +Further assume the stubs contain the following structure: [source,bash,indent=0] ---- @@ -53,14 +50,14 @@ And the stubs contain the following structure: └── mappings ---- -Let's consider the following contracts (let' number it with *1*): +Consider the following contracts (numbered *1*): [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ---- -and number *2* +Now consider *2*: [source,groovy] ---- @@ -74,56 +71,66 @@ and the following Spring Integration Route: include::src/test/resources/integration-context.xml[lines=1;18..-1] ---- +These examples lend themselves to three scenarios: +* <> +* <> +* <> + +[[integration-scenario-1]] ===== Scenario 1 (no input message) -So as to trigger a message via the `return_book_1` label we'll use the `StubTigger` interface as follows +To trigger a message via the `return_book_1` label, use the `StubTigger` interface, as +follows: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- -Next we'll want to listen to the output of the message sent to `{output_name}` +To listen to the output of the message sent to `{output_name}`: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ---- -And the received message would pass the following assertions +The received message would pass the following assertions: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ---- +[[integration-scenario-1]] ===== Scenario 2 (output triggered by input) -Since the route is set for you it's enough to just send a message to the `{output_name}` destination. +Since the route is set for you, you can send a message to the `{output_name}` +destination: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_send,indent=0] ---- -Next we'll want to listen to the output of the message sent to `{output_name}` +To listen to the output of the message sent to `{output_name}`: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive,indent=0] ---- -And the received message would pass the following assertions +The received message passes the following assertions: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/integration/IntegrationStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ---- +[[integration-scenario-3]] ===== Scenario 3 (input with no output) -Since the route is set for you it's enough to just send a message to the `{input_name}` destination. +Since the route is set for you, you can send a message to the `{input_name}` destination: [source,groovy] ---- diff --git a/tests/spring-cloud-contract-stub-runner-stream/README.adoc b/tests/spring-cloud-contract-stub-runner-stream/README.adoc index 9e0f1cf08d..fad7b0ad93 100644 --- a/tests/spring-cloud-contract-stub-runner-stream/README.adoc +++ b/tests/spring-cloud-contract-stub-runner-stream/README.adoc @@ -1,15 +1,15 @@ === Stub Runner Stream -Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to integrate with Spring Stream. -For the provided artifacts it will automatically download the stubs and register the required -routes. +Spring Cloud Contract Verifier Stub Runner's messaging module gives you an easy way to +integrate with Spring Stream. For the provided artifacts, it automatically downloads the +stubs and registers the required routes. -WARNING: In Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings are resolved -first as a `destination` of a channel, and then if there is no such `destination` it's resolved as a -channel name. +WARNING: If Stub Runner's integration with Stream the `messageFrom` or `sentTo` Strings +are resolved first as a `destination` of a channel and no such `destination` exists, the +destination is resolved as a channel name. -IMPORTANT: If you want to use Spring Cloud Stream remember to add a -`org.springframework.cloud:spring-cloud-stream-test-support` dependency. +IMPORTANT: If you want to use Spring Cloud Stream remember, to add a dependency on +`org.springframework.cloud:spring-cloud-stream-test-support`. [source,xml,indent=0,subs="verbatim,attributes",role="primary"] .Maven @@ -27,21 +27,18 @@ IMPORTANT: If you want to use Spring Cloud Stream remember to add a testCompile "org.springframework.cloud:spring-cloud-stream-test-support" ---- -==== Adding it to the project +==== Adding the Runner to the Project -It's enough to have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on classpath. -Remember to annotate your test class with `@AutoConfigureStubRunner`. +You can have both Spring Cloud Stream and Spring Cloud Contract Stub Runner on the +classpath. Remember to annotate your test class with `@AutoConfigureStubRunner`. ==== Disabling the functionality -If you need to disable this functionality just pass `stubrunner.stream.enabled=false` property. +If you need to disable this functionality, set the `stubrunner.stream.enabled=false` +property. -==== Examples - -===== Stubs structure - -Let us assume that we have the following Maven repository with a deployed stubs for the -`streamService` application. +Assume that you have the following Maven repository with a deployed stubs for the +`streamService` application: [source,bash,indent=0] ---- @@ -59,7 +56,7 @@ Let us assume that we have the following Maven repository with a deployed stubs └── maven-metadata-local.xml ---- -And the stubs contain the following structure: +Further assume the stubs contain the following structure: [source,bash,indent=0] ---- @@ -73,77 +70,89 @@ And the stubs contain the following structure: └── mappings ---- -Let's consider the following contracts (let' number it with *1*): +Consider the following contracts (numbered *1*): [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0] ---- -and number *2* +Now consider *2*: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl_2,indent=0] ---- -and the following Spring configuration: +Now consider the following Spring configuration: [source,yaml] ---- include::src/test/resources/application.yml[] ---- +These examples lend themselves to three scenarios: +* <> +* <> +* <> + +[[stream-scenario-1]] ===== Scenario 1 (no input message) -So as to trigger a message via the `return_book_1` label we'll use the `StubTrigger` interface as follows +To trigger a message via the `return_book_1` label, use the `StubTrigger` interface as +follows: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger,indent=0] ---- -Next we'll want to listen to the output of the message sent to a channel whose `destination` is `returnBook` +To listen to the output of the message sent to a channel whose `destination` is +`returnBook`: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_receive,indent=0] ---- -And the received message would pass the following assertions +The received message passes the following assertions: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_trigger_message,indent=0] ---- +[[stream-scenario-2]] ===== Scenario 2 (output triggered by input) -Since the route is set for you it's enough to just send a message to the `bookStorage` `destination`. +Since the route is set for you, you can send a message to the `bookStorage` +`destination`: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_send,indent=0] ---- -Next we'll want to listen to the output of the message sent to `returnBook` +To listen to the output of the message sent to `returnBook`: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive,indent=0] ---- -And the received message would pass the following assertions +The received message passes the following assertions: [source,groovy] ---- include::src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=client_receive_message,indent=0] ---- +[[stream-scenario-3]] ===== Scenario 3 (input with no output) -Since the route is set for you it's enough to just send a message to the `{output_name}` destination. +Since the route is set for you, you can send a message to the `{output_name}` +destination: [source,groovy] ----