合同DSL

Spring Cloud Contract 支持以下语言编写的 DSL:spring-doc.cadn.net.cn

Spring Cloud Contract 支持在一个文件中定义多个合同(在 Groovy 中返回列表而非单个合同)。

以下示例展示了合同的定义:spring-doc.cadn.net.cn

槽的
org.springframework.cloud.contract.spec.Contract.make {
	request {
		method 'PUT'
		url '/api/12'
		headers {
			header 'Content-Type': 'application/vnd.org.springframework.cloud.contract.verifier.twitter-places-analyzer.v1+json'
		}
		body '''\
	[{
		"created_at": "Sat Jul 26 09:38:57 +0000 2014",
		"id": 492967299297845248,
		"id_str": "492967299297845248",
		"text": "Gonna see you at Warsaw",
		"place":
		{
			"attributes":{},
			"bounding_box":
			{
				"coordinates":
					[[
						[-77.119759,38.791645],
						[-76.909393,38.791645],
						[-76.909393,38.995548],
						[-77.119759,38.995548]
					]],
				"type":"Polygon"
			},
			"country":"United States",
			"country_code":"US",
			"full_name":"Washington, DC",
			"id":"01fbe706f872cb32",
			"name":"Washington",
			"place_type":"city",
			"url": "https://api.twitter.com/1/geo/id/01fbe706f872cb32.json"
		}
	}]
'''
	}
	response {
		status OK()
	}
}
YAML
description: Some description
name: some name
priority: 8
ignored: true
request:
  url: /foo
  queryParameters:
    a: b
    b: c
  method: PUT
  headers:
    foo: bar
    fooReq: baz
  body:
    foo: bar
  matchers:
    body:
      - path: $.foo
        type: by_regex
        value: bar
    headers:
      - key: foo
        regex: bar
response:
  status: 200
  headers:
    foo2: bar
    foo3: foo33
    fooRes: baz
  body:
    foo2: bar
    foo3: baz
    nullValue: null
  matchers:
    body:
      - path: $.foo2
        type: by_regex
        value: bar
      - path: $.foo3
        type: by_command
        value: executeMe($it)
      - path: $.nullValue
        type: by_null
        value: null
    headers:
      - key: foo2
        regex: bar
      - key: foo3
        command: andMeToo($it)
Java
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.verifier.util.ContractVerifierUtil;

class contract_rest implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Collections.singletonList(Contract.make(c -> {
			c.description("Some description");
			c.name("some name");
			c.priority(8);
			c.ignored();
			c.request(r -> {
				r.url("/foo", u -> {
					u.queryParameters(q -> {
						q.parameter("a", "b");
						q.parameter("b", "c");
					});
				});
				r.method(r.PUT());
				r.headers(h -> {
					h.header("foo", r.value(r.client(r.regex("bar")), r.server("bar")));
					h.header("fooReq", "baz");
				});
				r.body(ContractVerifierUtil.map().entry("foo", "bar"));
				r.bodyMatchers(m -> {
					m.jsonPath("$.foo", m.byRegex("bar"));
				});
			});
			c.response(r -> {
				r.fixedDelayMilliseconds(1000);
				r.status(r.OK());
				r.headers(h -> {
					h.header("foo2", r.value(r.server(r.regex("bar")), r.client("bar")));
					h.header("foo3", r.value(r.server(r.execute("andMeToo($it)")), r.client("foo33")));
					h.header("fooRes", "baz");
				});
				r.body(ContractVerifierUtil.map().entry("foo2", "bar").entry("foo3", "baz").entry("nullValue", null));
				r.bodyMatchers(m -> {
					m.jsonPath("$.foo2", m.byRegex("bar"));
					m.jsonPath("$.foo3", m.byCommand("executeMe($it)"));
					m.jsonPath("$.nullValue", m.byNull());
				});
			});
		}));
	}

}
Kotlin
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract
import org.springframework.cloud.contract.spec.withQueryParameters

contract {
	name = "some name"
	description = "Some description"
	priority = 8
	ignored = true
	request {
		url = url("/foo") withQueryParameters  {
			parameter("a", "b")
			parameter("b", "c")
		}
		method = PUT
		headers {
			header("foo", value(client(regex("bar")), server("bar")))
			header("fooReq", "baz")
		}
		body = body(mapOf("foo" to "bar"))
		bodyMatchers {
			jsonPath("$.foo", byRegex("bar"))
		}
	}
	response {
		delay = fixedMilliseconds(1000)
		status = OK
		headers {
			header("foo2", value(server(regex("bar")), client("bar")))
			header("foo3", value(server(execute("andMeToo(\$it)")), client("foo33")))
			header("fooRes", "baz")
		}
		body = body(mapOf(
				"foo" to "bar",
				"foo3" to "baz",
				"nullValue" to null
		))
		bodyMatchers {
			jsonPath("$.foo2", byRegex("bar"))
			jsonPath("$.foo3", byCommand("executeMe(\$it)"))
			jsonPath("$.nullValue", byNull)
		}
	}
}

您可以使用以下独立的 Maven 命令将合同编译为存根映射:spring-doc.cadn.net.cn

mvn org.springframework.cloud:spring-cloud-contract-maven-plugin:convert

Groovy 中的合同 DSL

如果你不熟悉Groovy,不用担心。你可以在 还有Groovy DSL文件。spring-doc.cadn.net.cn

如果你决定用Groovy写合同,不用担心还没用过Groovy 以前。其实不需要懂该语言,因为合同DSL只使用一个 其中极小的子集(只有文字、方法调用和闭包)。另外,DSL是静态的 打字,使程序员无需了解DSL即可阅读。spring-doc.cadn.net.cn

请记住,在Groovy合同文件中,你必须提供完整的 限定名称为合同类和静态导入,例如org.springframework.cloud.spec.Contract.make { ... }.你也可以提供导入到 这合同类 (import org.springframework.cloud.spec.Contract然后呼叫Contract.make { ... }.

Java 中的合同 DSL

要在 Java 中编写合同定义,你需要创建一个实现以下提供商<合同条款>接口(用于单一合同)或提供商<收款<合同>>(针对多个合同)。spring-doc.cadn.net.cn

你也可以写下合同定义SRC/测试/Java(例如,src/test/java/contracts这样你就不必修改项目的类路径。在这种情况下,你需要为你的 Spring Cloud Contract 插件提供新的合同定义位置。spring-doc.cadn.net.cn

以下示例(在Maven和Gradle中)包含了合同的定义SRC/测试/Java:spring-doc.cadn.net.cn

梅文
<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>${spring-cloud-contract.version}</version>
    <extensions>true</extensions>
    <configuration>
        <contractsDirectory>src/test/java/contracts</contractsDirectory>
    </configuration>
</plugin>
格拉德勒
contracts {
	contractsDslDir = new File(project.rootDir, "src/test/java/contracts")
}

Kotlin 中的合同 DSL

要开始用Kotlin写合同,你需要从一个(新创建的)Kotlin Script文件开始(.kts). 和 Java DSL 一样,你可以将契约放到任意你选择的目录中。 默认情况下,Maven插件会检测SRC/测试/资源/合同目录和Gradle插件会 看看src/contractTest/资源/合同目录。spring-doc.cadn.net.cn

从 3.0.0 版本起,Gradle 插件也会查看遗留系统 目录SRC/测试/资源/合同为了迁移目的。当该目录中发现合同时,会有警告 在你构建过程中会被记录。

你需要明确传递Spring-cloud-contract-spec-kotlin依赖你的项目插件设置。 以下示例(在Maven和Gradle中)展示了如何实现:spring-doc.cadn.net.cn

梅文
<plugin>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-maven-plugin</artifactId>
    <version>${spring-cloud-contract.version}</version>
    <extensions>true</extensions>
    <configuration>
        <!-- some config -->
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-spec-kotlin</artifactId>
            <version>${spring-cloud-contract.version}</version>
        </dependency>
    </dependencies>
</plugin>

<dependencies>
        <!-- Remember to add this for the DSL support in the IDE and on the consumer side -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-spec-kotlin</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
格拉德勒
buildscript {
    repositories {
        // ...
    }
	dependencies {
		classpath "org.springframework.cloud:spring-cloud-contract-gradle-plugin:$\{scContractVersion}"
	}
}

dependencies {
    // ...

    // Remember to add this for the DSL support in the IDE and on the consumer side
    testImplementation "org.springframework.cloud:spring-cloud-contract-spec-kotlin"
    // Kotlin versions are very particular down to the patch version. The <kotlin_version> needs to be the same as you have imported for your project.
    testImplementation "org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:<kotlin_version>"
}
请记住,在 Kotlin Script 文件中,你必须为ContractDSL类。 通常你会按照以下方式使用其契约函数:org.springframework.cloud.contract.spec.ContractDsl.contract { ... }. 你也可以向合同函数(import org.springframework.cloud.contract.spec.Contract.ContractDsl.Companion.contract然后呼叫合同 { ... }.

YAML中的合同DSL

要查看 YAML 合同的模式,请访问 YML 模式页面。spring-doc.cadn.net.cn

局限性

验证JSON数组大小的支持还处于实验阶段。如果需要帮助, 要开启它,将以下系统属性的值设为true:Spring.cloud.contract.verifier.assert.size.默认情况下,此功能设置为false. 你也可以设置assertJsonSize插件配置中的属性。
因为JSON结构可以是任何形式,解析它可能不可能 在使用 Groovy DSL 和价值(消费者......)、生产者(......))记号GString.那 这就是为什么你应该使用Groovy Map符号。

一个文件中的多个合同

你可以在一个文件中定义多个合同。这样的合同可能类似于 以下示例:spring-doc.cadn.net.cn

槽的
import org.springframework.cloud.contract.spec.Contract

[
	Contract.make {
		name("should post a user")
		request {
			method 'POST'
			url('/users/1')
		}
		response {
			status OK()
		}
	},
	Contract.make {
		request {
			method 'POST'
			url('/users/2')
		}
		response {
			status OK()
		}
	}
]
YAML
---
name: should post a user
request:
  method: POST
  url: /users/1
response:
  status: 200
---
request:
  method: POST
  url: /users/2
response:
  status: 200
---
request:
  method: POST
  url: /users/3
response:
  status: 200
Java
class contract implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Arrays.asList(
            Contract.make(c -> {
            	c.name("should post a user");
                // ...
            }), Contract.make(c -> {
                // ...
            }), Contract.make(c -> {
                // ...
            })
		);
	}

}
Kotlin
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract

arrayOf(
    contract {
        name("should post a user")
        // ...
    },
    contract {
        // ...
    },
    contract {
        // ...
    }
}

在上述例子中,一个合同具有名称而另一个则不然。这 导致生成两个测试,如下:spring-doc.cadn.net.cn

import com.example.TestBase;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import com.jayway.restassured.response.ResponseOptions;
import org.junit.Test;

import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;

public class V1Test extends TestBase {

	@Test
	public void validate_should_post_a_user() throws Exception {
		// given:
			MockMvcRequestSpecification request = given();

		// when:
			ResponseOptions response = given().spec(request)
					.post("/users/1");

		// then:
			assertThat(response.statusCode()).isEqualTo(200);
	}

	@Test
	public void validate_withList_1() throws Exception {
		// given:
			MockMvcRequestSpecification request = given();

		// when:
			ResponseOptions response = given().spec(request)
					.post("/users/2");

		// then:
			assertThat(response.statusCode()).isEqualTo(200);
	}

}

请注意,对于包含名称字段,生成的测试方法命名为validate_should_post_a_user.那就是没有名称场称为validate_withList_1.它对应文件的名称WithList.groovy以及 列表中合同的索引。spring-doc.cadn.net.cn

生成的存根示例如下所示:spring-doc.cadn.net.cn

should post a user.json
1_WithList.json

第一个文件得到了名称合同中的参数。第二 拿到了合同文件的名称(WithList.groovy) 以索引前缀(在此中) 该合同的索引为1在档案中的合同列表中)。spring-doc.cadn.net.cn

最好是给合同命名,因为这样会让 你的测试更有意义。

有状态契约

有状态合同(也称为情景)是应当阅读的合同定义 挨次。这在以下情况下可能有用:spring-doc.cadn.net.cn

  • 你希望按照精确定义的顺序调用合同,因为你用的是 Spring 云合同用于测试你的有状态应用。spring-doc.cadn.net.cn

我们非常不建议你这么做,因为合同测试应该是无状态的。

要创建有状态契约(或场景),你需要 在制定合同时,请使用正确的命名规范。大会 需要包含订单号和下划线。无论如何,这个方法都有效 无论你是用YAML还是Groovy。以下列表展示了一个示例:spring-doc.cadn.net.cn

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

这样的树会导致Spring Cloud Contract Verifier生成带有 名称情景1以及以下三个步骤:spring-doc.cadn.net.cn

  1. 登录,标记为开始指向......spring-doc.cadn.net.cn

  2. showCart,标记为第一步指向......spring-doc.cadn.net.cn

  3. 注销,标记为第二步(这就结束了剧情)。spring-doc.cadn.net.cn

你可以在 https://wiremock.org/docs/stateful-behaviour/ 找到更多关于WireMock场景的详细信息。spring-doc.cadn.net.cn