ashur
ashur

Reputation: 4307

Hamcrest matcher with slashes is interpreted as a part of validation

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, ...}

Upvotes: 10

Views: 3243

Answers (3)

Adam Beddoe
Adam Beddoe

Reputation: 173

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.

Upvotes: 3

Dagmar
Dagmar

Reputation: 3261

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)); 

Upvotes: 0

vanlooverenkoen
vanlooverenkoen

Reputation: 2301

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

assertTrue(response.contains("\"id\":6354"));

Upvotes: 2

Related Questions