如何使用 Spring Cloud Contracts 在 Stub 中将 NULL 值设置为 clientValue

How to set NULL values in Stub as clientValue with Spring Cloud Contracts

我们正在尝试将 null 值设置到生产者客户端站点代码中。

Groovy 合同示例:

Contract.make {
        description("Creating user")
        name("Create user")
        request {
            method 'POST'
            url '/api/user'
            body(
                    name: $(consumer(anyNonEmptyString()), producer('John Doe')),
                    address: $(consumer(optional(regex(alphaNumeric()))), producer(null))
            )
            headers {
                contentType(applicationJson())
            }
        }
        response {
            status 201
        }
    }

以下合约在尝试解析 Groovy 合约时产生断言失败:

assert testSide ==~ Pattern.compile(stubSide.optionalPattern())
   |        |           |       |        |
   null     false       |       |        ([a-zA-Z0-9]+)?
                        |       ([a-zA-Z0-9]+)?
                        ([a-zA-Z0-9]+)?

在生成的 class 中将其设置为 null 以获得这样的结果的任何建议(或者只是不添加字段 address:

@Test
public void create_user() throws Exception {
    // given:
        MockMvcRequestSpecification request = given()
                .header("Content-Type", "application/json")
                .body("{\"name\":\"John Doe\",\"address\": null,");

    // when:
        ResponseOptions response = given().spec(request)
                .post("/api/user");

    // then:
        assertThat(response.statusCode()).isEqualTo(201);
}

Spring 云合同中存在一个问题,我们将可选 属性 视为设置为空或非空的值,但它必须存在。通过修复 https://github.com/spring-cloud/spring-cloud-contract/issues/1257,我们还添加了对 null 值的支持。