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, ...}
ashur
  • 4,177
  • 14
  • 53
  • 85

3 Answers3

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.

Adam Beddoe
  • 153
  • 2
  • 10
  • 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? – risingTide Mar 03 '21 at 17:11
2

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

assertTrue(response.contains("\"id\":6354"));
vanlooverenkoen
  • 2,121
  • 26
  • 50
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)); 
Dagmar
  • 2,968
  • 23
  • 27