Spring 云合同 YAML header 匹配
Spring Cloud Contract YAML header matching
在使用 POST
方法创建新资源时,新资源的位置将作为 Location
header.
添加到响应中
如何创建一个 spring-cloud-contract YML 来验证响应是否包含 Location
header 以及有效的 URI
值?
我尝试使用以下 YAML,但它不起作用。
request:
method: POST
url: /customers/v1
body:
firstName: First Name
lastName: Last Name
dateOfBirth: "1990-12-12"
active: false
headers:
Content-Type: application/json
response:
status: 201
matchers:
headers:
- key: Location
regex: "http://localhost/customers/v1/*"
生成测试代码
@Test
public void validate_create_customer_successfully() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"firstName\":\"First Name\",\"lastName\":\"Last Name\",\"dateOfBirth\":\"1990-12-12\",\"active\":false}");
// when:
ResponseOptions response = given().spec(request)
.post("/customers/v1");
// then:
assertThat(response.statusCode()).isEqualTo(201);
}
生成的代码不包含任何 header 验证。
我还没有测试过,但是如果你尝试会发生什么:
response:
status: 201
matchers:
headers:
- key: Location
type: by_regex
predefined: url
这就是您将用于 body 匹配器的内容,我不确定它是否适用于 headers。
只是想让你知道。我相信匹配器部分只是为了响应的测试方的利益(验证生产者发出的响应)。如果您还想将此 header 作为存根响应提供给您的消费者,则必须将其添加到匹配器部分之外并使用固定值。
以下 yaml 定义有效
response:
status: 201
headers:
Location: "http://localhost/customers/v1/"
matchers:
headers:
- key: Location
regex: "http://localhost/customers/v1/.*"
生成测试代码
// then:
assertThat(response.statusCode()).isEqualTo(201);
assertThat(response.header("Location")).matches("http://localhost/customers/v1/.*");
这按预期工作。我不知道为什么。有人可以解释一下吗?
在使用 POST
方法创建新资源时,新资源的位置将作为 Location
header.
如何创建一个 spring-cloud-contract YML 来验证响应是否包含 Location
header 以及有效的 URI
值?
我尝试使用以下 YAML,但它不起作用。
request:
method: POST
url: /customers/v1
body:
firstName: First Name
lastName: Last Name
dateOfBirth: "1990-12-12"
active: false
headers:
Content-Type: application/json
response:
status: 201
matchers:
headers:
- key: Location
regex: "http://localhost/customers/v1/*"
生成测试代码
@Test
public void validate_create_customer_successfully() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"firstName\":\"First Name\",\"lastName\":\"Last Name\",\"dateOfBirth\":\"1990-12-12\",\"active\":false}");
// when:
ResponseOptions response = given().spec(request)
.post("/customers/v1");
// then:
assertThat(response.statusCode()).isEqualTo(201);
}
生成的代码不包含任何 header 验证。
我还没有测试过,但是如果你尝试会发生什么:
response:
status: 201
matchers:
headers:
- key: Location
type: by_regex
predefined: url
这就是您将用于 body 匹配器的内容,我不确定它是否适用于 headers。
只是想让你知道。我相信匹配器部分只是为了响应的测试方的利益(验证生产者发出的响应)。如果您还想将此 header 作为存根响应提供给您的消费者,则必须将其添加到匹配器部分之外并使用固定值。
以下 yaml 定义有效
response:
status: 201
headers:
Location: "http://localhost/customers/v1/"
matchers:
headers:
- key: Location
regex: "http://localhost/customers/v1/.*"
生成测试代码
// then:
assertThat(response.statusCode()).isEqualTo(201);
assertThat(response.header("Location")).matches("http://localhost/customers/v1/.*");
这按预期工作。我不知道为什么。有人可以解释一下吗?