%dw 2.0
output application/json
---
{
"foo" : "var"
}
Mocking Resources for Your Tests
As your tests suites start to get bigger and more complex, it’s a good practice to externalize some parts of the test code, not only so that you can keep the code clean and organized but also so that you can reuse the files that you need to mock for your tests.
Mule 3 uses a getResourceAsString()
function to incorporate external or mocked resources into your tests. In Mule 4, you can leverage DataWeave to mock your test code, either by creating DataWeave scripts or by using variables in a DataWeave module.
Mocking Files Using DataWeave File
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:
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
.
Mocking Files Using Variables in a DataWeave Module
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 a couple of 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>