I'm working with Spring Boot and REST Assured to test REST APIs. I was trying the example with JSON schema validation but it throws this error:
java.lang.IllegalArgumentException: Schema to use cannot be null
According to documentation, the schema should be located in the classpath. My example schema is located there. Here is my project structure and example schema location:
Here is my code. Without schema validation it works fine.
given().
contentType("application/json").
when().
get("http://myExample/users").
then().
assertThat().body(matchesJsonSchemaInClasspath("example_schema.json"));
Here, we have to add the JSON body whose scheme we want to validate. Then click on the Generate Schema button. Then the corresponding scheme for the JSON gets generated at the bottom of the page. Let us create a JSON file, say schema.
We can get a JSON field in a complex nested JSON using Rest Assured. First, we shall obtain a Response body which is in JSON format from a request. Then convert it to string. We shall send a GET request via Postman on a mock API URL and observe its Response.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
Your schema file is in the rest.resource
package but you haven't mentioned that when calling matchesJsonSchemaInClasspath
. You either need to move the file to the root of the classpath (put it in src/test/resources
, for example), or change the string you're passing into matchesJsonSchemaInClasspath
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With