Search code examples
spring-cloud-contract

Spring Cloud Contract YAML header matching


While creating a new resource using POST method, location of the new resource is added to response as Location header.

How to create a spring-cloud-contract YML to verify that response contains Location header with a valid URI as it's value?

I tried with below YAML, but it doesn't work.

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/*"

Generated code for test

@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);
}

Generated code doesn't contain any header validation.


Solution

  • Below yaml definition works

    response:
      status: 201
      headers:
          Location: "http://localhost/customers/v1/"
      matchers:
        headers:
          - key: Location
            regex: "http://localhost/customers/v1/.*"
    

    Generated code for test

    // then:
        assertThat(response.statusCode()).isEqualTo(201);
        assertThat(response.header("Location")).matches("http://localhost/customers/v1/.*");
    

    This works as expected. I don't know why. Can someone please explain?