Search code examples
groovyspring-cloud-contract

How can I build my own checks for spring cloud contract DSL, without regex


Example json:

{ id: 50,
  dateTime: "2017-03-09T10:26: }

Instead of writing a regex to accept any number for the id, I want to check if it is parseable to Integer.

For the dateTime I could write something like '([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9])' (from RegexPatterns class) but I just want to check that its parseable to LocalDateTime.

Solution from Marcin's answer:

In the contract:

id: $(consumer(50), producer(execute('isInteger($it+"")'))),
dateTime: $(consumer('2017-03-09T10:26'), producer(execute('isLocalDate($it)'))),

In the BaseClass:

public void isLocalDate(String date) {
    boolean parseAble = false;
    try {
        LocalDateTime.parse(date);
        parseAble = true;
    } catch (DateTimeParseException e) {
    }
    assertThat(parseAble).isEqualTo(true);
}

public void isInteger(String value) {
    boolean parseAble = false;
    try {
        Integer.parseInt(value);
        parseAble = true;
    } catch (NumberFormatException e) {
    }
    assertThat(parseAble).isEqualTo(true);
}

Solution

  • You can use the execute method and create your own method to parse the value. You can also provide your own customizations and write your own methods. Check this http://cloud.spring.io/spring-cloud-static/spring-cloud-contract/1.0.3.RELEASE/#_executing_custom_methods_on_server_side and this http://cloud.spring.io/spring-cloud-static/spring-cloud-contract/1.0.3.RELEASE/#_extending_the_dsl respectively for more information