常见的顶层元素

以下章节描述了最常见的顶层元素

描述

你可以为你的契约添加一个 description。描述是任意文本。以下代码展示了一个示例

Groovy
			org.springframework.cloud.contract.spec.Contract.make {
				description('''
given:
	An input
when:
	Sth happens
then:
	Output
''')
			}
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
Contract.make(c -> {
	c.description("Some description");
}));
Kotlin
contract {
	description = """
given:
	An input
when:
	Sth happens
then:
	Output
"""
}

名称

你可以为你的契约提供一个名称。假设你提供的名称如下:should register a user。如果你这样做,自动生成的测试名称将是 validate_should_register_a_user。此外,WireMock 存根中的存根名称将是 should_register_a_user.json

你必须确保名称不包含任何会导致生成的测试无法编译的字符。另外,请记住,如果你为多个契约提供了相同的名称,你的自动生成的测试将无法编译,并且你生成的存根会相互覆盖。

以下示例展示了如何为契约添加名称

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	name("some_special_name")
}
YAML
name: some name
Java
Contract.make(c -> {
	c.name("some name");
}));
Kotlin
contract {
	name = "some_special_name"
}

忽略契约

如果你想忽略某个契约,你可以在插件配置中设置忽略的契约值,或者在契约本身上设置 ignored 属性。以下示例展示了如何这样做

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	ignored()
}
YAML
ignored: true
Java
Contract.make(c -> {
	c.ignored();
}));
Kotlin
contract {
	ignored = true
}

正在进行中的契约

正在进行中的契约不会在生产者端生成测试,但允许生成存根。

谨慎使用此功能,因为它可能导致误报,因为你在实际实现尚未到位的情况下为消费者生成了可用的存根。

如果你想设置一个正在进行中的契约,以下示例展示了如何这样做

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	inProgress()
}
YAML
inProgress: true
Java
Contract.make(c -> {
	c.inProgress();
}));
Kotlin
contract {
	inProgress = true
}

你可以设置 failOnInProgress Spring Cloud Contract 插件属性的值,以确保当你的源代码中至少存在一个正在进行中的契约时,你的构建会失败。

从文件传递值

从版本 1.2.0 开始,你可以从文件传递值。假设你的项目中包含以下资源

└── src
    └── test
        └── resources
            └── contracts
                ├── readFromFile.groovy
                ├── request.json
                └── response.json

进一步假设你的契约如下所示

Groovy
/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://apache.ac.cn/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

Contract.make {
	request {
		method('PUT')
		headers {
			contentType(applicationJson())
		}
		body(file("request.json"))
		url("/1")
	}
	response {
		status OK()
		body(file("response.json"))
		headers {
			contentType(applicationJson())
		}
	}
}
YAML
request:
  method: GET
  url: /foo
  bodyFromFile: request.json
response:
  status: 200
  bodyFromFile: response.json
Java
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;

class contract_rest_from_file implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Collections.singletonList(Contract.make(c -> {
			c.request(r -> {
				r.url("/foo");
				r.method(r.GET());
				r.body(r.file("request.json"));
			});
			c.response(r -> {
				r.status(r.OK());
				r.body(r.file("response.json"));
			});
		}));
	}

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

contract {
	request {
		url = url("/1")
		method = PUT
		headers {
			contentType = APPLICATION_JSON
		}
		body = bodyFromFile("request.json")
	}
	response {
		status = OK
		body = bodyFromFile("response.json")
		headers {
			contentType = APPLICATION_JSON
		}
	}
}

进一步假设 JSON 文件如下所示

request.json
{
  "status": "REQUEST"
}
response.json
{
  "status": "RESPONSE"
}

当进行测试或存根生成时,request.jsonresponse.json 文件的内容会传递给请求或响应的正文。文件的名称需要是相对于契约所在文件夹的某个位置中的文件。

如果你需要以二进制形式传递文件内容,可以在编码 DSL 中使用 fileAsBytes 方法,或者在 YAML 中使用 bodyFromFileAsBytes 字段。

以下示例展示了如何传递二进制文件的内容

Groovy
import org.springframework.cloud.contract.spec.Contract

Contract.make {
	request {
		url("/1")
		method(PUT())
		headers {
			contentType(applicationOctetStream())
		}
		body(fileAsBytes("request.pdf"))
	}
	response {
		status 200
		body(fileAsBytes("response.pdf"))
		headers {
			contentType(applicationOctetStream())
		}
	}
}
YAML
request:
  url: /1
  method: PUT
  headers:
    Content-Type: application/octet-stream
  bodyFromFileAsBytes: request.pdf
response:
  status: 200
  bodyFromFileAsBytes: response.pdf
  headers:
    Content-Type: application/octet-stream
Java
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;

class contract_rest_from_pdf implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Collections.singletonList(Contract.make(c -> {
			c.request(r -> {
				r.url("/1");
				r.method(r.PUT());
				r.body(r.fileAsBytes("request.pdf"));
				r.headers(h -> {
					h.contentType(h.applicationOctetStream());
				});
			});
			c.response(r -> {
				r.status(r.OK());
				r.body(r.fileAsBytes("response.pdf"));
				r.headers(h -> {
					h.contentType(h.applicationOctetStream());
				});
			});
		}));
	}

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

contract {
	request {
		url = url("/1")
		method = PUT
		headers {
			contentType = APPLICATION_OCTET_STREAM
		}
		body = bodyFromFileAsBytes("contracts/request.pdf")
	}
	response {
		status = OK
		body = bodyFromFileAsBytes("contracts/response.pdf")
		headers {
			contentType = APPLICATION_OCTET_STREAM
		}
	}
}
每当你想处理二进制负载时,无论是对于 HTTP 还是消息传递,都应该使用此方法。

元数据

你可以为你的契约添加 metadata。通过元数据,你可以将配置传递给扩展。下面是一个使用 wiremock 键的示例。其值是一个映射,键是 stubMapping,值是 WireMock 的 StubMapping 对象。Spring Cloud Contract 能够使用你的自定义代码修补生成的存根映射的一部分。你可能想这样做是为了添加 webhooks、自定义延迟或与第三方 WireMock 扩展集成。

java
Contract.make(c -> {
	c.metadata(MetadataUtil.map()
		.entry("wiremock", ContractVerifierUtil.map()
			.entry("stubMapping", "{ \"response\" : { \"fixedDelayMilliseconds\" : 2000 } }")));
}));
kotlin
contract {
	metadata("wiremock" to ("stubmapping" to """
{
  "response" : {
	"fixedDelayMilliseconds": 2000
  }
}"""))
}

在以下章节中,你可以找到支持的元数据条目的示例。

HTTP 契约

Spring Cloud Contract 允许你验证使用 REST 或 HTTP 作为通信手段的应用。Spring Cloud Contract 验证对于与契约 request 部分标准匹配的请求,服务器提供的响应是否与契约 response 部分保持一致。随后,契约被用于生成 WireMock 存根,对于任何匹配提供标准的请求,这些存根会提供合适的响应。