Hamcrest matcher with slashes is interpreted as a part of validation

陌路散爱 提交于 2021-02-07 13:01:25

问题


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

回答1:


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

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/32139002/hamcrest-matcher-with-slashes-is-interpreted-as-a-part-of-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!