In a Spring Boot REST application, I want to check with Cucumber-jvm that the returned JSON is exactly what I expect. However, because I have to use double quotation around JSON key names, Cucumber cannot detect the correct step definition method and thus the test cannot pass.
Here is the expected JSON result:
{"fields":[],"errorMsg":"BIN not found"}
Cucumber step definition:
Given bin number is <bin>
When binlookup searches with this bin number
Then binlookup returns <result> and status code <code>
Examples:
| bin | result | code |
| "222222" | "{\"fields\":[\"bin\"]\,\"errorMsg\":\"Invalid Argument\"}" | 404 |
The corresponding method:
@Then("^binlookup returns \"([^\"]*)\" and status code \\d$")
public void binlookup_returns_and_status_code(String result, Integer code) throws Exception {
assertThat(this.results.getResponse().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8_VALUE);
assertThat(this.results.getResponse().getStatus()).isEqualTo(code);
assertThat(this.results.getResponse().getContentAsString().length()).isNotEqualTo(0);
assertThat(this.results.getResponse().getContentAsString()).isEqualTo(result);
}
When running the test, I do have correct returned JSON:
{"fields":["bin"],"errorMsg":"Invalid Argument"}
But I see test errors and Cucumber cannot detect my method, and gives me tips like:
You can implement missing steps with the snippets below:
@Then("binlookup returns {string}\\:[],\\{string}\\:\\{string} and status code {int}")
public void binlookup_returns_and_status_code(String string, String string2, String string3, Integer int1) {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
Obviously, it pairs the first " with the first escaped " and sees {\"fields as the first parameter, but it is wrong.
But, I cannot quote the JSON string with ' ' because it will not be the case.
What can I do?
If it is impossible, how can I verify the JSON has the data I expect?
