spring-cloud-contract

Spring cloud contract: is possible to use constant from Java in groovy Contract file?


I would like to share constants from Java classes in groovy Contracts.

Test base class:

    @SpringBootTest(classes = TestBase.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestBase {

    public static final String NAME = "just constant";

    @Before
    public void setup() {
        RestAssured.baseURI = "https://rest-service.com";
        RestAssured.port = 443;
    }
}

Contract file:

package contracts.test_contract

import org.springframework.cloud.contract.spec.Contract
import static test.TestBase.NAME;

Contract.make {
    request {
        method 'GET'
        url ''
        body (
                """${value(client(NAME), server(NAME))}"""
        )
    }
    response {
        status 200
    }
}

pom.xml - spring cloud contract plugin config:

<plugin>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-contract-maven-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <testMode>EXPLICIT</testMode>
                    <baseClassForTests>test.TestBase</baseClassForTests>
                </configuration>
            </plugin>

Running mvn clean install and getting

[ERROR] Exception occurred while trying to evaluate the contract at path [C:\dev\_idea_workspace\test_1\src\test\resources\contracts\test_contract\c1.groovy]
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\dev\_idea_workspace\test_1\src\test\resources\contracts\test_contract\c1.groovy: 7: unable to resolve class test.TestBase
 @ line 7, column 1.
   import static test.TestBase.NAME;
   ^

1 error

But when I try to import statically constant from another file, like Long.MAX_VALUE, it works.

Any suggestions how to go over this or how to share variable in more groovy contract files? Thanks!


Solution

  • Yes, please read this section of the documentation - https://docs.spring.io/spring-cloud-contract/docs/current/reference/html/advanced.html#customization-customization . Here you can see the code with shared stuff - https://github.com/spring-cloud-samples/spring-cloud-contract-samples/tree/main/common . Here you can see how it's added on the producer side https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/main/producer/pom.xml#L106-L111 and here on the consumer https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/main/consumer/pom.xml#L63-L68