Hamcrest matcher with slashes is interpreted as a part of validation
Asked Answered
D

3

10

I have the following validation where I have to check if returned body has a string containing "id": 6354, but it interprets slashes of special characters. How I can validate strings which contain double quotation marks ?

Code

import static org.hamcrest.Matchers.containsString;
import com.jayway.restassured.response.Response;


    response.then()
            .body(containsString("\"id\": 6354"));

Error

Response body doesn't match expectation.
Expected: a string containing "\"id\": 6354"
  Actual: {...,"id": 6354, ...}
Deutsch answered 21/8, 2015 at 11:19 Comment(4)
What's the code of containsString?Saunder
@NiklasP I've updated the question,Deutsch
Could you provide an example of the JSON document?Brosy
How did you fix this? Got the same problemRiorsson
F
3

Hamcrest containsString seems to print the escaped characters in the output error message, however it seems to correctly escape them when doing the matching.

In my example, I was incorrectly adding a space, so following the example in the question: "id": 6354 would give the error Expected: a string containing "\"id\": 6354" however when I changed it to "id":6354", it passed the assertion.

Forum answered 16/7, 2018 at 10:54 Comment(1)
I experience the same behavior here with the actual matching working correctly even though the output error message prints the escape characters; as a reference I am using Hamcrest 1.3. Perhaps this behavior is different in a newer version?Stercoraceous
R
2

I think there is something wrong with the escape slash. So I used:

assertTrue(response.contains("\"id\":6354"));
Riorsson answered 12/3, 2017 at 11:16 Comment(0)
U
0

I had a similar seemingly perplexing problem, but the solution was simple. I was comparing a non-String object with a String therefore it failed. The confusion comes in because the description of non-String object looks like a String without the escape characters.

To solve the problem, I changed:

assertThat(message, is(expectedLog));

to:

assertThat(message.toString(), is(expectedLog)); 
Unskillful answered 10/5, 2018 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.