In Postman tests I can validate if response has a given schema:
var jsonObject = pm.response.json();
var schemaResponse = {
"type": "object",
"properties": {
"ok": {
"type": "boolean"
},
"operation_id": {
"type": "string"
},
"push_ids": {
"type": "array",
"items": [
{
"type": "string"
}
]
},
"message_ids": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
]
},
"content_urls": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
]
},
"localized_ids": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
]
}
}
}
pm.test("Response Schema Validation", function() {
var result = tv4.validateResult(jsonObject, schemaResponse);
pm.expect(result.valid).to.be.true;
});
Can I do the same in Mule 4 Munit tests?
There is no out of the box option to do it. If you need a simple workaround you can use json-schema-validator as one of your validation steps. The problem with this is it will not throw an
AssertionException, but aJSON:SCHEMA_NOT_HONOUREDerror, due to which your test will be treated as Errored out instead of the expected Failed. Therefore I will not recommend this approach.The correct way to do this is to create your own custom assertion and use
Run Custom Event Processor. The official MuleSoft document (link) describes the process with a simple and good explanation on how to implement a custom assertion class.Basically, you will need to create a Java class that will implement
MunitAssertioninterface and use a Java Library to do the schema validation. You can pick from a variety of Java library available like everit-org/json-schema