Home > Enterprise >  Kotlin rest-assured collection matcher
Kotlin rest-assured collection matcher

Time:11-17

Could anyone help with right restassured matcher? I have a custom error message, that is returned by rest controller advice. It contains a meta field, which stores object with code and description.

I'm writing a test, where i'm trying to check whether the right meta is present, so:

body("meta", hasItem(ErrorDto(code = "code", description = "description")))

I get an error:

java.lang.AssertionError: 1 expectation failed.
JSON path meta doesn't match.
Expected: a collection containing <ErrorDto(code=code, 
description=description)>
  Actual: <[{code=code, description=description}]>

It seems that hasItem is not suitable at this case. I've tried to use other Matcher, but i get the same error... P.S. the index approach works fine, but imho it's a little ugly...

body("meta[0].code", equalTo("code"))
body("meta[0].description", equalTo("description"))

I'm trying to solve this for few hours and i' completely stuck... Any ideas?

CodePudding user response:

Problem: As far as I know, RestAssured will map

  • array (json) <--> List (java)
  • object (json) <--> LinkedHashMap (java)

Therefore, body("meta") --> return List of LinkedHashMap. You can't compare Object to LinkedHashMap.

Solution:

To make a list of ErrorDto, you need to tell RestAssured which type will be converted to.

Below is java version.

List<ErrorDto> list = response.jsonPath().getList("", ErrorDto.class);

Then you can use Hamcrest to assert

assertThat(list, hasItems(new ErrorDto("code", "description")));
  • Related