https://kotlinlang.org logo
Title
j

Jonathan Olsson

05/02/2023, 6:26 AM
Is there any library that helps with json introspection? Coming from spock+groovy, using kotest+serializationx is a bit ... crude for e2e testing of web services.
e

Emil Kantis

05/02/2023, 6:40 AM
What do you want to do? There’s json assertions if that’s what you need
j

Jonathan Olsson

05/02/2023, 6:47 AM
obj = {
    "id": "someId",
    "someList": [
        {
            "a": "foo"
        }
    ]
}
I want to be able to do something along the lines of:
obj.id shouldBe "someId"
obj.someList[0].a shouldBe "foo"
Without having to define all the necessary data classes.
I guess it would be possible to achieve:
obj["id"] shouldBe "someId"
obj["someList"][0]["a"] shouldBe "foo"
Not as "fancy" as groovy for this purpose, but would be good enough for my purposes.
e

Emil Kantis

05/02/2023, 7:04 AM
obj shouldEqualJson {
  fieldComparison = FieldComparison.Lenient // Ignore properties not defined in `expected`
  """
  {
    "id": "someId",
    "someList": [{ "a": "foo" }]
  }
  """
}
j

Jonathan Olsson

05/02/2023, 7:14 AM
Interesting. Yes, this will help a lot. Won't however help with another convenient thing with the dynamic approach of groovy, field extraction. For instance:
id = obj.someList[0].a

//
callSomeOtherApiWithId(id)
e

Emil Kantis

05/02/2023, 7:17 AM
Personally I often use rest-assured for testing APIs. You can do body-assertions and extractions with it. They have a Kotlin DSL module
your example could look like
val id = When {
  get("/api/v1/hello")
} Then {
  body("id", equalTo("someId"))
  body("someList[0].a" equalTo("foo"))
} Extract {
  body().jsonPath().getString("id")
}

println(id) // > someId