Home > Software engineering >  set dynamic date in json for spock test
set dynamic date in json for spock test

Time:07-30

having below unit test case in spock

@ActiveProfiles("local")
@ContextConfiguration
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = [DemoAppApplication])
class DemoAppIT extends Specification {

    @LocalServerPort
    int localServerPort

    def setup() {
        RestAssured.port = localServerPort
    }

    def 'test' () {
        expect:
        given()
            .contentType(ContentType.JSON)
            .when()
            .body(Paths.get(getClass().getResource("/testdata/request.json").toURI()).toFile().text)
            .get('/hello')
            .then()
            .statusCode(200)

    }
}

below is request.json file

    {
      "trainingDate": "2022-08-10",
      "code": "ZMD",
      "name": "demo"
    }

here I want to populate trainingDate field as dynamically. dynamic value should be current date 10 days with the same above format.

when I pass the request body to the /hello api, the date should passed as dynamically.

for example:

current date is 2022-07-01 and want to plus 10 days in request body everytime. with the YYYY-MM-dd format

any possibilities there to do this?

Note: I'm maintaining request in file

CodePudding user response:

Just use a GString with the code @OleVV already shared in the comment.

@ActiveProfiles("local")
@ContextConfiguration
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = [DemoAppApplication])
class DemoAppIT extends Specification {

    @LocalServerPort
    int localServerPort

    def setup() {
        RestAssured.port = localServerPort
    }

    def 'test' () {
        expect:
        given()
            .contentType(ContentType.JSON)
            .when()
            .body("""
    {
      "trainingDate": "${LocalDate.now(ZoneId.systemDefault()).plusDays(10)}",
      "code": "ZMD",
      "name": "demo"
    }
            """)
            .get('/hello')
            .then()
            .statusCode(200)

    }
}

Edit:

As OP really want to keep the original file, here a way to do it. We have to replace the text in the file, there are always trade-offs on how to do it, either with placeholders or simple text replacement, or unmarshalling and marshalling of json.

To be as close to the original request, I'll go with text replacement.

def originalBody = Paths.get(getClass().getResource("/testdata/request.json").toURI()).toFile().text
def newBody = originalBody.replace("2022-08-10", LocalDate.now(ZoneId.systemDefault()).plusDays(10).toString())

then just use newBody in the request.

  • Related