Getting started Community Training Tutorials Documentation APIs, AI & Tools
%dw 2.0
output application/json
---
{
"foo" : "var"
}
Externalize mock data for MUnit tests using DataWeave scripts or modules to keep your test code clean and reusable. Use DataWeave files or variables in a DataWeave module to centralize mocked payloads and responses.
You can write a DataWeave file that returns the data that you want to mock, save the file under a folder in src/test/resources and then use a DataWeave function from your test to read this file.
For example, imagine that you have defined a mockPost.dwl file in the src/test/resources/sample_data folder with the following content:
%dw 2.0
output application/json
---
{
"foo" : "var"
}
This DataWeave file (mockPost.dwl) is a sample that creates a mock payload that you want to return in an http:request request.
When configuring the then-return section in the mock-when, use the readUrl function to read the mapping file:
<munit-tools:then-return>
<munit-tools:payload value="#[readUrl('classpath://sample_data/mockPost.dwl')]" mediaType="application/json" encoding="UTF-8" />
</munit-tools:then-return>
The classpath-based URL uses the classpath: protocol prefix to find the file defined in src/test/resources.
You can create a DataWeave module to centralize all your mocked data in a single file by declaring it using DataWeave variables.
For example, imagine that you create a custom DataWeave module by creating a TestData.dwl file in src/test/resources, and you add variables with references to different mocked data, either from files or inline:
import getResourceAsString from MunitTools
var mockPost = readUrl('classpath://sample_data/mockPost.dwl')
var foo = "N123"
var jsonFromFile = read(getResourceAsString('sample_data/mydata.json'), 'application/json')
var jsonObject = { paymentID: "1B56925769601335TLQMIWVY" }
You can then access any of the defined variables in the DataWeave module by importing the variables from your module:
<munit-tools:then-return >
<munit-tools:variables>
<munit-tools:variable key="ticket" value="#[import TestData output application/json --- TestData::mockPost]" mediaType="application/json" />
</munit-tools:variables>
</munit-tools:then-return>