In REST API Mule development in which system returns a JSON response, it is always advisable to write MUnit tests and assert the entire JSON response payload to avoid contract conflicts/mismatches.

Objective:

Our objective is loading expected JSON data from a file and comparing it with actual MUnit payload which we got from the tested flow.

Problem Description:

If You are using Mule 4 and seeing MUnit test fails comparing JSON string payload to another JSON string.
The application produces an output similar to below:
%dw 2.0
output application/json

{
  message: “Success PUT”
}

The sample payload below to compare for the MUnit test is saved in a file:
{“message”:”Success PUT”}

After running your MUnit you may get similar error like below:

java.lang.AssertionError: The response payload is not correct! at file: [munit-for-apikit-flow-part2-mule4-apikit-test.xml], line: [22]
Expected: “{“message”:”Success PUT”}” as String {class: “java.lang.String”}
     but: “{n  “message”: “Success PUT”n}” as String {encoding: “UTF-8”, mediaType: “application/java; charset=UTF-8”, mimeType: “application/java”, class: “java.lang.String”, contentLength: 30} at (root)

at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)

Problem Solution:

Use “readUrl” function to compare both types as JSON with JSON:

<munit-tools:assert-that expression=”#[%dw 2.0 output application/json —payload]” is=’#[MunitTools::equalTo(readUrl(“classpath://scaffolder/response/put_201_apikit-put_application_json.json”, “application/json“))]’ message=”The response payload is not correct!” doc:name=”Assert That – Payload is Expected” doc:id=”bb6653e2-3022-4644-9099-204d13a5fce6″/>
   

Please find sample Mule project in Github munit-for-apikit-flow-part1-mule4

Happy Learning 🙂

By Manish Kumar

I am having around 10 years of IT experience in Integration Architecture, Requirement gathering, Effort Estimation, Application Design\Development\Testing and Deployment including 5+ years of experience in MuleSoft ESB and Hybrid Integrations. DevOps and Cloud Integration is my area of interest.

2 thoughts on “Comparing JSON string payload to another JSON string – Mule4”

Leave a Reply

Your email address will not be published. Required fields are marked *