Testing Dataweave With MUnit
In this post, we take a look at how to configure and test your Dataweave app using Mulsesoft's MUnit tool. Read on for more detail!
Join the DZone community and get the full member experience.
Join For FreeIts easier to test data weave when developing the code using the previewer, but when you are moving the code into CI/CD we need an automated testing where Munit comes into the picture. Most developers use an entire flow to test Dataweave, but this is not the recommended way.
Many developers are not using one of the best-hidden features of Dataweave, which is referring a dwl file from resources.
The advantages of using a separate dwl file are:
Cleaner XML files.
Reusability.
Easy testing.
In this article, I am going to show you how to test Dataweave alone, using a simple example.
{
"Name":"satheesh",
"Role":"Engineer",
"ID":"12343534"
}
This JSON needs to be converted to
{
"Name":"satheesh",
"ID":"12343534",
"Email":"sath1234@abc.com"
}
The Dataweave code for this should look like what I've got below:
%dw 1.0
%output application/json
---
{
Name: payload.Name,
ID: payload.ID,
Email: payload.Name[0..3] ++ payload.ID[0..3] ++ "@abc.com"
}
Now let create a new dwl file under src/main/resources/mapping
Add the Dataweave code in the file and refer to the file in the transform message, as shown below.
Now your config.xml will look cleaner and the Dataweave file can be used in other transformations too.
<flow name="sftp-testFlow">
<sftp:inbound-endpoint connector-ref="SFTP" host="xxxxx" port="22" path="xxxxxxx" user="santonyraj" password="yyyyyyy" responseTimeout="10000" doc:name="SFTP"/>
<byte-array-to-string-transformer doc:name="Byte Array to String"/>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
<dw:transform-message doc:name="Transform Message">
<dw:set-payload resource="classpath:mapping/sample.dwl"/>
</dw:transform-message>
</flow>
Now let's see how to test the file using Munit:
Create an MUnit test suite.
Use a set Message to set your payload.
Use a transform message and refer your dwl file (Don't use UI to refer the file as it will overwrite the original one. Instead, use the xml and add <dw:set-payload resource="classpath:mapping/sample.dwl"/> in the transform message).
Use assert payload to check your output.
The config.xml should look like this:
<munit:test name="dataweave-test" description="Test">
<munit:set payload="#[getResource('input.json').asString()]" doc:name="Set Message"/>
<dw:transform-message doc:name="Transform Message">
<dw:set-payload resource="classpath:mapping/sample.dwl"/>
</dw:transform-message>
<munit:assert-payload-equals expectedValue="#[getResource('output.json').asString()]" doc:name="Assert Payload"/>
</munit:test>
In this way, all the mapping can be tested.
Opinions expressed by DZone contributors are their own.
Comments