常见的顶级元素

以下各节介绍最常见的顶级元素

描述

您可以为契约添加 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 stub 中的 stub 名称为 should_register_a_user.json

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

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

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
}

正在进行的契约

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

请谨慎使用此功能,因为它可能导致误报,因为您为消费者生成了 stub,但实际上并未实现。

如果您想设置一个正在进行的契约,以下示例显示了如何操作

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-present 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"
}

当进行测试或 stub 生成时,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 能够使用您的自定义代码修补生成的 stub 映射的部分。您可能希望这样做是为了添加 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 stub,对于任何匹配提供条件的请求,这些 stub 提供适当的响应。

© . This site is unofficial and not affiliated with VMware.