Keifer
Keifer

Reputation: 175

Spring Cloud Contract Verifier Test Generating Unwanted Asserts

I have the following YAML contract:

request:
  method: GET
  url: /get
response:
  status: 200
  body:
    name: 'Name'
    code: '123'
    asOfDate: '1994-05-25T04:00:00.000Z'
  matchers:
    body:
    - path: "$[*].name"
      type: by_type
    - path: "$[*].code"
      type: by_regex
      value: '[0-9]{3}'
    - path: "$[*].asOfDate"
      type: by_regex
      predefined: iso_date_time

Which generates the following test code:

        // and:
            DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
            assertThatJson(parsedJson).field("['code']").isEqualTo("123");
            assertThatJson(parsedJson).field("['asOfDate']").isEqualTo("1994-05-25T04:00:00.000Z");
            assertThatJson(parsedJson).field("['name']").isEqualTo("Name");
        // and:
            assertThat((Object) parsedJson.read("$[*].name")).isInstanceOf(java.util.List.class);
            assertThat((java.lang.Iterable) parsedJson.read("$[*].code", java.util.Collection.class)).allElementsMatch("[0-9]{3}");
            assertThat((java.lang.Iterable) parsedJson.read("$[*].asOfDate", java.util.Collection.class)).allElementsMatch("ignore");

My issue is that I do not want the contract to force the code to match values exactly (the first three asserts). I only want the contract to generate the last three asserts (the ones that check for correct typing).

Is there something I am not writing correctly in the YAML contract? Worth noting that removing "asOfDate" from the response body generates the asserts I want, but if I remove "name" and "code", no asserts will be generated at all.

Upvotes: 1

Views: 330

Answers (2)

Daemon2017
Daemon2017

Reputation: 180

If you only want to use checks from response->matchers->body and don't want to use checks from response->body, you can do a trick that Marcin suggested:

request:
  method: GET
  url: /get
response:
  status: 200
  body:
    name: $.name
    code: $.code
    asOfDate: $.asOfDate
  matchers:
    body:
    - path: "$[*].name"
      type: by_type
    - path: "$[*].code"
      type: by_regex
      value: '[0-9]{3}'
    - path: "$[*].asOfDate"
      type: by_regex
      predefined: iso_date_time

As a result, you will have no asserts like:

assertThatJson(parsedJson).field("['name']").isEqualTo("Name");

but only:

assertThat(parsedJson.read("$[*].code", String.class)).matches("[0-9]{3}");

Upvotes: 0

Marcin Grzejszczak
Marcin Grzejszczak

Reputation: 11159

I think your paths are wrong. You should write $.name, $.code and $.asOfDate. Then SC-Contract will remove these entries from automatic generation.

Upvotes: 1

Related Questions