### Maven log output for stub and application installation
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
Example Maven log output showing the build and installation of the application and stub artifacts into the local Maven repository.
```bash
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
```
--------------------------------
### Start bash script with set -x
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Starts a bash script with trace output enabled. This is the beginning of the example for running contract tests against existing middleware.
```bash
#!/bin/bash
set -x
```
--------------------------------
### Install contract definitions locally
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/cdc-external-repo.adoc
Install the contract definitions into the local Maven repository.
```bash
$ ./mvnw clean install
```
--------------------------------
### Stub Runner build log output
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/first-application.adoc
Example build log entries showing Stub Runner resolving and unpacking the stub artifact and then starting all stubs. The log shows the resolved version, the artifact coordinates, and the final running stubs with their port.
```bash
2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
```
--------------------------------
### JAR version example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-do-stubs-versioning.adoc
Example of a JAR version generated during continuous delivery, built on 20.10.2016 at 20:15:21.
```groovy
1.0.0.20161020-201521-RELEASE
```
--------------------------------
### Stub Runner Boot Eureka example
Source: https://github.com/spring-attic/spring-cloud-contract/wiki/Spring-Cloud-Contract-1.0.0-M2-Release-Notes
Example class with annotations to enable Stub Runner server and Eureka client. When executed with the provided properties, stubs are downloaded and registered in Eureka.
```java
@SpringBootApplication
@EnableStubRunnerServer
@EnableEurekaClient
@AutoConfigureStubRunner
public class StubRunnerBootEurekaExample {
public static void main(String[] args) {
SpringApplication.run(StubRunnerBootEurekaExample.class, args);
}
}
```
--------------------------------
### Install producer stubs locally (consumer workflow)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/spring-cloud-contract-stub-runner/src/test/resources/git_samples/contract-git/README.adoc
Run from the root of the contracts repo to install the producer's stubs locally. After this, the target directory contains beer-api-producer-external-0.0.1-SNAPSHOT-stubs.jar, which can be referenced as com.example:server:+:stubs in consumer tests.
```bash
cd src/main/resources/contracts/com/example/beer-api-producer-external/1.0.0
mvn clean install -DskipTests
```
--------------------------------
### Install producer stubs locally with Maven
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/cdc-external-repo.adoc
Install the producer stubs locally from the cloned contracts repository. Run this from the producer contracts directory before setting up Stub Runner in the consumer tests.
```bash
$ cd src/main/resource/contracts/producer
$ ./mvnw clean install
```
--------------------------------
### Default Gradle Plugin Setup
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/gradle-project.adoc
Pseudocode representing the default configuration and task setup created by the Spring Cloud Contract Gradle plugin.
```groovy
contracts {
testFramework ='JUNIT'
testMode = 'MockMvc'
generatedTestJavaSourcesDir = project.file("${project.buildDir}/generated-test-sources/contractTest/java")
generatedTestGroovySourcesDir = project.file("${project.buildDir}/generated-test-sources/contractTest/groovy")
generatedTestResourcesDir = project.file("${project.buildDir}/generated-test-resources/contracts")
contractsDslDir = project.file("${project.projectDir}/src/contractTest/resources/contracts")
basePackageForTests = 'org.springframework.cloud.verifier.tests'
stubsOutputDir = project.file("${project.buildDir}/stubs")
sourceSet = null
}
def verifierStubsJar = tasks.register(type: Jar, name: 'verifierStubsJar', dependsOn: 'generateClientStubs') {
baseName = project.name
classifier = contracts.stubsSuffix
from contractVerifier.stubsOutputDir
}
def copyContracts = tasks.register(type: Copy, name: 'copyContracts') {
from contracts.contractsDslDir
into contracts.stubsOutputDir
}
verifierStubsJar.dependsOn copyContracts
```
--------------------------------
### Maven install output confirming stubs jar installation
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
The key line from the Maven install output confirming that the stubs jar for http-server has been installed into the local Maven repository. This is the line that verifies the stubs are available for the consumer side.
```bash
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
```
--------------------------------
### Stop and start Docker infra
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Commands to stop and start Docker infrastructure for nodejs and artifactory.
```bash
# Stop docker infra (nodejs, artifactory)
$ ./stop_infra.sh
# Start docker infra (nodejs, artifactory)
$ ./setup_infra.sh
```
```bash
# Kill & Run app
$ pkill -f "node app"
$ nohup node app &
```
```bash
# Prepare environment variables
$ SC_CONTRACT_DOCKER_VERSION="..."
$ APP_IP="192.168.0.100"
$ APP_PORT="3000"
$ ARTIFACTORY_PORT="8081"
$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
$ CURRENT_DIR="$( pwd )"
$ CURRENT_FOLDER_NAME=${PWD##*/}
$ PROJECT_VERSION="0.0.1.RELEASE"
```
```bash
# Run contract tests
$ docker run --rm -e "APPLICATION_BASE_URL=${APPLICATION_BASE_URL}" -e "PUBLISH_ARTIFACTS=true" -e "PROJECT_NAME=${CURRENT_FOLDER_NAME}" -e "REPO_WITH_BINARIES_URL=${ARTIFACTORY_URL}" -e "PROJECT_VERSION=${PROJECT_VERSION}" -v "${CURRENT_DIR}/contracts/:/contracts:ro" -v "${CURRENT_DIR}/node_modules/spring-cloud-contract/output:/spring-cloud-contract-output/" springcloud/spring-cloud-contract:"${SC_CONTRACT_DOCKER_VERSION}"
```
--------------------------------
### Git protocol URL examples
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-use-git-as-storage.adoc
Shows how to prefix repository URLs with 'git://' to use Git as the storage source. Supports file, HTTPS, and SSH protocols.
```text
git://file:///foo/bar
git://https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
```
--------------------------------
### Generated stub JAR version example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-do-stubs-versioning.adoc
Example of the generated stub JAR version corresponding to the JAR version above.
```groovy
1.0.0.20161020-201521-RELEASE-stubs.jar
```
--------------------------------
### Contract Directory Structure Example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/gradle-project.adoc
Example of the directory structure used by Spring Cloud Contract Verifier to map contract definitions to test classes.
```groovy
src/contractTest/resources/contracts/myservice/shouldCreateUser.groovy
src/contractTest/resources/contracts/myservice/shouldReturnUser.groovy
```
--------------------------------
### Stub Runner Boot configuration for Spring Cloud CLI
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-boot.adoc
Example stubrunner.yml configuration file for running stubs locally. Place this file in the current working directory, in a config subdirectory, or in ~/.spring-cloud. Then run 'spring cloud stubrunner' to start the server on port 8750.
```yml
spring.cloud.contract.stubrunner:
stubsMode: LOCAL
ids:
- com.example:beer-api-producer:+:9876
```
--------------------------------
### Integration Stub Repository and Stub Structure
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
These directory listings show the expected Maven repository layout for the integrationService stubs and the internal structure of the stubs jar. They are used to illustrate the setup for the Spring Integration messaging example.
```bash
└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── integrationService
├── 0.0.1-SNAPSHOT
│ ├── integrationService-0.0.1-SNAPSHOT.pom
│ ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
│ └── maven-metadata-local.xml
└── maven-metadata-local.xml
```
```bash
├── META-INF
│ └── MANIFEST.MF
└── repository
├── accurest
│ └── bookReturned1.groovy
└── mappings
```
--------------------------------
### Stream contract example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
Contract example for the Spring Cloud Stream integration.
```groovy
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/stream/StreamStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
```
--------------------------------
### Stream application.yml
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
Spring configuration example for the Stream integration.
```yaml
include::{tests_path}/spring-cloud-contract-stub-runner-stream/src/test/resources/application.yml[]
```
--------------------------------
### Annotation-based mappingsOutputFolder
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
Shows the @AutoConfigureStubRunner annotation with the mappingsOutputFolder property to dump mappings to files. The example uses ids 'a.b.c:loanIssuance,a.b.c:fraudDetectionServer' and output folder 'target/outputmappings/'.
```java
@AutoConfigureStubRunner(ids="a.b.c:loanIssuance,a.b.c:fraudDetectionServer",
mappingsOutputFolder = "target/outputmappings/")
```
--------------------------------
### Kotlin: Multiple contracts in one file
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-multiple.adoc
Kotlin example showing how to define multiple contracts using the Contract DSL. It uses an array of contracts, with one contract having a name and others without.
```kotlin
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
arrayOf(
contract {
name("should post a user")
// ...
},
contract {
// ...
},
contract {
// ...
}
)
```
--------------------------------
### Stub Runner startup log output
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Console output indicating that Stub Runner is ready to accept requests after starting.
```bash
o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.4.3 (camel-1) started in 0.007 seconds
o.s.c.c.s.server.StubRunnerBoot : Started StubRunnerBoot in 14.483 seconds (JVM running for 18.666)
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms
```
--------------------------------
### WireMock mappings JSON example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
Shows an example of the mappings file content for WireMock, containing a mapping with id, request, response, and uuid fields. The response returns status 200 and body 'fraudDetectionServer'.
```json
[{
"id" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7",
"request" : {
"url" : "/name",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "fraudDetectionServer"
},
"uuid" : "f9152eb9-bf77-4c38-8289-90be7d10d0d7"
},
...
]
```
--------------------------------
### Contract with matchers (Groovy and YAML)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/dsl-dynamic-properties.adoc
Example contract definition using matchers in both Groovy and YAML formats. The Groovy version is the primary example, and the YAML version is the secondary. The matchers section defines dynamic portions for request and response.
```groovy
include::{verifier_root_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/MockMvcMethodBodyBuilderWithMatchersSpec.groovy[tags=matchers,indent=0]
```
```yaml
include::{verifier_root_path}/src/test/resources/yml/contract_matchers.yml[indent=0]
```
--------------------------------
### Maven repository stub layout
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
Example Maven repository layout with deployed stubs for the streamService application.
```bash
└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── streamService
├── 0.0.1-SNAPSHOT
│ ├── streamService-0.0.1-SNAPSHOT.pom
│ ├── streamService-0.0.1-SNAPSHOT-stubs.jar
│ └── maven-metadata-local.xml
└── maven-metadata-local.xml
```
--------------------------------
### Maven build output showing stub generation and installation
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
Output from running the Maven build for the http-server module. It shows the spring-cloud-contract-maven-plugin generating stubs, the maven-jar-plugin building the main jar, the spring-boot-maven-plugin repackaging, and the maven-install-plugin installing both the main jar and the stubs jar into the local Maven repository.
```bash
[INFO] --- spring-cloud-contract-maven-plugin:1.0.0.BUILD-SNAPSHOT:generateStubs (default-generateStubs) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ http-server ---
[INFO] Building jar: /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.BUILD-SNAPSHOT:repackage (default) @ http-server ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ http-server ---
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.jar
[INFO] Installing /some/path/http-server/pom.xml to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT.pom
[INFO] Installing /some/path/http-server/target/http-server-0.0.1-SNAPSHOT-stubs.jar to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
```
--------------------------------
### Download and run Stub Runner Server fat jar
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-boot.adoc
Commands to download a standalone JAR from Maven (example for version 2.0.1.RELEASE) and run it with configuration properties for stubrunner ids and repository root.
```bash
$ wget -O stub-runner.jar 'https://search.maven.org/remotecontent?filepath=org/springframework/cloud/spring-cloud-contract-stub-runner-boot/2.0.1.RELEASE/spring-cloud-contract-stub-runner-boot-2.0.1.RELEASE.jar'
$ java -jar stub-runner.jar --spring.cloud.contract.stubrunner.ids=... --spring.cloud.contract.stubrunner.repositoryRoot=...
```
--------------------------------
### Configuring Plugin Settings
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/gradle-project.adoc
Example of overriding default plugin configuration values within the contracts block.
```groovy
contracts {
testMode = 'MockMvc'
baseClassForTests = 'org.mycompany.tests'
generatedTestJavaSourcesDir = project.file('src/generatedContract')
}
```
--------------------------------
### Base Class with Full Context Setup (Java)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/maven-project.adoc
Base class for setting up the whole Spring context in MockMvc mode. Uses @SpringBootTest with a random port and injects the WebApplicationContext to configure RestAssuredMockMvc.
```java
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = SomeConfig.class, properties="some=property")
public abstract class BaseTestClass {
@Autowired
WebApplicationContext context;
@Before
public void setup() {
RestAssuredMockMvc.webAppContextSetup(this.context);
}
}
```
--------------------------------
### Stub structure
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
Example stub structure inside the stubs jar.
```bash
├── META-INF
│ └── MANIFEST.MF
└── repository
├── accurest
│ └── bookReturned1.groovy
└── mappings
```
--------------------------------
### Package stubs with Maven assembly or Gradle stubsJar task
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/provider-contract-testing-rest-docs.adoc
Configures the build to package generated stubs into a JAR. The Maven setup uses the maven-assembly-plugin with a descriptor at src/assembly/stub.xml, while the Gradle setup defines a stubsJar task that depends on the test task and is included in bootJar.
```xml
org.apache.maven.plugins
maven-assembly-plugin
stub
prepare-package
single
false
true
${basedir}/src/assembly/stub.xml
stubs
jar
false
${project.build.directory}/generated-snippets/stubs
META-INF/${project.groupId}/${project.artifactId}/${project.version}/mappings
**/*
```
```groovy
task stubsJar(type: Jar) {
classifier = "stubs"
into("META-INF/${project.group}/${project.name}/${project.version}/mappings") {
include('**/*.*')
from("${project.buildDir}/generated-snippets/stubs")
}
}
// we need the tests to pass to build the stub jar
stubsJar.dependsOn(test)
bootJar.dependsOn(stubsJar)
```
--------------------------------
### Kill and run node app
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Kill any existing node app process and start it in the background with nohup.
```bash
# Kill & Run app
$ pkill -f "node app"
$ nohup node app &
```
--------------------------------
### Run stubs mappings from current directory (full plugin coordinates)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/site/asciidoc/usage.adoc
Runs the plugin's run goal using the full Maven coordinates to start the stub runner from the current directory.
```bash
mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:run
```
--------------------------------
### YAML: Request with body
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-request.adoc
Shows how to define a request body in the contract DSL using YAML. This example is extracted from a YAML file with the 'request' and 'body' tags.
```yaml
include::{verifier_root_path}/src/test/resources/yml/contract.yml[tags=request,indent=0]
...
include::{verifier_root_path}/src/test/resources/yml/contract.yml[tags=body,indent=0]
```
--------------------------------
### Java: Multiple contracts in one file
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-multiple.adoc
Java example showing how to define multiple contracts using the Contract DSL. The contract class implements Supplier> and returns a list of contracts, with one contract having a name and others without.
```java
class contract implements Supplier> {
@Override
public Collection get() {
return Arrays.asList(
Contract.make(c -> {
c.name("should post a user");
// ...
}), Contract.make(c -> {
// ...
}), Contract.make(c -> {
// ...
})
);
}
}
```
--------------------------------
### Javalin Application
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/provider-contract-testing-non-spring.adoc
A simple non-Spring HTTP server using Javalin that returns 'Hello World' for GET requests to '/'. This server is used to demonstrate the EXPLICIT test mode.
```java
package com.example.demo;
import io.javalin.Javalin;
public class DemoApplication {
public static void main(String[] args) {
new DemoApplication().run(7000);
}
public Javalin start(int port) {
return Javalin.create().start(port);
}
public Javalin registerGet(Javalin app) {
return app.get("/", ctx -> ctx.result("Hello World"));
}
public Javalin run(int port) {
return registerGet(start(port));
}
}
```
--------------------------------
### GET /stubs
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-boot.adoc
Returns a list of all running stubs in ivy:integer notation.
```APIDOC
## GET /stubs
### Description
Returns a list of all running stubs in `ivy:integer` notation.
### Method
GET
### Endpoint
/stubs
### Response
#### Success Response (200)
- **body** (string) - A list of all running stubs in `ivy:integer` notation.
#### Response Example
```
[ivy:integer notation]
```
```
--------------------------------
### Groovy: Request with body
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-request.adoc
Shows how to define a request body in the contract DSL using Groovy. This example is from the primary role and is part of the request body section.
```groovy
include::{verifier_root_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/ContractHttpDocsSpec.groovy[tags=body,indent=0]
```
--------------------------------
### WireMockHttpServerStubConfigurer implementation
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
Shows an implementation of WireMockHttpServerStubConfigurer that can be extended to provide custom configuration, such as starting WireMock on an HTTPS port. The configure method allows altering configuration files for the HTTP server stub.
```groovy
include::{stubrunner_core_path}/src/test/groovy/org/springframework/cloud/contract/stubrunner/spring/StubRunnerConfigurationSpec.groovy[tags=wireMockHttpServerStubConfigurer]
```
--------------------------------
### Stub Runner log output showing stub resolution and startup
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
Log output from running the consumer tests with Stub Runner. It shows the stub downloader resolving the latest version, downloading the stubs artifact, unpacking it, and starting the stub server on port 8080. This confirms that Stub Runner has found and started the stubs for the http-server application.
```bash
2016-07-19 14:22:25.403 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Desired version is + - will try to resolve the latest version
2016-07-19 14:22:25.438 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved version is 0.0.1-SNAPSHOT
2016-07-19 14:22:25.439 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolving artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT using remote repositories []
2016-07-19 14:22:25.451 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Resolved artifact com.example:http-server:jar:stubs:0.0.1-SNAPSHOT to /path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar
2016-07-19 14:22:25.465 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacking stub from JAR [URI: file:/path/to/your/.m2/repository/com/example/http-server/0.0.1-SNAPSHOT/http-server-0.0.1-SNAPSHOT-stubs.jar]
2016-07-19 14:22:25.475 INFO 41050 --- [ main] o.s.c.c.stubrunner.AetherStubDownloader : Unpacked file to [/var/folders/0p/xwq47sq106x1_g3dtv6qfm940000gq/T/contracts100276532569594265]
2016-07-19 14:22:27.737 INFO 41050 --- [ main] o.s.c.c.stubrunner.StubRunnerExecutor : All stubs are now running RunningStubs [namesAndPorts={com.example:http-server:0.0.1-SNAPSHOT:stubs=8080}]
```
--------------------------------
### Customizing verifierStubsJar Task
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/gradle-project.adoc
Example of using native Gradle mechanisms to add files, such as git.properties, to the generated stubs JAR.
```groovy
verifierStubsJar {
from("${buildDir}/resources/main/") {
include("git.properties")
}
}
```
--------------------------------
### Run producer message tests with Docker
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Bash script to start a Docker image with attached contracts for running message tests on the producer side. It sets environment variables for the contract version, application URL, project coordinates, and stub classifier, with defaults for each.
```bash
#!/bin/bash
set -x
CURRENT_DIR="$( pwd )"
export SC_CONTRACT_DOCKER_VERSION="${SC_CONTRACT_DOCKER_VERSION:-4.0.1-SNAPSHOT}"
export APP_IP="$( ./whats_my_ip.sh )"
export APP_PORT="${APP_PORT:-8000}"
export APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
export PROJECT_GROUP="${PROJECT_GROUP:-group}"
export PROJECT_NAME="${PROJECT_NAME:-application}"
export PROJECT_VERSION="${PROJECT_VERSION:-0.0.1-SNAPSHOT}"
export PRODUCER_STUBS_CLASSIFIER="${PRODUCER_STUBS_CLASSIFIER:-stubs}"
export FAIL_ON_NO_CONTRACTS="${FAIL_ON_NO_CONTRACTS:-false}"
```
--------------------------------
### Consumer Side GraphQL Test
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-flows/graphql.adoc
Example consumer test that uses StubRunner to download and run the stub, then sends a GraphQL request and verifies the response status.
```java
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class BeerControllerGraphQLTest {
@RegisterExtension
static StubRunnerExtension rule = new StubRunnerExtension()
.downloadStub("com.example","beer-api-producer-graphql")
.stubsMode(StubRunnerProperties.StubsMode.LOCAL);
private static final String REQUEST_BODY = "{\n"
+ "\"query\":\"query queryName($personName: String!) {\\n personToCheck(name: $personName) {\\n name\\n age\\n }\\n}\","
+ "\"variables\":{\"personName\":\"Old Enough\"},\n"
+ "\"operationName\":\"queryName\"\n"
+ "}";
@Test
public void should_send_a_graphql_request() {
ResponseEntity responseEntity = new RestTemplate()
.exchange(RequestEntity
.post(URI.create("http://localhost:" + rule.findStubUrl("beer-api-producer-graphql").getPort() + "/graphql"))
.contentType(MediaType.APPLICATION_JSON)
.body(REQUEST_BODY), String.class);
BDDAssertions.then(responseEntity.getStatusCode().value()).isEqualTo(200);
}
}
```
--------------------------------
### Maven build output showing test error
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/cdc.adoc
Example output from running `./mvnw clean install` showing a test error in `ContractVerifierTest.validate_shouldMarkClientAsFraud`.
```bash
Results :
Tests in error:
ContractVerifierTest.validate_shouldMarkClientAsFraud:32 » IllegalState Parsed...
```
--------------------------------
### Maven plugin setup for git stubs
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/using/provider-contract-testing-with-stubs-in-git.adoc
Maven plugin configuration to fetch contracts from a git repository and push stubs back to SCM. Sets `contractsRepositoryUrl` with the `git` protocol, `contractsMode` to `REMOTE`, and adds the `pushStubsToScm` goal to the `package` phase.
```xml
org.springframework.cloud
spring-cloud-contract-maven-plugin
${spring-cloud-contract.version}
true
git://git://git@github.com:spring-cloud-samples/spring-cloud-contract-nodejs-contracts-git.git
${project.groupId}
${project.artifactId}
${project.version}
REMOTE
package
pushStubsToScm
```
--------------------------------
### WebTestClient base class setup with RestAssuredWebTestClient
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-flows/feature-webflux.adoc
Base class for WebFlux tests using RestAssuredWebTestClient. It sets up a standalone controller with a lambda that checks if the person's age is at least 20.
```groovy
import io.restassured.module.webtestclient.RestAssuredWebTestClient;
import org.junit.Before;
public abstract class BeerRestBase {
@Before
public void setup() {
RestAssuredWebTestClient.standaloneSetup(
new ProducerController(personToCheck -> personToCheck.age >= 20));
}
}
}
```
--------------------------------
### Clone sample repository and change directory
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Clones the spring-cloud-contract-nodejs sample repository and changes into the bookstore directory.
```bash
$ git clone https://github.com/spring-cloud-samples/spring-cloud-contract-nodejs
$ cd bookstore
```
--------------------------------
### Camel Stub Repository and Stub Structure
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
These directory listings show the expected Maven repository layout for the camelService stubs and the internal structure of the stubs jar. They are used to illustrate the setup for the Camel messaging example.
```bash
└── .m2
└── repository
└── io
└── codearte
└── accurest
└── stubs
└── camelService
├── 0.0.1-SNAPSHOT
│ ├── camelService-0.0.1-SNAPSHOT.pom
│ ├── camelService-0.0.1-SNAPSHOT-stubs.jar
│ └── maven-metadata-local.xml
└── maven-metadata-local.xml
```
```bash
├── META-INF
│ └── MANIFEST.MF
└── repository
├── accurest
│ └── bookReturned1.groovy
└── mappings
```
--------------------------------
### Configure ignoredClassPatterns and ignoredResourcePatterns for duplicate-finder
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/README.adoc
Add this configuration to the plugin section to specify patterns for classes and resources that should be ignored during duplicate checks. The example shows ignoring a specific class and a resource pattern.
```xml
org.basepom.maven
duplicate-finder-maven-plugin
org.joda.time.base.BaseDateTime
.*module-info
changelog.txt
```
--------------------------------
### Convert Spring Cloud Contract DSL into WireMock stub mappings (short form)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/site/asciidoc/usage.adoc
Runs the convert goal using the short plugin prefix. Requires the plugin group to be configured in ~/.m2/settings.xml as described in the footnote.
```bash
mvn spring-cloud-contract:convert
```
--------------------------------
### Kotlin contract definition example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract.adoc
Example of a contract definition written in Kotlin. The example is included from the Spring Cloud Contract verifier source code.
```kotlin
include::{verifier_root_path}/src/test/resources/kotlin/contract_rest.kts[tags=class,indent=0]
```
--------------------------------
### Java contract definition example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract.adoc
Example of a contract definition written in Java. The example is included from the Spring Cloud Contract verifier source code.
```java
include::{verifier_root_path}/src/test/resources/contractsToCompile/contract_rest.java[tags=class,indent=0]
```
--------------------------------
### Add stub dependencies for classpath scanning (Maven and Gradle)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-core.adoc
Adds the stub dependencies to the classpath for classpath scanning. The Maven and Gradle examples are equivalent; both disable transitive dependencies to avoid pulling in unwanted artifacts.
```xml
com.example
beer-api-producer-restdocs
stubs
0.0.1-SNAPSHOT
test
*
*
com.example.thing1
thing2
superstubs
1.0.0
test
*
*
```
```groovy
testCompile("com.example:beer-api-producer-restdocs:0.0.1-SNAPSHOT:stubs") {
transitive = false
}
testCompile("com.example.thing1:thing2:1.0.0:superstubs") {
transitive = false
}
```
--------------------------------
### Gradle: Create task dependencies
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/howto/how-to-common-repo-with-contracts.adoc
Sets up task dependencies so that unzipContracts depends on getContracts, deleteUnwantedContracts depends on unzipContracts, and build depends on deleteUnwantedContracts.
```groovy
unzipContracts.dependsOn("getContracts")
deleteUnwantedContracts.dependsOn("unzipContracts")
build.dependsOn("deleteUnwantedContracts")
```
--------------------------------
### YAML contract definition example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract.adoc
Example of a contract definition written in YAML. The example is included from the Spring Cloud Contract verifier source code.
```yaml
include::{verifier_root_path}/src/test/resources/yml/contract_rest.yml[indent=0]
```
--------------------------------
### Run npm test
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Runs the tests for the sample application.
```bash
$ npm test
```
--------------------------------
### Groovy contract definition example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract.adoc
Example of a contract definition written in Groovy. The example is included from the Spring Cloud Contract verifier source code.
```groovy
include::{verifier_root_path}/src/test/groovy/org/springframework/cloud/contract/verifier/builder/SpringTestMethodBodyBuildersSpec.groovy[tags=dsl_example,indent=0]
```
--------------------------------
### JMS contract example
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-messaging.adoc
Contract example for the Spring JMS integration.
```groovy
include::{tests_path}/spring-cloud-contract-stub-runner-jms/src/test/groovy/org/springframework/cloud/contract/stubrunner/messaging/jms/JmsStubRunnerSpec.groovy[tags=sample_dsl,indent=0]
```
--------------------------------
### Run stubs mappings from current directory (short form)
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/spring-cloud-contract-tools/spring-cloud-contract-maven-plugin/src/site/asciidoc/usage.adoc
Runs the plugin's run goal using the short plugin prefix. Requires the plugin group to be configured in ~/.m2/settings.xml.
```bash
mvn spring-cloud-contract:run
```
--------------------------------
### Kotlin: Multipart request
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/_dsl-request.adoc
Shows how to define multipart elements in a request using Kotlin.
```kotlin
include::{verifier_root_path}/src/test/resources/kotlin/multipart.kts[tags=class,indent=0]
```
--------------------------------
### Prepare environment variables
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Sets environment variables used by the contract test Docker run command.
```bash
# Prepare environment variables
$ SC_CONTRACT_DOCKER_VERSION="..."
$ APP_IP="192.168.0.100"
$ APP_PORT="3000"
$ ARTIFACTORY_PORT="8081"
$ APPLICATION_BASE_URL="http://${APP_IP}:${APP_PORT}"
$ ARTIFACTORY_URL="http://${APP_IP}:${ARTIFACTORY_PORT}/artifactory/libs-release-local"
$ CURRENT_DIR="$( pwd )"
$ CURRENT_FOLDER_NAME=${PWD##*/}
$ PROJECT_VERSION="0.0.1.RELEASE"
```
--------------------------------
### Project Structure for Passing Values from Files
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-contract/common-top-elements.adoc
Directory structure showing where contract files and JSON data files should be placed. The contract file and the JSON files must be in the same folder.
```bash
└── src
└── test
└── resources
└── contracts
├── readFromFile.groovy
├── request.json
└── response.json
```
--------------------------------
### Configure baseClassForTests in pom.xml
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/getting-started/three-second-tour.adoc
Configure the Spring Cloud Contract Maven plugin with a base test class. The baseClassForTests element must be a child of the configuration element within the plugin. The base test class is extended by all auto-generated tests and should contain setup information such as RestAssuredMockMvc controller setup or messaging test setup.
```xml
org.springframework.cloud
spring-cloud-contract-maven-plugin
2.1.2.RELEASE
true
com.example.contractTest.BaseTestClass <1>
org.springframework.boot
spring-boot-maven-plugin
```
--------------------------------
### Enable stubs.find-producer with stubs:// protocol
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/project-features-stubrunner/stub-runner-stubs-protocol.adoc
Configure Stub Runner to find per-consumer folders by setting stubs.find-producer=true. The repositoryRoot points to the contracts directory. Three setups are shown: annotation, JUnit 4 rule, and JUnit 5 extension, each passing the property.
```java
@AutoConfigureStubRunner(
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "stubs://file://location/to/the/contracts/directory",
ids = "com.example:some-producer",
properties="stubs.find-producer=true")
```
```java
static Map contractProperties() {
Map map = new HashMap<>();
map.put("stubs.find-producer", "true");
return map;
}
@Rule
public StubRunnerRule rule = new StubRunnerRule()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts/directory")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.properties(contractProperties());
```
```java
static Map contractProperties() {
Map map = new HashMap<>();
map.put("stubs.find-producer", "true");
return map;
}
@RegisterExtension
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts/directory")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.properties(contractProperties());
```
--------------------------------
### Run first and second curl requests to the books API
Source: https://github.com/spring-attic/spring-cloud-contract/blob/main/docs/modules/ROOT/pages/docker-project.adoc
Run the first request to create a book (no response is returned), then the second request to retrieve the books. The second request returns the contents of the JSON.
```bash
$ curl -H "Content-Type:application/json" -X POST --data '{ "title" : "Title", "genre" : "Genre", "description" : "Description", "author" : "Author", "publisher" : "Publisher", "pages" : 100, "image_url" : "https://d213dhlpdb53mu.cloudfront.net/assets/pivotal-square-logo-41418bd391196c3022f3cd9f3959b3f6d7764c47873d858583384e759c7db435.svg", "buy_url" : "https://pivotal.io" }' http://localhost:9876/api/books
```
```bash
$ curl -X GET http://localhost:9876/api/books
```