I would like to get assert the response body using REST Assured. But currently I am not able to do so. I am getting the below-mentioned error message.
Implementation detail is as follows :
BannerDto resultBannerDto = given()
.contentType("application/json")
.body(bannerAddDto)
.when()
.post("/api/v1/admin/banners")
.then()
.statusCode(HttpStatus.OK.value())
.contentType(ContentType.JSON)
.body("name", equalTo("banner A"))
//this line make error:
.body("regions", equalTo(regionsSet.toString()))
.extract().as(BannerDto.class);
while error is:
java.lang.AssertionError: 1 expectation failed.
JSON path regions does not match.
Expected: [1, 2]
Actual: [1, 2]
parameter regionsSet is:
private Set<Long> regionsSet = new HashSet<>();
regionsSet.add(1l);
regionsSet.add(2l);
and Response of the Service is as follows:
{regions=[1, 2], endDate=2017-05-01T22:00:00, productIds=[], bannerId=15,...
The solution is pretty simple after looking into your response body. What you are trying to do :
.body("regions", equalTo(regionsSet.toString()))
here is collecting the data of regions
from response body which is currently a JsonArray and comparing it with string due to which your case is failing. Here below I have given a little code which will clarify your issue. Over here I am using Gson Library :
public class Simple {
public static void main(String[] arg) {
Set<Long> regionsSet = new LinkedHashSet<>();
regionsSet.add(1l);
regionsSet.add(2l);
Gson gson = new Gson();
JsonArray jr = new JsonArray();
jr.add(1);
jr.add(2);
System.out.println("Not Equal now : " + jr.equals(gson.toJson(regionsSet).toString()));
System.out.println("Equal now : " + jr.toString().equals(gson.toJson(regionsSet).toString()));
}
}
Sample output :
Not Equal now : false
Equal now : true
Hope this clarified your problem and made you understand how to proceed.