首页 > 解决方案 > Spring Cloud Contract YAML 头匹配

问题描述

使用方法创建新资源POST时,新资源的位置作为Location标头添加到响应中。

如何创建一个 spring-cloud-contract YML 来验证响应是否包含Location具有有效值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);
}

生成的代码不包含任何标头验证。

标签: spring-cloud-contract

解决方案


以下 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/.*");

这按预期工作。我不知道为什么。有人可以解释一下吗?


推荐阅读