# mulesoft MUnit - Full Documentation --- product: MUnit version: 2.3 --- # Assert Equals > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Assert Equals processor allows you to run assertions in order to validate the state of a Mule Event’s content. This processor can be used to validate the Mule Event after the production code runs. For example, to assert that a payload is equal to a certain value, you can configure the Assert-Equals processor the following way: ```xml ``` If the `expected` attribute is a String, you can specify the literal value without requiring an expression. ```xml ``` If this assertion fails, the processor throws a `java.lang.AssertionError`. --- product: MUnit version: 3.6 --- # Assert Equals > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Assert Equals processor allows you to run assertions in order to validate the state of a Mule Event’s content. This processor can be used to validate the Mule Event after the production code runs. For example, to assert that a payload is equal to a certain value, you can configure the Assert-Equals processor the following way: ```xml ``` If the `expected` attribute is a String, you can specify the literal value without requiring an expression. ```xml ``` If this assertion fails, the processor throws a `java.lang.AssertionError`. --- product: MUnit version: 2.3 --- # Assert Expression > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Assert Expression processor allows you evaluate a Dataweave expression that asserts the state of a Mule Event’s content. This processor can be used to validate the Mule Event after the production code runs, using the [DataWeave Assertions Library](https://docs.mulesoft.com/munit/2.3/dataweave-assertions-library). For example, to assert that a payload is equal to a certain value, you can configure the Assert-Expression processor using the equalTo() matcher. ```xml #[ import * from dw::test::Asserts --- payload must equalTo('example') ] ``` ## Perform Complex Assertions The DW assertions library allows you to assert the state of the Mule Event’s content in a deeper way. ```xml #[ import * from dw::test::Asserts --- vars.attributes must [beObject(), $.statusCode must equalTo(200), $.method must equalTo('GET')] ] ``` ## Create your own Matcher To create your own matcher, you can add DW files to your `src/test/resources` folder. For example, a file called `MyMatcher.dwl` with the following content: ```dataweave import * from dw::test::Asserts fun beEven(): Matcher = (actual:Number) -> do { var matchesEven = (actual mod 2) == 0 --- { matches: matchesEven, description: {expected: " to be an even number.", actual: write(actual) as String} } } ``` And then use it in your Assert-Expression processor: ```xml #[ import * from dw::test::Asserts --- payload must MyMatcher::beEven() ] ``` If this assertion fails, the processor throws a `java.lang.AssertionError`. > [!WARNING] Matchers from the `dw::test::Asserts` library are not compatible with the `MunitTools` > matchers. You can’t use `dw::test::Asserts` with the Assert-That processor, and you can’t use > `MunitTools` matchers with the Assert-Expression processor. --- product: MUnit version: 3.6 --- # Assert Expression > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Assert Expression processor allows you evaluate a Dataweave expression that asserts the state of a Mule Event’s content. This processor can be used to validate the Mule Event after the production code runs, using the [DataWeave Assertions Library](https://docs.mulesoft.com/munit/3.6/dataweave-assertions-library). For example, to assert that a payload is equal to a certain value, you can configure the Assert-Expression processor using the equalTo() matcher. ```xml #[ import * from dw::test::Asserts --- payload must equalTo('example') ] ``` ## Perform Complex Assertions The DW assertions library allows you to assert the state of the Mule Event’s content in a deeper way. ```xml #[ import * from dw::test::Asserts --- vars.attributes must [beObject(), $.statusCode must equalTo(200), $.method must equalTo('GET')] ] ``` ## Create your own Matcher To create your own matcher, you can add DW files to your `src/test/resources` folder. For example, a file called `MyMatcher.dwl` with the following content: ```dataweave import * from dw::test::Asserts fun beEven(): Matcher = (actual:Number) -> do { var matchesEven = (actual mod 2) == 0 --- { matches: matchesEven, description: {expected: " to be an even number.", actual: write(actual) as String} } } ``` And then use it in your Assert-Expression processor: ```xml #[ import * from dw::test::Asserts --- payload must MyMatcher::beEven() ] ``` If this assertion fails, the processor throws a `java.lang.AssertionError`. > [!WARNING] Matchers from the `dw::test::Asserts` library are not compatible with the `MunitTools` > matchers. You can’t use `dw::test::Asserts` with the Assert-That processor, and you can’t use > `MunitTools` matchers with the Assert-Expression processor. --- product: MUnit version: 2.3 keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # Assert That Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Assert That event processor allows you to run assertions to validate the state of a Mule event’s content. You can use the Assert That processor to validate the Mule event after the production code runs. The Assert That processor uses a set of DataWeave functions called `MUnit matchers` to define the assertion conditions for any value in an expression. For example, to assert that a payload is equal to a certain value, configure the Assert That processor using the `equalTo()` matcher. ```xml ``` Or you can also check if the payload is null using the `nullValue()` matcher. ```xml ``` See [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) for more information. If these assertion fails, the processor throws a `java.lang.AssertionError`. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) --- product: MUnit version: 3.6 keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # Assert That Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Assert That event processor allows you to run assertions to validate the state of a Mule event’s content. You can use the Assert That processor to validate the Mule event after the production code runs. The Assert That processor uses a set of DataWeave functions called `MUnit matchers` to define the assertion conditions for any value in an expression. For example, to assert that a payload is equal to a certain value, configure the Assert That processor using the `equalTo()` matcher. ```xml ``` Or you can also check if the payload is null using the `nullValue()` matcher. ```xml ``` See [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) for more information. If these assertion fails, the processor throws a `java.lang.AssertionError`. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) --- product: MUnit version: 2.3 --- # Before and After Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Before Suite Scope The MUnit Before Suite contains code that is meant to be executed before the whole suite. The Before Suite has one execution rule: Run before all the tests, just once. For example, suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before Suite runs just once, before your four tests. > [!NOTE] You can only use one Before Suite scope per MUnit test suite. Before Suite example ```xml ``` Note that the `before-suite` is located outside the MUnit test. One instance in which the MUnit Before Suite is useful is when you need to set up a test environment before all tests run. When you place a before-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Suite Scope The MUnit After Suite is a scope. It can contain code that is meant to be executed after the whole suite. The After suite has one execution rule: Run after all the tests, just once. For instance, let’s suppose you have an MUnit Test Suite File with four tests. The code inside an MUnit After Suite, runs just once, after all your tests. > [!NOTE] You can only use one After Suite scope per MUnit test suite. After Suite example ```xml ``` Note that the after-suite is located outside the MUnit test. One instance in which the MUnit After Suite is useful is when you need to tear down a test environment after the whole test runs. When you place an after-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Test Scope The MUnit Before Test Scope contains code that is meant to be executed before each test. Each Before Test scope follows the same execution rule: Run before each test. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before test runs before each of your four tests; it runs four times. > [!NOTE] You can only use one Before Test scope per MUnit test suite. Before Test example ```xml ``` Note that the `before.test` is located outside the MUnit test. One instance in which the MUnit Before Test is useful is when you need to set up a test environment before each test run, like creating a file or setting a variable that will be consumed in each test. When you place an before-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Test Scope The MUnit After Test Scope contains code that is meant to be executed after each test. Each After Test scope follows the same execution rule: Run after each test. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit After Test runs after each of your four tests; it runs four times. > [!NOTE] You can only use one After Test scope per MUnit test suite. After Test example ```xml ``` Note that the `after.test` is located outside the MUnit test. One instance in which the MUnit After test is useful is when you need to tear down a test environment after the whole test runs. When you place an after-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Suite Reference
Attribute NameDescription

name

Defines the name of the Before suite. The name must be unique inside the suite.

description

Describes the actions performed.

## After Suite Reference
Attribute NameDescription

name

Defines the name of the After suite. The name must be unique inside the suite.

description

Describes the actions performed.

## Before Test Reference
Attribute NameDescription

name

Defines the name of the Before test. The name must be unique inside the suite.

description

Describes the actions performed.

## After Test Reference
Attribute NameDescription

name

Defines the name of the After test. The name must be unique inside the suite.

description

Describes the actions performed.

--- product: MUnit version: 3.6 --- # Before and After Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## Before Suite Scope The MUnit Before Suite contains code that is meant to be executed before the whole suite. The Before Suite has one execution rule: Run before all the tests, just once. For example, suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before Suite runs just once, before your four tests. > [!NOTE] You can only use one Before Suite scope per MUnit test suite. Before Suite example ```xml ``` Note that the `before-suite` is located outside the MUnit test. One instance in which the MUnit Before Suite is useful is when you need to set up a test environment before all tests run. When you place a before-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Suite Scope The MUnit After Suite is a scope. It can contain code that is meant to be executed after the whole suite. The After suite has one execution rule: Run after all the tests, just once. For instance, let’s suppose you have an MUnit Test Suite File with four tests. The code inside an MUnit After Suite, runs just once, after all your tests. > [!NOTE] You can only use one After Suite scope per MUnit test suite. After Suite example ```xml ``` Note that the after-suite is located outside the MUnit test. One instance in which the MUnit After Suite is useful is when you need to tear down a test environment after the whole test runs. When you place an after-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Test Scope The MUnit Before Test Scope contains code that is meant to be executed before each test. Each Before Test scope follows the same execution rule: Run before each test. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before test runs before each of your four tests; it runs four times. > [!NOTE] You can only use one Before Test scope per MUnit test suite. Before Test example ```xml ``` Note that the `before.test` is located outside the MUnit test. One instance in which the MUnit Before Test is useful is when you need to set up a test environment before each test run, like creating a file or setting a variable that will be consumed in each test. When you place an before-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Test Scope The MUnit After Test Scope contains code that is meant to be executed after each test. Each After Test scope follows the same execution rule: Run after each test. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit After Test runs after each of your four tests; it runs four times. > [!NOTE] You can only use one After Test scope per MUnit test suite. After Test example ```xml ``` Note that the `after.test` is located outside the MUnit test. One instance in which the MUnit After test is useful is when you need to tear down a test environment after the whole test runs. When you place an after-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Suite Reference
Attribute NameDescription

name

Defines the name of the Before suite. The name must be unique inside the suite.

description

Describes the actions performed.

## After Suite Reference
Attribute NameDescription

name

Defines the name of the After suite. The name must be unique inside the suite.

description

Describes the actions performed.

## Before Test Reference
Attribute NameDescription

name

Defines the name of the Before test. The name must be unique inside the suite.

description

Describes the actions performed.

## After Test Reference
Attribute NameDescription

name

Defines the name of the After test. The name must be unique inside the suite.

description

Describes the actions performed.

--- product: MUnit version: 2.3 --- # Comparable Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!NOTE] `Comparable` is a DataWeave type that represents all the types that can be compared to > each other. > Allowed primitives are String, Number, Boolean, DateTime, LocalDateTime, LocalTime, Time, and > TimeZone that you can pass any primitive value such as an integer or a date. ## greaterThan(Comparable) Checks that the expression is greater than the specified value. Example ```xml ``` Example ```xml ``` ## greaterThanOrEqualTo(Comparable) Checks that the expression is greater than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## lessThan(Comparable) Example ```xml ``` Example ```xml ``` ## lessThanOrEqualTo(Comparable) Checks that the expression is less than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## closeTo(Number, Number) Checks that the expression is close to the first number, using the second number as a delta value. In other words, checks that the expression belongs to the range defined by the first number +/- the second number. Example ```xml ``` ## equalTo(Object) Checks that the expression is equal to a specific value. Example ```xml ``` Example ```xml ``` This matcher also accepts Dataweave objects. Example ```xml ``` The matcher validates that the keys and their respective values are the same. The order in the matcher must be the same as the one in the expression or the assertion fails. Example ```xml ``` Example ```xml ``` ## See Also - [DataWeave Comparable Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_comparable) - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/2.3/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/2.3/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference) --- product: MUnit version: 3.6 --- # Comparable Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio > [!NOTE] `Comparable` is a DataWeave type that represents all the types that can be compared to > each other. > Allowed primitives are String, Number, Boolean, DateTime, LocalDateTime, LocalTime, Time, and > TimeZone that you can pass any primitive value such as an integer or a date. ## greaterThan(Comparable) Checks that the expression is greater than the specified value. Example ```xml ``` Example ```xml ``` ## greaterThanOrEqualTo(Comparable) Checks that the expression is greater than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## lessThan(Comparable) Example ```xml ``` Example ```xml ``` ## lessThanOrEqualTo(Comparable) Checks that the expression is less than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## closeTo(Number, Number) Checks that the expression is close to the first number, using the second number as a delta value. In other words, checks that the expression belongs to the range defined by the first number +/- the second number. Example ```xml ``` ## equalTo(Object) Checks that the expression is equal to a specific value. Example ```xml ``` Example ```xml ``` This matcher also accepts Dataweave objects. Example ```xml ``` The matcher validates that the keys and their respective values are the same. The order in the matcher must be the same as the one in the expression or the assertion fails. Example ```xml ``` Example ```xml ``` ## See Also - [DataWeave Comparable Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_comparable) - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/3.6/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/3.6/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference) --- product: MUnit version: 3.7 is-latest-version: true --- # Configure MUnit Coverage in Maven > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Configure MUnit coverage reports in Maven by adding the munit-maven-plugin to your pom.xml and enabling the coverage-report goal. Coverage reports are generated during the Maven site lifecycle and are not available when running tests from Anypoint Code Builder or Anypoint Studio. MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ## Coverage Report Types When you enable MUnit Coverage, the console displays a summary report. ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ==================================================================================== ``` MUnit Coverage offers four types of reports: - Console report The console report prints in the console. It works with the summary report and shows an overview of the MUnit run, with a count of all resources, flows, and processors, as well as the overall application coverage level, and warnings and errors if any. - HTML report The HTML report shows the same information as the console report but is formatted to fit any web browser. It’s available in the `${application.path}/target/site/munit/coverage/` path. - JSON report The JSON report provides the same information as the HTML report but in a JSON format. It’s available at `${application.path}/target/site/munit/coverage/munit-coverage.json`. - SONAR report The SONAR report shows the same information as the HTML report, in a SonarQube format. To enable the report generation, add the following configuration: MUnit Coverage - Report Configuration ```xml true console (1) html (2) json (3) sonar (4) ```
1Console report
2HTML report
3JSON report
4SONAR report
You can choose to have either none, one, or all the report types added to your configuration. To configure, for example, the JSON report generation, add the following configuration to your `pom.xml` file: ```xml true json ``` ## Set Up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level isn’t reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage isn’t defined, it defaults to -1, which sets no requirements for said level so the build doesn’t fail due to low coverage.
If you define coverage levels but set the property `failBuild` to `false`, and then the levels aren’t reached, a warning shows up in the MUnit Coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level isn’t met, and where it happens.
## Ignore a Flow or a File You can also ignore a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow isn’t tested or if the flow doesn’t reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## See Also - [Coverage Report](https://docs.mulesoft.com/munit/latest/munit-coverage-report) - [Run MUnit Coverage Reports in Anypoint Studio](https://docs.mulesoft.com/munit/latest/coverage-studio-concept). --- product: MUnit version: 3.7 is-latest-version: true --- # Configure the MUnit Database Server Utility > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Configure the MUnit Database Server utility to run MUnit tests against an in-memory database without connecting to an external database server. Use it to test Mule flows that interact with a database connector in an isolated and repeatable way. If you want to test the following Mule application: ```xml SELECT * FROM jobtitlelookup WHERE jobtitleid = :id ``` The file `db.properties` in `src/main/resources` has the following content: ```none db.config=Database_Config ``` You must create a test that: - Contains a database server with a `jobtitlelookup` table. - Provides a valid database structure for the database connector to perform its query. - Passes a value for the `jobid` variable that Database Connector uses. ## Install the MUnit DB Server Module 1. Look for the **MUnit Utils Database Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-dbserver-module 2.0.2 mule-plugin test ``` The MUnit DB server artifact in your POM file must have the `test` scope. 3. Add the `h2` dependency to your POM file and list it as `sharedLibrary` in `mule-maven-plugin`: ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` The **h2** dependency enhances MUnit tests by allowing the simulation of database interactions using an in-memory, lightweight, and fast database. This setup ensures tests are both isolated and repeatable. > [!NOTE] The **MUnit DB Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-dbserver-module/). > The **MUnit DB Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Define the MUnit DB Server Define the database server by creating the **global-configs.xml** file and defining the MUnit DB Server Config element. Define the MUnit DB Server Config element as follows: 1. Go to the `src/test/resources` directory in your project. 2. Create a file named `jobtitlelookup.csv` containing the following values: ```text JOBTITLE,EECSALARYORHOURLY,JOBTITLEID Developer,10,DEV ``` 3. Create the **global-configs.xml** file and define the **MUnit DB Server Config** element as follows: ```xml ``` 4. Define the DB configuration to connect to your DB server: ```xml ``` 5. Define the `db.properties` file in your `src/test/resources` folder that picks up your test database configuration: ```none db.config=Test_Database_Config ``` ## Run the Test After installing and configuring the DB server you can run the test: ```xml ``` This test validates that the query run in your production code is correct and that the DB server returns the payload as expected. ## See Also - [Database Util](https://docs.mulesoft.com/munit/latest/db-util) - [Add Modules to Your Test in Anypoint Code Builder](https://docs.mulesoft.com/anypoint-code-builder/ref-acb-commands) - [Add Modules to Your Test in Anypoint Studio](https://docs.mulesoft.com/studio/add-modules-in-studio-to) --- product: MUnit version: 3.7 is-latest-version: true --- # Configure the MUnit FTP Server Utility > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Configure the MUnit FTP Server utility to run MUnit tests against an in-memory FTP server without connecting to an external FTP server. Use it to test Mule flows that interact with FTP or SFTP connectors in an isolated environment. If you want to test the following Mule application: ```xml ``` The `ftp.properties` in `src/main/resources` has the following content: ```none ftp.host=localhost ftp.port=22 ftp.user=max ftp.password=munittest ``` The username field can’t be empty. If you don’t have a username-password pair, set the username to `anonymous` and don’t set any password. By default, the `anonymous` attribute is set to `true`. ## Install the FTP Server To install the FTP server: 1. Look for the **MUnit Utils FTP Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module 2.0.1 mule-plugin test ``` The MUnit FTP server artifact in your POM file must have the `test` scope. > [!NOTE] The **MUnit FTP Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-ftpserver-module/). > The **MUnit FTP Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Define the FTP Server To define the FTP server, change the FTP server attributes as follows: ```xml ---- ---- ``` ## Run the Test After configuring the FTP server, you can run the test: ```xml ``` This FTP accepts any user, so you must not set up a user database or list. ## See Also - [FTP Util](https://docs.mulesoft.com/munit/latest/ftp-util) --- product: MUnit version: 2.3 --- # Configuring Database Server Utility in an MUnit Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Assume that you want to test the following Mule application: ```xml SELECT * FROM jobtitlelookup WHERE jobtitleid = :id ``` The file `db.properties` in `src/main/resources` has the following content: ```none db.config=Database_Config ``` You need to create a test that: \* Contains a database server with a `jobtitlelookup` table. \* Provides a valid database structure for the database connector to perform its query. \* Passes a value for the `jobid` variable that Database Connector uses. ## Install the MUnit DB Server Module 1. From Anypoint Studio, go to the **Mule Palette** view and locate **Search in Exchange…​**. 2. In the search bar, look for **MUnit Utils Database Server** and add the module to your project: ```xml com.mulesoft.munit.utils munit-dbserver-module 2.0.2 mule-plugin test ``` The MUnit DB server artifact in your POM file must have the `test` scope. 3. Add the `h2` dependency to your POM file and list it as `sharedLibrary` in `mule-maven-plugin`: ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` ## Define the MUnit DB Server Define the database server using the **MUnit DB Server Config** from the **Global Elements** in your canvas. For this example, define the DB structure and content using a CSV file: 1. Go to the `src/test/resources` directory in your project. 2. Create a file named `jobtitlelookup.csv` containing the following values: ```text JOBTITLE,EECSALARYORHOURLY,JOBTITLEID Developer,10,DEV ``` 3. Navigate to the **Global Elements** tab and select the **MUnit DB Server Config** element. 4. Click **Edit** and complete the fields:
NameMUnit_DB_Server_Config

CSV

jobtitlelookup.csv

Database

DATABASE_NAME

Connection string parameters

MODE=MySQL

```xml ``` 5. Define the DB configuration to connect to your DB server:
NameTest_Database_Config

Connection

Generic connection

URL

jdbc:h2:tcp://localhost/mem:DATABASE_NAME

Driver class name

org.h2.Driver

```xml ``` 6. Define the `db.properties` file in your `src/test/resources` folder that will pick up your test database configuration: ```none db.config=Test_Database_Config ``` ## Run the Test After installing and configuring the DB server you can run the test: ```xml ``` This test validates that the query run in your production code is correct and that the payload returned by the DB server is as expected. ## See Also - [Database Util](https://docs.mulesoft.com/munit/2.3/db-util) --- product: MUnit version: 2.3 --- # Configuring FTP Server Utility in an MUnit Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Assume that you want to test the following Mule application: ```xml ``` The `ftp.properties` in `src/main/resources` has the following content: ```none ftp.host=localhost ftp.port=22 ftp.user=max ftp.password=munittest ``` The username field cannot be empty. If you do not have a username-password pair, set the username to `anonymous` and don’t set any password. By default, the `anonymous` attribute is set to `true`. ## Install the FTP Server 1. From Anypoint Studio, go to the **Mule Palette** view and locate **Search in Exchange…​**. 2. In the search bar look for **MUnit Utils FTP Server** and add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module 2.0.1 mule-plugin test ``` The MUnit FTP server artifact in your POM file must have the `test` scope. ## Define the FTP Server 1. In your Studio canvas, go to the **Global Elements** tab and select your **MUnit FTP Server Config** element. 2. Click **Edit** and complete the fields:
AttributeValue

Name

MUnit_FTP_Server_Config

Port

${ftp.port}

Username

${ftp.user}

Password

${ftp.password}

Secure

true

homeDir

${app.home}

```xml ``` ## Run the Test After configuring the FTP server you can run the test: ```xml ``` This FTP accepts any user, so there is no need to set up a user database or list. ## See Also - [FTP Util](https://docs.mulesoft.com/munit/2.3/ftp-util) --- product: MUnit version: 3.6 --- # Configuring the Database Server Utility in an MUnit Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio If you want to test the following Mule application: ```xml SELECT * FROM jobtitlelookup WHERE jobtitleid = :id ``` The file `db.properties` in `src/main/resources` has the following content: ```none db.config=Database_Config ``` You must create a test that: - Contains a database server with a `jobtitlelookup` table. - Provides a valid database structure for the database connector to perform its query. - Passes a value for the `jobid` variable that Database Connector uses. ## Install the MUnit DB Server Module 1. Look for the **MUnit Utils Database Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-dbserver-module 2.0.2 mule-plugin test ``` The MUnit DB server artifact in your POM file must have the `test` scope. 3. Add the `h2` dependency to your POM file and list it as `sharedLibrary` in `mule-maven-plugin`: ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` The **h2** dependency enhances MUnit tests by allowing the simulation of database interactions using an in-memory, lightweight, and fast database. This setup ensures tests are both isolated and repeatable. > [!NOTE] The **MUnit DB Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-dbserver-module/). > The **MUnit DB Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Define the MUnit DB Server Define the database server by creating the **global-configs.xml** file and defining the MUnit DB Server Config element. Define the MUnit DB Server Config element as follows: 1. Go to the `src/test/resources` directory in your project. 2. Create a file named `jobtitlelookup.csv` containing the following values: ```text JOBTITLE,EECSALARYORHOURLY,JOBTITLEID Developer,10,DEV ``` 3. Create the **global-configs.xml** file and define the **MUnit DB Server Config** element as follows: ```xml ``` 4. Define the DB configuration to connect to your DB server: ```xml ``` 5. Define the `db.properties` file in your `src/test/resources` folder that picks up your test database configuration: ```none db.config=Test_Database_Config ``` ## Run the Test After installing and configuring the DB server you can run the test: ```xml ``` This test validates that the query run in your production code is correct and that the DB server returns the payload as expected. ## See Also - [Database Util](https://docs.mulesoft.com/munit/3.6/db-util) - [Add Modules to Your Test in Anypoint Code Builder](https://docs.mulesoft.com/anypoint-code-builder/ref-acb-commands) - [Add Modules to Your Test in Anypoint Studio](https://docs.mulesoft.com/studio/add-modules-in-studio-to) --- product: MUnit version: 3.6 --- # Configuring the FTP Server Utility in an MUnit Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio If you want to test the following Mule application: ```xml ``` The `ftp.properties` in `src/main/resources` has the following content: ```none ftp.host=localhost ftp.port=22 ftp.user=max ftp.password=munittest ``` The username field can’t be empty. If you don’t have a username-password pair, set the username to `anonymous` and don’t set any password. By default, the `anonymous` attribute is set to `true`. ## Install the FTP Server To install the FTP server: 1. Look for the **MUnit Utils FTP Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module 2.0.1 mule-plugin test ``` The MUnit FTP server artifact in your POM file must have the `test` scope. > [!NOTE] The **MUnit FTP Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-ftpserver-module/). > The **MUnit FTP Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Define the FTP Server To define the FTP server, change the FTP server attributes as follows: ```xml ---- ---- ``` ## Run the Test After configuring the FTP server, you can run the test: ```xml ``` This FTP accepts any user, so you must not set up a user database or list. ## See Also - [FTP Util](https://docs.mulesoft.com/munit/3.6/ftp-util) --- product: MUnit version: 2.3 --- # Core Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## nullValue() Checks that the expression is null. Example ```xml ``` ## notNullValue() Checks that the expression is not null. Example ```xml ``` ## withMediaType(String) Checks that the expression’s media type is the one specified. Example ```xml ``` ## withEncoding(String) Checks that the expression encoding is the one specified. Example ```xml ``` ## both(Matcher, Matcher) Checks that both provided matchers are successful. Example ```xml ``` ## either(Matcher,Matcher) Checks that at least one of the matchers is successful. Example ```xml ``` ## not(Object) Checks if the provided matcher is not successful. Example ```xml ``` Example ```xml ``` ## anyOf(Array) Checks if any of the matchers are successful. Example ```xml ``` ## allOf(Array) Checks if all of the matchers are successful. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [String Matchers Reference](https://docs.mulesoft.com/munit/2.3/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference) --- product: MUnit version: 3.6 --- # Core Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## nullValue() Checks that the expression is null. Example ```xml ``` ## notNullValue() Checks that the expression is not null. Example ```xml ``` ## withMediaType(String) Checks that the expression’s media type is the one specified. Example ```xml ``` ## withEncoding(String) Checks that the expression encoding is the one specified. Example ```xml ``` ## both(Matcher, Matcher) Checks that both provided matchers are successful. Example ```xml ``` ## either(Matcher,Matcher) Checks that at least one of the matchers is successful. Example ```xml ``` ## not(Object) Checks if the provided matcher is not successful. Example ```xml ``` Example ```xml ``` ## anyOf(Array) Checks if any of the matchers are successful. Example ```xml ``` ## allOf(Array) Checks if all of the matchers are successful. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [String Matchers Reference](https://docs.mulesoft.com/munit/3.6/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference) --- product: MUnit version: 2.3 --- # Coverage > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The MUnit Coverage feature provides a measurement of how much of a Mule application has been executed by a set of MUnit tests by counting the amount of event processors executed. This allows you to obtain a quality standard for your application, and provides metrics for: - Application overall coverage: An average of the items below. - Resource coverage: Refers to each Mule configuration file under src/main/mule. - Flow coverage: Refers to any of the following components: Flows, Sub-flows, and Batch jobs. Coverage report runs only for EE edition runtimes. If your application has a `requiredProduct` of a Mule CE runtime you will see the following message: **Coverage is a EE only feature and you’ve selected to run over CE**. To run against an EE runtime see [Specifying the Runtime Product](https://docs.mulesoft.com/munit/2.3/munit-maven-plugin#specify-runtime-product). The following is a coverage report sample in JSON format. Use the code callouts below to understand each field in the report: MUnit Coverage - sample JSON report ```json { "coverage": 75.0, (1) "requiredApplicationCoverage": 40.0, (2) "requiredResourceCoverage": 30.0, (2) "requiredFlowCoverage": 25.0, (2) "flowCount": 3, (3) "processorCount": 4, (4) "coveredProcessorCount": 3, (5) "files": [ { "name": "file1.xml", (6) "flowCount": 1, (7) "coverage": 100.0, (8) "processorCount": 2, (9) "weight": 50.0, (10) "flows": [ { "name": "file1Flow1", (11) "type": "FLOW", (12) "coverage": 100.0, (13) "messageProcessorCount": 2, (14) "coveredProcessorCount": 2, (15) "lines": [ { (16) "lineNumber": 11, "covered": true }, { "lineNumber": 12, "covered": true } ] } ] }, { "name": "file2.xml", "flowCount": 2, "coverage": 50.0, "processorCount": 2, "weight": 50.0, "flows": [ { "name": "file2Flow2", "type": "SCOPE", "coverage": 100.0, "messageProcessorCount": 1, "coveredProcessorCount": 1, "lines": [ { "lineNumber": 10, "covered": true } ] }, { "name": "file2Flow1", "type": "SCOPE", "coverage": 0.0, "messageProcessorCount": 1, "coveredProcessorCount": 0, "lines": [ { "lineNumber": 7, "covered": false } ] } ] } ] } ```
1Coverage percentage of the whole application.
2Required coverages for application, resources, and flows. If not configured, they default to -1.
3Amount of flows in the application.
4Amount of event processors in the application.
5Amount of covered event processors.
6Name of that file.
7Amount of flows in that file.
8Coverage percentage of that file.
9Amount of event processors in that file.
10Contribution of that file to the coverage percentage of the whole application.
11Name of the flow.
12Type of the top level element.
Other type of top level element in coverage is error-handler.
13Coverage percentage of that flow.
14Amount of event processors in that flow.
15Amount of event processors covered in that flow.
16XML line numbers containing event processors in that file, and whether they were covered or not.
## See Also - [Coverage in Maven](https://docs.mulesoft.com/munit/2.3/coverage-maven-concept) --- product: MUnit version: 3.6 --- # Coverage > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Coverage feature provides a measurement of how much of a Mule application has been executed by a set of MUnit tests by counting the amount of event processors executed. This allows you to obtain a quality standard for your application, and provides metrics for: - Application overall coverage: An average of the items below. - Resource coverage: Refers to each Mule configuration file under src/main/mule. - Flow coverage: Refers to any of the following components: Flows, Sub-flows, and Batch jobs. Coverage report runs only for EE edition runtimes. If your application has a `requiredProduct` of a Mule CE runtime you will see the following message: **Coverage is a EE only feature and you’ve selected to run over CE**. To run against an EE runtime see [Specifying the Runtime Product](https://docs.mulesoft.com/munit/3.6/munit-maven-plugin#specify-runtime-product). The following is a coverage report sample in JSON format. Use the code callouts below to understand each field in the report: MUnit Coverage - sample JSON report ```json { "coverage": 75.0, (1) "requiredApplicationCoverage": 40.0, (2) "requiredResourceCoverage": 30.0, (2) "requiredFlowCoverage": 25.0, (2) "flowCount": 3, (3) "processorCount": 4, (4) "coveredProcessorCount": 3, (5) "files": [ { "name": "file1.xml", (6) "flowCount": 1, (7) "coverage": 100.0, (8) "processorCount": 2, (9) "weight": 50.0, (10) "flows": [ { "name": "file1Flow1", (11) "type": "FLOW", (12) "coverage": 100.0, (13) "messageProcessorCount": 2, (14) "coveredProcessorCount": 2, (15) "lines": [ { (16) "lineNumber": 11, "covered": true }, { "lineNumber": 12, "covered": true } ] } ] }, { "name": "file2.xml", "flowCount": 2, "coverage": 50.0, "processorCount": 2, "weight": 50.0, "flows": [ { "name": "file2Flow2", "type": "SCOPE", "coverage": 100.0, "messageProcessorCount": 1, "coveredProcessorCount": 1, "lines": [ { "lineNumber": 10, "covered": true } ] }, { "name": "file2Flow1", "type": "SCOPE", "coverage": 0.0, "messageProcessorCount": 1, "coveredProcessorCount": 0, "lines": [ { "lineNumber": 7, "covered": false } ] } ] } ] } ```
1Coverage percentage of the whole application.
2Required coverages for application, resources, and flows. If not configured, they default to -1.
3Amount of flows in the application.
4Amount of event processors in the application.
5Amount of covered event processors.
6Name of that file.
7Amount of flows in that file.
8Coverage percentage of that file.
9Amount of event processors in that file.
10Contribution of that file to the coverage percentage of the whole application.
11Name of the flow.
12Type of the top level element.
Other type of top level element in coverage is error-handler.
13Coverage percentage of that flow.
14Amount of event processors in that flow.
15Amount of event processors covered in that flow.
16XML line numbers containing event processors in that file, and whether they were covered or not.
## See Also - [Coverage in Maven](https://docs.mulesoft.com/munit/3.6/coverage-maven-concept) --- product: MUnit version: 2.3 --- # Database > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To test a piece of code that connects with a database server, you must install a database server in your local environment to run the tests. You could also have a dedicated external database server for testing, but your Maven project would not be portable — a third party would need to install the testing database server to compile your project. To make it easier for you to test database connections, MUnit allows you to implement a database server in your local environment. ## Install the MUnit DB Server Module 1. From Anypoint Studio, go to the **Mule Palette** and **Search in Exchange…​**. 2. In the search bar look for **MUnit Utils Database Server**, and add the module to your project. ```xml com.mulesoft.munit.utils munit-dbserver-module 2.0.2 mule-plugin test ``` The MUnit DB server artifact in your `pom` file must have the `test` scope. 3. The `h2` dependency used for the database is a shared library. You must add the dependency to your `pom.xml` file and list it as a `sharedLibrary` in the `mule-maven-plugin`. ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` ## Attributes Reference
Attribute NameDescription

name

Defines the configuration name of this DB server. This value must be unique.

database

Defines the name of the in-memory DB.

sqlFile

Specifies the path of the SQL file that defines the DB structure/contents. This parameter is used to create the DB at startup. See the Defining the DB Structure from an SQL File section for more information.

csv

Specifies the path of the-comma separated file used to define the DB structure/contents. This parameter is used to create the DB at startup. See Defining the DB Structure from a CSV File section for more information.

connectionStringParameters

Defines the connection string for your database. You can concatenate the parameters with a semicolon.

## Define the DB Structure There are two different ways to define the structure and content of your database: - SQL - CSV The MUnit DB server is based on H2. Complex structures, index and join commands may not work properly. ### Defining the DB Structure from an SQL File To define the DB structure and content from an SQL file, you must provide a valid set of ANSI SQL DDL (Data Definition Language) instructions. ```xml ``` ### Define the DB Structure From a CSV File To define your DB structure based on a CSV file: - The name of the table is the name of the file (in the example below, `customers`). - The name of the columns are the headers of your CSV file. ```xml ``` You can also split your DB structure among several CSV files. To do this, include the file names in a list, with the names separated by semicolons: ```xml ``` This creates two tables: `FILE_NAME` and `FILE_NAME_1`. ## MUnit DB Server Processors The DB server utility has two processors to interact with your DB server: ### Validate-That The MUnit DB Server allows you to validate that the results of a query are as expected. To do this, you use the `validate-that` operation. Set the `results` property to CSV with rows separated by a newline character (`\n`), as shown below. ```xml ``` ### Execute MUnit DB Server enables you to execute instructions to the in-memory databases so that you can add or remove registries before a test and verify that your data was stored correctly. Use a DB Server connector with the `execute` operation to insert the new values to the table (`Culinary Team Member,10,HIR`), then use another DB Server connector with an `execute query` operation to retrieve all values from the table (including the newly added ones) and check the payload using a logger component to store the payload: ```xml ``` The logger in your console reads: ```text org.mule.runtime.core.internal.processor.LoggerMessageProcessor: [{JOBTITLEID=DEV, EECSALARYORHOURLY=10, JOBTITLE=Developer}, {JOBTITLEID=HIR, EECSALARYORHOURLY=10, JOBTITLE=Culinary Team Member}] ``` ## See Also - [Configuring DB Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/2.3/db-server-cookbook) --- product: MUnit version: 2.3 --- # DataWeave Assertions Library > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## dw::test::Asserts This module contains the set of core Matchers to use in your tests Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must beObject() ``` Validates if a payload is of type Object ## Functions ### anyOf #### anyOf(Array>): Matcher Validates that the value satisfies at least one of the given matchers ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must anyOf([beObject(), beString()]) ``` ### beArray #### beArray(): Matcher Validates that a given value is of type Array ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, 4, 7] must beArray() ``` ### beBlank #### beBlank(): Matcher Validates that the String value is blank ```dataweave %dw 2.0 import dw::tests::Asserts --- " " must beBlank() ``` ### beBoolean #### beBoolean(): Matcher Validates that a given value is of type Boolean ```dataweave %dw 2.0 import dw::tests::Asserts --- true must beBoolean() ``` ### beEmpty #### beEmpty(): Matcher Validates that the value (String, Object or Array) is empty ```dataweave %dw 2.0 import dw::tests::Asserts --- [] must beEmpty() ``` ### beGreaterThan #### beGreaterThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is greater than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::tests::Asserts --- 3 must beGreaterThan(2) ``` ### beLowerThan #### beLowerThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is lower than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must beLowerThan(2) ``` ### beNull #### beNull(): Matcher Validates that a given value is of type Null ```dataweave %dw 2.0 import dw::tests::Asserts --- null must beNull() ``` ### beNumber #### beNumber(): Matcher Validates that a given value is of type Number ```dataweave %dw 2.0 import dw::tests::Asserts --- 123 must beNumber() ``` ### beObject #### beObject(): Matcher Validates that a given value is of type Object ```dataweave %dw 2.0 import dw::tests::Asserts --- { name : "Lionel", lastName: "Messi"} must beObject() ``` ### beOneOf #### beOneOf(Array): Matcher Validates that the value is contained in the given Array ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must beOneOf([1, "A Text", true]) ``` ### beString #### beString(): Matcher Validates that a given value is of type String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must beString() ``` ### contain #### contain(String): Matcher Validates that the asserted String contains the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must contain("ex") ``` #### contain(Any): Matcher> Validates that the asserted Array contains the given value ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, "A Text", true] must contain(1) ``` ### eachItem #### eachItem(Matcher): Matcher> Validates that each item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- [1,2,3] must eachItem(beNumber()) ``` ### endWith #### endWith(String): Matcher Validates that the asserted String ends with the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must endWith("xt") ``` ### equalTo #### equalTo(Any, { unordered?: Boolean }): Matcher Validates that a value is equal to another one ```dataweave %dw 2.0 import dw::tests::Asserts --- (1 + 2) must equalTo(3) ``` ### equalToResource #### equalToResource(String, String, Object): Matcher Validates that the given value is equal to the content of a resource file The resource file must belong to the classpath ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must equalToResource("user.json", "application/json") ``` ### haveItem #### haveItem(Matcher): Matcher> Validates that at least one item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, true, "a text"] must haveItem(beNumber()) ``` ### haveKey #### haveKey(String): Matcher Validates that the Object has the given key ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must haveKey("name") ``` ### haveSize #### haveSize(Number): Matcher Validates that the array has the given size ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, 4, 7] must haveSize(3) ``` ### haveValue #### haveValue(Any): Matcher Validates that the Object has the given value ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must haveValue("Messi") ``` ### must #### must(T, Array<(value: T) → Matcher | MatcherResult | Boolean>): MatcherResult This function allows to assert a value with with a list of Matcher of Expressions Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must [ beObject(), $.foo is Null ] ``` #### must(T, (value: T) → Matcher | Boolean): MatcherResult This function allows to assert a value with a Matcher of Expressions Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must beObject() ``` ### notBe #### notBe(Matcher): Matcher Validates that the value doesn’t satisfy the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must notBe(equalTo(2)) ``` ### notBeNull #### notBeNull(): Matcher Validates that a given value isn’t of type Null ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must notBeNull() ``` ### startWith #### startWith(String): Matcher Validates that the asserted String starts with the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must startWith("A") ``` ## Variables ### MATCHED Constant that represents a successful match ## Types ### Matcher Data Type that represents a Matcher to perform assertions Example ```dataweave %dw 2.0 import dw::tests::Asserts fun beEqualToOne(): Matcher = (actual) -> do { { matches: actual == 1, description: { expected: "To be 1", actual: write(actual) as String } } } ``` Definition ```dataweave (value: T) -> MatcherResult ``` ### MatcherResult Data Type that represents the result of an Assertion Example ```dataweave { "matches": false, description : { expected : "Number type", actual: "A Text" } } ``` Definition ```dataweave { matches: Boolean, description: { expected: String, actual: String }, reasons?: Array } ``` --- product: MUnit version: 3.6 --- # DataWeave Assertions Library > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## dw::test::Asserts This module contains the set of core Matchers to use in your tests Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must beObject() ``` Validates if a payload is of type Object ## Functions ### anyOf #### anyOf(Array>): Matcher Validates that the value satisfies at least one of the given matchers ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must anyOf([beObject(), beString()]) ``` ### beArray #### beArray(): Matcher Validates that a given value is of type Array ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, 4, 7] must beArray() ``` ### beBlank #### beBlank(): Matcher Validates that the String value is blank ```dataweave %dw 2.0 import dw::tests::Asserts --- " " must beBlank() ``` ### beBoolean #### beBoolean(): Matcher Validates that a given value is of type Boolean ```dataweave %dw 2.0 import dw::tests::Asserts --- true must beBoolean() ``` ### beEmpty #### beEmpty(): Matcher Validates that the value (String, Object or Array) is empty ```dataweave %dw 2.0 import dw::tests::Asserts --- [] must beEmpty() ``` ### beGreaterThan #### beGreaterThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is greater than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::tests::Asserts --- 3 must beGreaterThan(2) ``` ### beLowerThan #### beLowerThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is lower than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must beLowerThan(2) ``` ### beNull #### beNull(): Matcher Validates that a given value is of type Null ```dataweave %dw 2.0 import dw::tests::Asserts --- null must beNull() ``` ### beNumber #### beNumber(): Matcher Validates that a given value is of type Number ```dataweave %dw 2.0 import dw::tests::Asserts --- 123 must beNumber() ``` ### beObject #### beObject(): Matcher Validates that a given value is of type Object ```dataweave %dw 2.0 import dw::tests::Asserts --- { name : "Lionel", lastName: "Messi"} must beObject() ``` ### beOneOf #### beOneOf(Array): Matcher Validates that the value is contained in the given Array ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must beOneOf([1, "A Text", true]) ``` ### beString #### beString(): Matcher Validates that a given value is of type String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must beString() ``` ### contain #### contain(String): Matcher Validates that the asserted String contains the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must contain("ex") ``` #### contain(Any): Matcher> Validates that the asserted Array contains the given value ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, "A Text", true] must contain(1) ``` ### eachItem #### eachItem(Matcher): Matcher> Validates that each item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- [1,2,3] must eachItem(beNumber()) ``` ### endWith #### endWith(String): Matcher Validates that the asserted String ends with the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must endWith("xt") ``` ### equalTo #### equalTo(Any, { unordered?: Boolean }): Matcher Validates that a value is equal to another one ```dataweave %dw 2.0 import dw::tests::Asserts --- (1 + 2) must equalTo(3) ``` ### equalToResource #### equalToResource(String, String, Object): Matcher Validates that the given value is equal to the content of a resource file The resource file must belong to the classpath ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must equalToResource("user.json", "application/json") ``` ### haveItem #### haveItem(Matcher): Matcher> Validates that at least one item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, true, "a text"] must haveItem(beNumber()) ``` ### haveKey #### haveKey(String): Matcher Validates that the Object has the given key ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must haveKey("name") ``` ### haveSize #### haveSize(Number): Matcher Validates that the array has the given size ```dataweave %dw 2.0 import dw::tests::Asserts --- [1, 4, 7] must haveSize(3) ``` ### haveValue #### haveValue(Any): Matcher Validates that the Object has the given value ```dataweave %dw 2.0 import dw::tests::Asserts --- { name: "Lionel", lastName: "Messi" } must haveValue("Messi") ``` ### must #### must(T, Array<(value: T) → Matcher | MatcherResult | Boolean>): MatcherResult This function allows to assert a value with a list of Matcher of Expressions Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must [ beObject(), $.foo is Null ] ``` #### must(T, (value: T) → Matcher | Boolean): MatcherResult This function allows to assert a value with a Matcher of Expressions Example ```dataweave %dw 2.0 import dw::tests::Asserts --- payload must beObject() ``` ### notBe #### notBe(Matcher): Matcher Validates that the value doesn’t satisfy the given matcher ```dataweave %dw 2.0 import dw::tests::Asserts --- 1 must notBe(equalTo(2)) ``` ### notBeNull #### notBeNull(): Matcher Validates that a given value isn’t of type Null ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must notBeNull() ``` ### startWith #### startWith(String): Matcher Validates that the asserted String starts with the given String ```dataweave %dw 2.0 import dw::tests::Asserts --- "A Text" must startWith("A") ``` ## Variables ### MATCHED Constant that represents a successful match ## Types ### Matcher Data Type that represents a Matcher to perform assertions Example ```dataweave %dw 2.0 import dw::tests::Asserts fun beEqualToOne(): Matcher = (actual) -> do { { matches: actual == 1, description: { expected: "To be 1", actual: write(actual) as String } } } ``` Definition ```dataweave (value: T) -> MatcherResult ``` ### MatcherResult Data Type that represents the result of an Assertion Example ```dataweave { "matches": false, description : { expected : "Number type", actual: "A Text" } } ``` Definition ```dataweave { matches: Boolean, description: { expected: String, actual: String }, reasons?: Array } ``` --- product: MUnit version: 2.3 --- # Dynamic Directories > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When managing files and folders during a test, MUnit provides the `munit.temporary.directory` property to reference a temporary directory. You can create files and folders inside this directory to use in your tests. The temporary directory is deleted at the end of each test. For example, using the file connector, you could configure the working directory as follows: ```xml ``` And then use it to create files/folders inside it: ```xml ``` ## See Also - [Dynamic Ports](https://docs.mulesoft.com/munit/2.3/dynamic-ports) --- product: MUnit version: 3.6 --- # Dynamic Directories > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio When managing files and folders during a test, MUnit provides the `munit.temporary.directory` property to reference a temporary directory. You can create files and folders inside this directory to use in your tests. The temporary directory is deleted at the end of each test. For example, using the file connector, you could configure the working directory as follows: ```xml ``` And then use it to create files/folders inside it: ```xml ``` ## See Also - [Dynamic Ports](https://docs.mulesoft.com/munit/3.6/dynamic-ports) --- product: MUnit version: 2.3 --- # Dynamic Ports > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Ports global element allows you to bind a free port to a property. It searches for a free port available and can be narrowed to a specific range. For example, a dynamic port would look something like this: ```xml ``` And it can be used in the http configuration: ```xml ``` Additionally you can set min and max values from where to get the port: ```xml ``` ## See Also - [Dynamic Directories](https://docs.mulesoft.com/munit/2.3/dynamic-directories) - [Storage Event Processors](https://docs.mulesoft.com/munit/2.3/storage-event-processors) --- product: MUnit version: 3.6 --- # Dynamic Ports > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Dynamic Ports global element allows you to bind a free port to a property. It searches for a free port available and can be narrowed to a specific range. For example, a dynamic port would look something like this: ```xml ``` And it can be used in the http configuration: ```xml ``` Additionally you can set min and max values from where to get the port: ```xml ``` ## See Also - [Dynamic Directories](https://docs.mulesoft.com/munit/3.6/dynamic-directories) - [Storage Event Processors](https://docs.mulesoft.com/munit/3.6/storage-event-processors) --- product: MUnit version: 2.3 keywords: munit, test, flow sources --- # Enable Flow Sources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Enable Flow Sources element within the MUnit test tells MUnit which flow sources to load and execute for the test. By default, MUnit does not start any of the event sources (flow sources such as triggers, and listeners). You must configure which flow sources must start for your tests. Assume that your application has a flow with an HTTP listener that returns a specific payload: ```xml ``` For MUnit to be able to invoke that listener you must enable the `http-example-flow` in your `enable-flow-source` property within your MUnit test: ```xml ``` If the `http-example-flow` value is not listed as an enabled flow source, your MUnit test fails because it cannot initialize the HTTP listener configuration. MUnit starts flow sources at the beginning of the test, and stops them at the end of the test. Flow sources are not executed during the before-suite/before-test, nor during the after-test/after-suite. See [Before/After scopes](https://docs.mulesoft.com/munit/2.3/before-after-scopes-reference) for more information. ## Enable Flow Sources from Anypoint Studio You can define flow sources using the **Mule Properties** view of your MUnit test in Studio: ![Flow sources defined using the Mule Properties view in Studio.](/mulesoft/current/en-us/munit/2.3/_images/enable-flow-sources-concept.png) 1. Click **Add**. 2. Select the name of the flow you want to enable from the **Name of the flow** drop-down menu. --- product: MUnit version: 3.6 keywords: munit, test, flow sources --- # Enable Flow Sources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The `Enable Flow Sources` element within the MUnit test instructs MUnit which flow sources to load and execute for the test. By default, MUnit doesn’t start any of the event sources (flow sources such as triggers and listeners). You must configure which flow sources must start for your tests. Assume that your application has a flow with an HTTP listener that returns a specific payload: ```xml ``` For MUnit to invoke that listener, enable the `http-example-flow` in your `enable-flow-source` property within your MUnit test: ```xml ``` If the `http-example-flow` value isn’t listed as an enabled flow source, your MUnit test fails because it can’t initialize the HTTP listener configuration. MUnit starts flow sources at the beginning of the test and stops them at the end of the test. Flow sources aren’t executed during the before-suite/before-test, nor during the after-test/after-suite. See [Before/After scopes](https://docs.mulesoft.com/munit/3.6/before-after-scopes-reference) for additional information. --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, test, flow sources --- # Enable Flow Sources in MUnit > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Enable Flow Sources element specifies which flow sources, such as HTTP listeners and triggers, start and run during a MUnit test. By default, MUnit does not start any event sources. You must explicitly configure which ones to enable for each test. Assume that your application has a flow with an HTTP listener that returns a specific payload: ```xml ``` For MUnit to invoke that listener, enable the `http-example-flow` in your `enable-flow-source` property within your MUnit test: ```xml ``` If the `http-example-flow` value isn’t listed as an enabled flow source, your MUnit test fails because it can’t initialize the HTTP listener configuration. MUnit starts flow sources at the beginning of the test and stops them at the end of the test. Flow sources aren’t executed during the before-suite/before-test, nor during the after-test/after-suite. See [Before/After scopes](https://docs.mulesoft.com/munit/latest/before-after-scopes-reference) for additional information. --- product: MUnit version: 2.3 --- # Fail Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Fail Event Processor allows you to fail your test on purpose. This is useful to validate that a test should fail if that point is reached. ```xml ``` The message field is optional and defines the error message to print when the assertion fails. The processor throws a `java.lang.AssertionError`. --- product: MUnit version: 3.6 --- # Fail Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Fail Event Processor allows you to fail your test on purpose. This is useful to validate that a test should fail if that point is reached. ```xml ``` The message field is optional and defines the error message to print when the assertion fails. The processor throws a `java.lang.AssertionError`. --- product: MUnit version: 2.3 --- # FTP Utils > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To test a piece of code that connects with an FTP server, you must install an FTP server in your local environment to run the tests. You could also have a dedicated external FTP server for testing, but your Maven project would not be portable — a third party would need to install the testing FTP server to compile your project. To make it easier for you to test FTP connections, MUnit allows you to implement an FTP server in your local environment. ## Install the MUnit FTP Server Module 1. From Anypoint Studio, go to the **Mule Palette** and **Search in Exchange…​**. 2. In the search bar, look for **MUnit Utils FTP Server** and add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module 2.0.1 mule-plugin test ``` The MUnit FTP server artifact in your POM file must have the `test` scope. ## Attributes Reference The FTP Server takes the following parameters:
Attribute NameDescription

name

Defines the configuration name of the FTP server.

This value must be unique.

port

Defines the port on which the FTP server listens.

anonymous

(Boolean) Sets anonymous access to the FTP server. If anonymous is set to true, you don’t need to set a password to access the FTP server when using the anonymous username.

The default value is true.

secure

(Boolean) Defines the FTP protocol. When the secure parameter is set to true, the server behaves as an SFTP server and connections are allowed only through authentication. If this parameter is set to false, the server behaves as an FTP server and allows either authenticated or anonymous connections.

The default value is false.

homeDir

Defines the user home directory. The default value is the filesystem root.
It is possible to define the FTP user home directory using the ~ character to represent the home directory on the file system.

## MUnit FTP server Processors The FTP Utility has two processors to interact with your FTP server: contains-files The `contains-files` processor attempts to validate the existence of a file in the FTP server. If the file is not present, the processor fails causing the test to fail. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

Defines in which folder to search based on the user home directory defined previously.

file

Defines the name of the file to look for.

remove The `remove` processor provides another operation that may be of use. This operation instructs the FTP server to remove a file from storage. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

The full path of the file to remove.

This feature is useful when creating the same file name several times. You can configure it in `after-test` to ensure that no name collisions cause the test to fail. ## See Also - [Configuring FTP Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/2.3/ftp-server-cookbook) --- product: MUnit version: 3.6 --- # FTP Utils > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio To test a piece of code that connects with an FTP server, install an FTP server in your local environment to run the tests. You can also use a dedicated external FTP server for testing, but your Maven project can’t be portable. A third party must install the testing FTP server to compile your project. To test the FTP connections, you can implement an FTP server in your local environment with MUnit. ## Install the MUnit FTP Server Module To install the MUnit FTP server module: 1. Look for the **MUnit Utils FTP Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module LATEST_VERSION (1) mule-plugin test ```
1Check the MuleSoft Nexus repository to get the LATEST_VERSION.
The MUnit FTP server artifact in your POM file must have the `test` scope. > [!NOTE] The **MUnit FTP Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-ftpserver-module/). > The **MUnit FTP Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Attributes Reference The FTP server module takes the following parameters:
Attribute NameDescription

name

Defines the configuration name of the FTP server.
This value must be unique.

port

Defines the port on which the FTP server listens.

anonymous

(Boolean) Sets anonymous access to the FTP server. If you set anonymous to true, don’t set a password to access the FTP server when using the anonymous username.
The default value is true.

secure

(Boolean) Defines the FTP protocol. If you set the secure parameter to true, the server behaves as an SFTP server and connections must be authenticated. If you set the secure parameter to false, the server behaves as an FTP server and allows either authenticated or anonymous connections.
The default value is false.

homeDir

Defines the user’s home directory. The default value is the filesystem root.
You can define the FTP user home directory by using the ~ character to represent the home directory on the file system.

## MUnit FTP Server Processors The FTP Utility has two processors to interact with your FTP server: contains-files The `contains-files` processor validates the existence of a file in the FTP server. If there is no file present, the processor fails causing the test to fail. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

Defines in which folder to search based on the user home directory defined.

file

Defines the name of the file to look for.

remove The `remove` processor provides an operation that instructs the FTP server to remove a file from storage. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

Defines the full path of the file to remove.

This feature is useful when creating the same file name several times. You can configure it in `after-test` to ensure that no name collisions cause the test to fail. ## See Also - [Configuring FTP Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/3.6/ftp-server-cookbook) --- product: MUnit version: 3.7 is-latest-version: true --- # Install the MUnit Database Server Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Install the MUnit Database Server module to run MUnit tests against an in-memory H2 database without an external database server. This makes your Maven project portable and your database tests isolated and repeatable. ## Install the MUnit DB Server Module To install the MUnit DB Server Module: 1. Look for the **MUnit Utils Database Server** module. 2. Add the module to your project in the `pom.xml` file: ```xml com.mulesoft.munit.utils munit-dbserver-module LATEST_VERSION (1) mule-plugin test ```
1Check the MuleSoft Nexus repository to get the LATEST_VERSION.

The MUnit DB server artifact in your pom.xml file must have the test scope.

3. The `h2` dependency used for the database is a shared library. Add the dependency to your `pom.xml` file and list it as a `sharedLibrary` in `mule-maven-plugin`. ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` > [!NOTE] The **MUnit DB Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-dbserver-module/). > The **MUnit DB Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Attributes Reference
Attribute NameDescription

name

Defines the configuration name of this DB server. This value must be unique.

database

Defines the name of the in-memory DB.

sqlFile

Specifies the path of the SQL file that defines the DB structure/contents. Use this parameter to create the DB at startup. See the Defining the DB Structure from an SQL File section for additional information.

csv

Specifies the path of the comma-separated file used to define the DB structure/contents. Use this parameter to create the DB at startup. See Defining the DB Structure from a CSV File section for additional information.

connectionStringParameters

Defines the connection string for your database. You can concatenate the parameters with a semicolon.

## Define the DB Structure You can define the structure and content of your database in two different ways: - SQL - CSV The MUnit DB server is based on H2. Complex structures, index and join commands can present issues. ### Define the DB Structure from an SQL File To define the DB structure and content from an SQL file, you must provide a valid set of ANSI SQL DDL (Data Definition Language) instructions in your MUnit suite file. For example, `my-munit-suite.xml`. ```xml ``` ### Define the DB Structure from a CSV File To define your DB structure in your MUnit suite file based on a CSV file: - The name of the table is the name of the file (in the following example, `customers`). - The names of the columns are the headers of your CSV file. ```xml ``` You can also split your DB structure among several CSV files. In your MUnit suite file, include the file names in a list, with the names separated by semicolons: ```xml ``` This creates two tables: `FILE_NAME` and `FILE_NAME_1`. ## MUnit DB Server Processors The DB server utility has two processors to interact with your DB server: ### Validate-That To validate that the results of a query are as expected, use the `validate-that` operation in your MUnit suite file. Set the `results` property to CSV with rows separated by a newline character (`\n`), as follows: ```xml ``` ### Execute Execute instructions for the in-memory databases to add or remove registries before a test and verify that your data is correctly stored using MUnit DB Server. In your MUnit suite file, use a DB Server connector with the `execute` operation to insert the new values to the table (`Culinary Team Member,10,HIR`). Then use another DB Server connector with an `execute query` operation to retrieve all values from the table (including the newly added ones). Finally, check the payload using a logger component to store the payload: ```xml ``` The logger in your console reads: ```text org.mule.runtime.core.internal.processor.LoggerMessageProcessor: [{JOBTITLEID=DEV, EECSALARYORHOURLY=10, JOBTITLE=Developer}, {JOBTITLEID=HIR, EECSALARYORHOURLY=10, JOBTITLE=Culinary Team Member}] ``` ## See Also - [Configuring DB Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/latest/db-server-cookbook) --- product: MUnit version: 3.7 is-latest-version: true --- # Install the MUnit FTP Server Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Install the MUnit FTP Server module to run MUnit tests against an in-memory FTP or SFTP server without an external server. This makes your Maven project portable and your FTP-based tests isolated and repeatable. ## Install the MUnit FTP Server Module To install the MUnit FTP server module: 1. Look for the **MUnit Utils FTP Server** module. 2. Add the module to your project: ```xml com.mulesoft.munit.utils munit-ftpserver-module LATEST_VERSION (1) mule-plugin test ```
1Check the MuleSoft Nexus repository to get the LATEST_VERSION.
The MUnit FTP server artifact in your POM file must have the `test` scope. > [!NOTE] The **MUnit FTP Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-ftpserver-module/). > The **MUnit FTP Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Attributes Reference The FTP server module takes the following parameters:
Attribute NameDescription

name

Defines the configuration name of the FTP server.
This value must be unique.

port

Defines the port on which the FTP server listens.

anonymous

(Boolean) Sets anonymous access to the FTP server. If you set anonymous to true, don’t set a password to access the FTP server when using the anonymous username.
The default value is true.

secure

(Boolean) Defines the FTP protocol. If you set the secure parameter to true, the server behaves as an SFTP server and connections must be authenticated. If you set the secure parameter to false, the server behaves as an FTP server and allows either authenticated or anonymous connections.
The default value is false.

homeDir

Defines the user’s home directory. The default value is the filesystem root.
You can define the FTP user home directory by using the ~ character to represent the home directory on the file system.

## MUnit FTP Server Processors The FTP Utility has two processors to interact with your FTP server: contains-files The `contains-files` processor validates the existence of a file in the FTP server. If there is no file present, the processor fails causing the test to fail. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

Defines in which folder to search based on the user home directory defined.

file

Defines the name of the file to look for.

remove The `remove` processor provides an operation that instructs the FTP server to remove a file from storage. ```xml ```
Attribute NameDescription

config-ref

Defines the FTP server configuration.

path

Defines the full path of the file to remove.

This feature is useful when creating the same file name several times. You can configure it in `after-test` to ensure that no name collisions cause the test to fail. ## See Also - [Configuring FTP Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/latest/ftp-server-cookbook) --- product: MUnit version: 3.6 --- # Installing a Database Server > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio To test a piece of code that connects with a database server, install a database server in your local environment to run the tests. You can also use a dedicated external database server for testing, but your Maven project can’t be portable. If so, a third party must install the testing database server to compile your project. To make it easier for you to test database connections, MUnit allows you to implement a database server in your local environment. ## Install the MUnit DB Server Module To install the MUnit DB Server Module: 1. Look for the **MUnit Utils Database Server** module. 2. Add the module to your project in the `pom.xml` file: ```xml com.mulesoft.munit.utils munit-dbserver-module LATEST_VERSION (1) mule-plugin test ```
1Check the MuleSoft Nexus repository to get the LATEST_VERSION.

The MUnit DB server artifact in your pom.xml file must have the test scope.

3. The `h2` dependency used for the database is a shared library. Add the dependency to your `pom.xml` file and list it as a `sharedLibrary` in `mule-maven-plugin`. ```xml com.h2database h2 1.3.166 ``` ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true ... com.h2database h2 ``` > [!NOTE] The **MUnit DB Server** module is located at > [MuleSoft Nexus repository](https://repository.mulesoft.org/nexus/content/repositories/releases/com/mulesoft/munit/utils/munit-dbserver-module/). > The **MUnit DB Server** module version 3 and later is compatible with Java 17. Previous versions > of this module available at Anypoint Exchange are deprecated. ## Attributes Reference
Attribute NameDescription

name

Defines the configuration name of this DB server. This value must be unique.

database

Defines the name of the in-memory DB.

sqlFile

Specifies the path of the SQL file that defines the DB structure/contents. Use this parameter to create the DB at startup. See the Defining the DB Structure from an SQL File section for additional information.

csv

Specifies the path of the comma-separated file used to define the DB structure/contents. Use this parameter to create the DB at startup. See Defining the DB Structure from a CSV File section for additional information.

connectionStringParameters

Defines the connection string for your database. You can concatenate the parameters with a semicolon.

## Define the DB Structure You can define the structure and content of your database in two different ways: - SQL - CSV The MUnit DB server is based on H2. Complex structures, index and join commands can present issues. ### Defining the DB Structure from an SQL File To define the DB structure and content from an SQL file, you must provide a valid set of ANSI SQL DDL (Data Definition Language) instructions in your MUnit suite file. For example, `my-munit-suite.xml`. ```xml ``` ### Define the DB Structure From a CSV File To define your DB structure in your MUnit suite file based on a CSV file: - The name of the table is the name of the file (in the following example, `customers`). - The names of the columns are the headers of your CSV file. ```xml ``` You can also split your DB structure among several CSV files. In your MUnit suite file, include the file names in a list, with the names separated by semicolons: ```xml ``` This creates two tables: `FILE_NAME` and `FILE_NAME_1`. ## MUnit DB Server Processors The DB server utility has two processors to interact with your DB server: ### Validate-That To validate that the results of a query are as expected, use the `validate-that` operation in your MUnit suite file. Set the `results` property to CSV with rows separated by a newline character (`\n`), as follows: ```xml ``` ### Execute Execute instructions for the in-memory databases to add or remove registries before a test and verify that your data is correctly stored using MUnit DB Server. In your MUnit suite file, use a DB Server connector with the `execute` operation to insert the new values to the table (`Culinary Team Member,10,HIR`). Then use another DB Server connector with an `execute query` operation to retrieve all values from the table (including the newly added ones). Finally, check the payload using a logger component to store the payload: ```xml ``` The logger in your console reads: ```text org.mule.runtime.core.internal.processor.LoggerMessageProcessor: [{JOBTITLEID=DEV, EECSALARYORHOURLY=10, JOBTITLE=Developer}, {JOBTITLEID=HIR, EECSALARYORHOURLY=10, JOBTITLE=Culinary Team Member}] ``` ## See Also - [Configuring DB Server Utility in an MUnit Test](https://docs.mulesoft.com/munit/3.6/db-server-cookbook) --- product: MUnit version: 2.3 --- # Iterable and Map Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## everyItem(Matcher) Checks that every element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasItem(Object) Checks that any element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasSize(Matcher|Integer) Checks that the size of the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## isEmpty() Checks that the expression is an empty collection. Example ```xml ``` ## hasKey(Matcher|String) Checks that the expression has a key that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasValue(Object) Checks that the expression has a value that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/2.3/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/2.3/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference) --- product: MUnit version: 3.6 --- # Iterable and Map Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## everyItem(Matcher) Checks that every element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasItem(Object) Checks that any element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasSize(Matcher|Integer) Checks that the size of the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## isEmpty() Checks that the expression is an empty collection. Example ```xml ``` ## hasKey(Matcher|String) Checks that the expression has a key that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasValue(Object) Checks that the expression has a value that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/3.6/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/3.6/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference) --- product: MUnit version: 2.3 --- # Maven Configuration for Coverage > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Since MUnit 2.x, the coverage report goal is integrated with the maven reporting section. Coverage Reports are generated during Maven’s `site` lifecycle, during the `coverage-report` goal. The following configurations apply only when you execute your MUnit tests using the Maven plugin. They do not apply when running tests from Studio. To run coverage reports in Studio see [Using Coverage in Studio](https://docs.mulesoft.com/munit/2.3/coverage-studio-concept). MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ## Coverage Report Types When enabling MUnit Coverage, you see a summary report in the console. By default, no other action is taken: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ==================================================================================== ``` MUnit Coverage offers four types of reports: - Console report The console report is printed to the console. It works with the summary report and shows an overview of the MUnit run, with a count of all resources, flows, and processors, as well as the overall application coverage level, and warnings and errors if any. - HTML report The HTML report shows the same information as the console report, but formatted to fit any web browser. It is available in the `${application.path}/target/site/munit/coverage/` path.+ - JSON report The JSON report shows the same information as the HTML report, but in a JSON format. It is available in the `${application.path}/target/site/munit/coverage/munit-coverage.json` path.+ - The SONAR report shows the same information as the HTML report, in a SonarQube format. To enable the report generation, add the following configuration: MUnit Coverage - Report Configuration ```xml true console (1) html (2) json (3) sonar (4) ```
1Console report
2HTML report
3JSON report
4SONAR report
You can choose to have either none, one, or all the report types added to your configuration. To configure, for example, the JSON report generation, you must to add the following configuration to your `pom.xml` file: ```xml true json ``` ## Set up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level is not reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each individual Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage is not defined, it defaults to -1, which indicates that no requirements are defined for said level so the build will not fail due to low coverage.
If you define coverage levels but set the property `failBuild` to **false**, and then the levels are not reached, a warning shows up in the MUnit coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level was not met, and where it happened.
## Ignore a flow or a file Another feature is the ability to ignore either a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow is not tested or if the flow does not reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore both flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## See Also - [Coverage Report](https://docs.mulesoft.com/munit/2.3/munit-coverage-report) --- product: MUnit version: 3.6 --- # Maven Configuration for Coverage > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio From MUnit 2.x and later, the coverage report goal is integrated with the Maven reporting section. MUnit generates coverage reports during the Maven `site` lifecycle, during the `coverage-report` goal. The following configurations apply if you execute your MUnit tests using the Maven plugin. They don’t apply when running tests from Anypoint Code Builder or Anypoint Studio. MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ## Coverage Report Types When you enable MUnit Coverage, the console displays a summary report. ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ==================================================================================== ``` MUnit Coverage offers four types of reports: - Console report The console report prints in the console. It works with the summary report and shows an overview of the MUnit run, with a count of all resources, flows, and processors, as well as the overall application coverage level, and warnings and errors if any. - HTML report The HTML report shows the same information as the console report but is formatted to fit any web browser. It’s available in the `${application.path}/target/site/munit/coverage/` path. - JSON report The JSON report provides the same information as the HTML report but in a JSON format. It’s available at `${application.path}/target/site/munit/coverage/munit-coverage.json`. - SONAR report The SONAR report shows the same information as the HTML report, in a SonarQube format. To enable the report generation, add the following configuration: MUnit Coverage - Report Configuration ```xml true console (1) html (2) json (3) sonar (4) ```
1Console report
2HTML report
3JSON report
4SONAR report
You can choose to have either none, one, or all the report types added to your configuration. To configure, for example, the JSON report generation, add the following configuration to your `pom.xml` file: ```xml true json ``` ## Set up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level isn’t reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage isn’t defined, it defaults to -1, which sets no requirements for said level so the build doesn’t fail due to low coverage.
If you define coverage levels but set the property `failBuild` to `false`, and then the levels aren’t reached, a warning shows up in the MUnit Coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level isn’t met, and where it happens.
## Ignore a Flow or a File You can also ignore a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow isn’t tested or if the flow doesn’t reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## See Also - [Coverage Report](https://docs.mulesoft.com/munit/3.6/munit-coverage-report) - [Using Coverage in Studio](https://docs.mulesoft.com/munit/3.6/coverage-studio-concept). --- product: MUnit version: 3.7 is-latest-version: true --- # Mock Messages Before and Inside a Foreach Processor in MUnit > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Mock processors inside a foreach scope in MUnit to return different payloads on each iteration. Use the mock-when processor with a then-call operation to delegate mock responses to a separate flow that evaluates the foreach counter. Suppose you have a processor inside a `foreach` scope and you want to provide different values on each iteration: ```xml ``` Use an `munit-tools:mock-when` processor to mock the processor in your flow and use the `then-call` operation to call a new flow that set payloads depending on the `foreach` status: ```xml ``` Inside the flow that is called by the `then-call` you can use a `Choice` processor to evaluate a value and set a mocked payload. In this case, the `foreach` counter is evaluated to decide which payload to set: ```xml ``` ## Mock a Mule Message To mock processors like `file:list` or `ftp:list`, you must return a Mule message collection as payload. `MunitTools` provides a function to mock these payloads: ```none fun createMessage(payload: Any, attributes: Any = null) fun createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) ``` ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) --- product: MUnit version: 3.7 is-latest-version: true --- # Mock Resources for MUnit Tests with DataWeave > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio 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. ## Mock 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: ```none %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: ```xml ``` The `classpath-based` URL uses the `classpath:` protocol prefix to find the file defined in `src/test/resources`. ## Mock 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 variables with references to different mocked data, either from files or inline: ```none 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: ```xml ``` ## See Also - [Create Custom Modules and Mappings](https://docs.mulesoft.com/dataweave/latest/dataweave-create-module) --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # Mock When Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The **Mock When** processor enables you to mock an event processor when it matches the defined name and attributes. For example, you can use the **Mock Event** processor to mock a POST request with a mocked payload: ```xml ``` You can set the **processor** attribute to define the processor to mock and set the **with-attribute** element to define the attribute name and value. In the previous example, you define a POST method. You can also use DataWeave functions and mappings to set the `value` attribute in the **then-return** element. For example, create a **mockPost.dwl** in the **src/test/resources/sample\_data** file: ```none %dw 2.0 output application/json --- { "foo" : "var" } ``` This DataWeave file creates the payload to send in a POST request. You can then use the **readUrl** DataWeave function to read the mapping file: ```xml ``` Finally, you can configure a **then-return** element to define the type of response the mocked processor returns. It can be a payload, a variable, a list of attributes, or an error. You can use either a **then-return** to return a static, constant value, or you can use a **then-call** to invoke a flow for cases where the returned value can change over time, or to have different responses according to certain inputs. > [!NOTE] The mocking of the processors is executed after the initialization of the Mule app, and > some connectors can require credentials or configurations to start the app, even when its > processors are mocked. > [!NOTE] Logger processor and Transform Message processor (DataWeave) cannot be mocked. ## Mock Using Then-Return For example, you can mock a web service consumer such as this one: ```xml ``` By configuring the **mock-when** processor as shown in the following example: ```xml ``` This **mock-when** processor mocks a call to the **OrderTshirt** operation in the WSDL definition. You can also mock specific variables: ```xml ``` ### Mock Errors The **Mock When** processor also enables you to mock errors in your operations. Assume that you have an HTTP requester in your flow with an On-Error scope that catches any connectivity errors and returns a custom payload if the connection fails: ```xml ``` You can assert that every time the HTTP request fails, your application returns your custom payload: ```xml (1) (2) (3) (4) ```
1Mock an HTTP Requester with the configuration of the requester in your flow.
2Configure a then-return element to throw an HTTP:CONNECTIVITY error.
This triggers the On-error scope in your application.
3Execute the flow containing the requester.
4Assert that the returned payload is the one you set in the On-error scope.
You cannot return all known error types of a Mule application. You can return the type of errors defined in the modules the current flow uses. If you try to return an error type that is out of the scope of the flow you’re testing, you get a **MULE:UNKNOWN** error instead of the configured one. ### Parameters If you create a mock error, choose one of the following parameters to provide the trigger for the error in the **Then-return** tab: - **TypeId**: Follows a Mule Error type definition. For example, the HTTP:CONNECTIVITY error explained before. - **Cause**: Expects the instance of the exception with a message for the error. For example, using Java, write the expression: ```java #[java!java::lang::Exception::new("Exception Message")] ``` ## Mock Using Then-Call To dynamically mock a variable, use **then-call** as follows: ```xml (1) (2) (3) ```
1This is the processor you mock.
2The mock calls this flow. The mock sets a variable that changes depending on the incoming event.
3Configure the mock to call the desired flow.
## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/2.3/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/2.3/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/2.3/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/2.3/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/2.3/verify-event-processor) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # Mock When Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The **Mock When** processor enables you to mock an event processor when it matches the defined name and attributes. For example, you can use the **Mock Event** processor to mock a POST request with a mocked payload: ```xml ``` You can set the **processor** attribute to define the processor to mock and set the **with-attribute** element to define the attribute name and value. In the previous example, you define a POST method. You can also use DataWeave functions and mappings to set the `value` attribute in the **then-return** element. For example, create a **mockPost.dwl** in the **src/test/resources/sample\_data** file: ```none %dw 2.0 output application/json --- { "foo" : "var" } ``` This DataWeave file creates the payload to send in a POST request. You can then use the **readUrl** DataWeave function to read the mapping file: ```xml ``` Finally, you can configure a **then-return** element to define the type of response the mocked processor returns. It can be a payload, a variable, a list of attributes, or an error. You can use either a **then-return** to return a static, constant value, or you can use a **then-call** to invoke a flow for cases where the returned value can change over time, or to have different responses according to certain inputs. > [!NOTE] The mocking of the processors is executed after the initialization of the Mule app, and > some connectors can require credentials or configurations to start the app, even when its > processors are mocked. > [!NOTE] Logger processor and Transform Message processor (DataWeave) cannot be mocked. ## Mock Using Then-Return For example, you can mock a web service consumer such as this one: ```xml ``` By configuring the **mock-when** processor as shown in the following example: ```xml ``` This **mock-when** processor mocks a call to the **OrderTshirt** operation in the WSDL definition. You can also mock specific variables: ```xml ``` ### Mock Errors The **Mock When** processor also enables you to mock errors in your operations. Assume that you have an HTTP requester in your flow with an On-Error scope that catches any connectivity errors and returns a custom payload if the connection fails: ```xml ``` You can assert that every time the HTTP request fails, your application returns your custom payload: ```xml (1) (2) (3) (4) ```
1Mock an HTTP Requester with the configuration of the requester in your flow.
2Configure a then-return element to throw an HTTP:CONNECTIVITY error.
This triggers the On-error scope in your application.
3Execute the flow containing the requester.
4Assert that the returned payload is the one you set in the On-error scope.
You cannot return all known error types of a Mule application. You can return the type of errors defined in the modules the current flow uses. If you try to return an error type that is out of the scope of the flow you’re testing, you get a **MULE:UNKNOWN** error instead of the configured one. ### Parameters If you create a mock error, choose one of the following parameters to provide the trigger for the error in the **Then-return** tab: - **TypeId**: Follows a Mule Error type definition. For example, the HTTP:CONNECTIVITY error explained before. - **Cause**: Expects the instance of the exception with a message for the error. For example, using Java, write the expression: ```java #[java!java::lang::Exception::new("Exception Message")] ``` ## Mock Using Then-Call To dynamically mock a variable, use **then-call** as follows: ```xml (1) (2) (3) ```
1This is the processor you mock.
2The mock calls this flow. The mock sets a variable that changes depending on the incoming event.
3Configure the mock to call the desired flow.
## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/3.6/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/3.6/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/3.6/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/3.6/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/3.6/verify-event-processor) --- product: MUnit version: 2.3 --- # Mocking a Message Before and Inside a Foreach Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Suppose you have a processor inside a `foreach` scope and you want to provide different values on each iteration: ```xml ``` Use an `munit-tools:mock-when` processor to mock the processor in your flow and use the `then-call` operation to call a new flow that set payloads depending on the `foreach` status: ```xml ``` Inside the flow that is called by the `then-call` you can use a `Choice` processor to evaluate a value and set a mocked payload. In this case, the `foreach` counter is evaluated to decide which payload to set: ```xml ``` ## Mock a Mule Message To mock processors like `file:list` or `ftp:list`, you must return a Mule message collection as payload. `MunitTools` provides a function to mock these payloads: ```none fun createMessage(payload: Any, attributes: Any = null) fun createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) ``` ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) --- product: MUnit version: 3.6 --- # Mocking a Message Before and Inside a Foreach Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Suppose you have a processor inside a `foreach` scope and you want to provide different values on each iteration: ```xml ``` Use an `munit-tools:mock-when` processor to mock the processor in your flow and use the `then-call` operation to call a new flow that set payloads depending on the `foreach` status: ```xml ``` Inside the flow that is called by the `then-call` you can use a `Choice` processor to evaluate a value and set a mocked payload. In this case, the `foreach` counter is evaluated to decide which payload to set: ```xml ``` ## Mock a Mule Message To mock processors like `file:list` or `ftp:list`, you must return a Mule message collection as payload. `MunitTools` provides a function to mock these payloads: ```none fun createMessage(payload: Any, attributes: Any = null) fun createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) ``` ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor) --- product: MUnit version: 2.3 --- # Mocking Resources for Your Tests > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 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 to reuse the files that you need to mock for your tests. You can leverage DataWeave to mock your test code, either by creating DataWeave scripts or by using variables in a DataWeave module. ## Mock 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: ```none %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: ```xml ``` The `classpath-based` URL uses the `classpath:` protocol prefix to find the file defined in `src/test/resources`. ## Mock 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 variables with references to different mocked data, either from files or inline: ```none 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: ```xml ``` ## See Also - [Create Custom Modules and Mappings](https://docs.mulesoft.com/dataweave/latest/dataweave-create-module) --- product: MUnit version: 3.6 --- # Mocking Resources for Your Tests > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio 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 to reuse the files that you need to mock for your tests. You can leverage DataWeave to mock your test code, either by creating DataWeave scripts or by using variables in a DataWeave module. ## Mock 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: ```none %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: ```xml ``` The `classpath-based` URL uses the `classpath:` protocol prefix to find the file defined in `src/test/resources`. ## Mock 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 variables with references to different mocked data, either from files or inline: ```none 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: ```xml ``` ## See Also - [Create Custom Modules and Mappings](https://docs.mulesoft.com/dataweave/latest/dataweave-create-module) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Assert Equals Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Assert Equals processor validates that two values are equal during a MUnit test. Use it to check the state of a Mule Event’s payload or variables after production code runs. For example, to assert that a payload is equal to a certain value, you can configure the Assert-Equals processor the following way: ```xml ``` If the `expected` attribute is a String, you can specify the literal value without requiring an expression. ```xml ``` If this assertion fails, the processor throws a `MUNIT-TOOLS:ASSERTION_ERROR`. --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Assert Expression Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Assert Expression processor evaluates DataWeave expressions to validate a Mule event’s content during a MUnit test, using the DataWeave Assertions Library. Use it when you need DataWeave-native assertions or want to create custom matchers with the DataWeave Assertions Library. For example, to assert that a payload is equal to a certain value, you can configure the Assert-Expression processor using the equalTo() matcher. ```xml #[ import * from dw::test::Asserts --- payload must equalTo('example') ] ``` ## Perform Complex Assertions The DW assertions library allows you to assert the state of the Mule Event’s content in a deeper way. ```xml #[ import * from dw::test::Asserts --- vars.attributes must [beObject(), $.statusCode must equalTo(200), $.method must equalTo('GET')] ] ``` ## Create Your Own Matcher To create your own matcher, you can add DW files to your `src/test/resources` folder. For example, a file called `MyMatcher.dwl` with the following content: ```dataweave import * from dw::test::Asserts fun beEven(): Matcher = (actual:Number) -> do { var matchesEven = (actual mod 2) == 0 --- { matches: matchesEven, description: {expected: " to be an even number.", actual: write(actual) as String} } } ``` And then use it in your Assert-Expression processor: ```xml #[ import * from dw::test::Asserts --- payload must MyMatcher::beEven() ] ``` If this assertion fails, the processor throws a `MUNIT-TOOLS:ASSERTION_ERROR`. > [!WARNING] Matchers from the `dw::test::Asserts` library are not compatible with the `MunitTools` > matchers. You can’t use `dw::test::Asserts` with the Assert-That processor, and you can’t use > `MunitTools` matchers with the Assert-Expression processor. --- product: MUnit version: 3.7 is-latest-version: true keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # MUnit Assert That Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Assert That event processor validates the state of a Mule event’s content during a MUnit test using DataWeave MUnit matchers. Use it to assert conditions on any value in an expression after production code runs. The Assert That processor uses a set of DataWeave functions called `MUnit matchers` to define the assertion conditions for any value in an expression. For example, to assert that a payload is equal to a certain value, configure the Assert That processor using the `equalTo()` matcher. ```xml ``` Or you can also check if the payload is null using the `nullValue()` matcher. ```xml ``` See [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) for more information. If these assertion fails, the processor throws a `MUNIT-TOOLS:ASSERTION_ERROR`. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Before and After Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Before and After scopes let you run setup and teardown code at the suite or test level in a MUnit test suite. Use Before scopes to prepare shared state and After scopes to clean it up, so each test starts and ends in a controlled state. ## Before Suite Scope The MUnit Before Suite scope runs once before all tests in the suite. For example, suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before Suite runs just once, before your four tests. > [!NOTE] You can only use one Before Suite scope per MUnit test suite. Use a Before Suite scope to set up state that every test in the suite shares, such as seeding an in-memory database, starting a server utility, or storing values that the tests read. In the example, the `jobtitlelookup.csv` file creates the table and its initial contents when the database server starts, and the Before Suite adds one shared row that all tests in the suite query: Before Suite example ```xml ``` > [!NOTE] The `before-suite` scope is located outside the MUnit test, so the insert runs once before > the first test instead of once per test. When you place a before-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Suite Scope The MUnit After Suite scope runs once after all tests in the suite complete. For instance, let’s suppose you have an MUnit Test Suite File with four tests. The code inside an MUnit After Suite, runs just once, after all your tests. > [!NOTE] You can only use one After Suite scope per MUnit test suite. Use an After Suite scope to tear down whatever the Before Suite created, so the next suite run starts from a clean state. The example removes only the row that the Before Suite added, leaving the contents loaded from the CSV file untouched: After Suite example ```xml ``` > [!NOTE] The `after-suite` scope is located outside the MUnit test, so the cleanup runs once after > the last test completes. When you place an after-suite in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Test Scope The MUnit Before Test scope runs before each individual test in the suite. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit Before test runs before each of your four tests; it runs four times. > [!NOTE] You can only use one Before Test scope per MUnit test suite. Use a Before Test scope to set up state that each test needs individually, such as inserting a record, creating a file, or setting a variable that the test consumes. The following example inserts a record and sets the variable that the flow under test reads: Before Test example ```xml ``` > [!NOTE] The `before.test` scope is located outside the MUnit test, so each test starts from the > same record and variable value without repeating the setup in every test. When you place a before-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## After Test Scope The MUnit After Test scope runs after each individual test in the suite completes. For instance, let’s suppose you have an MUnit Test Suite file with four tests. The code inside an MUnit After Test runs after each of your four tests; it runs four times. > [!NOTE] You can only use one After Test scope per MUnit test suite. Use an After Test scope to undo what the Before Test created, so one test doesn’t leave data behind that affects the next one. The following example deletes the record that the Before Test inserted: After Test example ```xml ``` > [!NOTE] The `after.test` scope is located outside the MUnit test, so the cleanup runs after each > test rather than once after the suite. When you place an after-test in the Anypoint Studio canvas, the scope locates outside the MUnit test. ## Before Suite Reference
Attribute NameDescription

name

Defines the name of the Before suite. The name must be unique inside the suite.

description

Describes the actions performed.

## After Suite Reference
Attribute NameDescription

name

Defines the name of the After suite. The name must be unique inside the suite.

description

Describes the actions performed.

## Before Test Reference
Attribute NameDescription

name

Defines the name of the Before test. The name must be unique inside the suite.

description

Describes the actions performed.

## After Test Reference
Attribute NameDescription

name

Defines the name of the After test. The name must be unique inside the suite.

description

Describes the actions performed.

## See Also - [MUnit Test Structure Fundamentals](https://docs.mulesoft.com/munit/latest/munit-test-concept) - [Install the MUnit Database Server Module](https://docs.mulesoft.com/munit/latest/db-util) - [Configure the MUnit Database Server Utility](https://docs.mulesoft.com/munit/latest/db-server-cookbook) - [Install the MUnit FTP Server Module](https://docs.mulesoft.com/munit/latest/ftp-util) - [Enable Flow Sources in MUnit](https://docs.mulesoft.com/munit/latest/enable-flow-sources-concept) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Comparable Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Comparable matchers are matcher functions that assert comparison conditions on values during a MUnit test. Use them with the Assert That processor to check if a value is greater than, less than, equal to, or close to an expected value. > [!NOTE] `Comparable` is a DataWeave type that represents all the types that can be compared to > each other. > Allowed primitives are String, Number, Boolean, DateTime, LocalDateTime, LocalTime, Time, and > TimeZone that you can pass any primitive value such as an integer or a date. ## greaterThan(Comparable) Checks that the expression is greater than the specified value. Example ```xml ``` Example ```xml ``` ## greaterThanOrEqualTo(Comparable) Checks that the expression is greater than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## lessThan(Comparable) Checks that the expression is less than the specified value. Example ```xml ``` Example ```xml ``` ## lessThanOrEqualTo(Comparable) Checks that the expression is less than or equal to the specified value. Example ```xml ``` Example ```xml ``` ## closeTo(Number, Number) Checks that the expression is close to the first number, using the second number as a delta value. In other words, checks that the expression belongs to the range defined by the first number +/- the second number. Example ```xml ``` ## equalTo(Object) Checks that the expression is equal to a specific value. Example ```xml ``` Example ```xml ``` This matcher also accepts Dataweave objects. Example ```xml ``` The matcher validates that the keys and their respective values are the same. The order in the matcher must be the same as the one in the expression or the assertion fails. Example ```xml ``` Example ```xml ``` ## See Also - [DataWeave Comparable Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_comparable) - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/latest/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/latest/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference) --- product: MUnit version: 2.3 --- # MUnit Cookbook > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section links to examples that demonstrate common MUnit usages.
ExampleDescription

Mocking test code for your MUnit tests.

Mocking a processor that can return different payloads.

Mocking expected errors in your code.

Loading different environment values to your MUnit tests.

Using custom Java classes in your MUnit tests.

Configuring an FTP utility to test your FTP server connections.

Configuring a database utility to test your database connections.

Configuring MUnit to run against a patched Mule runtime engine version.

Testing Mule applications that inherit a Mule domain.

Testing a flow that is triggered by a scheduler.

Using the MUnit test recorder.

Ensuring that the assertions check the content of the stored variable.

--- product: MUnit version: 3.6 --- # MUnit Cookbook > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio This section links to examples that demonstrate common MUnit usages.
ExampleDescription

Mocking test code for your MUnit tests.

Mocking a processor that can return different payloads.

Mocking expected errors in your code.

Loading different environment values to your MUnit tests.

Using custom Java classes in your MUnit tests.

Configuring an FTP utility to test your FTP server connections.

Configuring a database utility to test your database connections.

Configuring MUnit to run against a patched Mule runtime engine version.

Testing Mule applications that inherit a Mule domain.

Testing a flow that is triggered by a scheduler.

Using the MUnit test recorder.

Ensuring that the assertions check the content of the stored variable.

--- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Cookbook > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit cookbooks are step-by-step examples that demonstrate common MUnit testing patterns, including mocking, error handling, environment properties, and utility classes.
ExampleDescription

Mocking test code for your MUnit tests.

Mocking a processor that can return different payloads.

Mocking expected errors in your code.

Loading different environment values to your MUnit tests.

Using custom Java classes in your MUnit tests.

Configuring an FTP utility to test your FTP server connections.

Configuring a database utility to test your database connections.

Configuring MUnit to run against a patched Mule runtime engine version.

Testing Mule applications that inherit a Mule domain.

Testing a flow that is triggered by a scheduler.

Using the MUnit test recorder.

Ensuring that the assertions check the content of the stored variable.

--- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Core Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit core matchers are general-purpose matcher functions for use with the Assert That processor in a MUnit test. Use them to check for null values, media types, encodings, and logical combinations of other matchers. ## nullValue() Checks that the expression is null. Example ```xml ``` ## notNullValue() Checks that the expression is not null. Example ```xml ``` ## withMediaType(String) Checks that the expression’s media type is the one specified. Example ```xml ``` ## withEncoding(String) Checks that the expression encoding is the one specified. Example ```xml ``` ## both(Matcher, Matcher) Checks that both provided matchers are successful. Example ```xml ``` ## either(Matcher,Matcher) Checks that at least one of the matchers is successful. Example ```xml ``` ## not(Object) Checks if the provided matcher is not successful. Example ```xml ``` Example ```xml ``` ## anyOf(Array) Checks if any of the matchers are successful. Example ```xml ``` ## allOf(Array) Checks if all of the matchers are successful. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [String Matchers Reference](https://docs.mulesoft.com/munit/latest/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Coverage Report > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Coverage feature measures how much of a Mule application is executed by a set of MUnit tests by counting event processors. Use it to track application, resource, and flow coverage metrics and enforce quality standards. - Application overall coverage: An average of the items below. - Resource coverage: Refers to each Mule configuration file under src/main/mule. - Flow coverage: Refers to any of the following components: Flows, Sub-flows, and Batch jobs. Coverage report runs only for EE edition runtimes. If your application has a `requiredProduct` of a Mule CE runtime you will see the following message: **Coverage is a EE only feature and you’ve selected to run over CE**. To run against an EE runtime see [Specifying the Runtime Product](https://docs.mulesoft.com/munit/latest/munit-maven-plugin#specify-runtime-product). The following is a coverage report sample in JSON format. Use the code callouts below to understand each field in the report: MUnit Coverage - sample JSON report ```json { "coverage": 75.0, (1) "requiredApplicationCoverage": 40.0, (2) "requiredResourceCoverage": 30.0, (2) "requiredFlowCoverage": 25.0, (2) "flowCount": 3, (3) "processorCount": 4, (4) "coveredProcessorCount": 3, (5) "files": [ { "name": "file1.xml", (6) "flowCount": 1, (7) "coverage": 100.0, (8) "processorCount": 2, (9) "weight": 50.0, (10) "flows": [ { "name": "file1Flow1", (11) "type": "FLOW", (12) "coverage": 100.0, (13) "messageProcessorCount": 2, (14) "coveredProcessorCount": 2, (15) "lines": [ { (16) "lineNumber": 11, "covered": true }, { "lineNumber": 12, "covered": true } ] } ] }, { "name": "file2.xml", "flowCount": 2, "coverage": 50.0, "processorCount": 2, "weight": 50.0, "flows": [ { "name": "file2Flow2", "type": "SCOPE", "coverage": 100.0, "messageProcessorCount": 1, "coveredProcessorCount": 1, "lines": [ { "lineNumber": 10, "covered": true } ] }, { "name": "file2Flow1", "type": "SCOPE", "coverage": 0.0, "messageProcessorCount": 1, "coveredProcessorCount": 0, "lines": [ { "lineNumber": 7, "covered": false } ] } ] } ] } ```
1Coverage percentage of the whole application.
2Required coverages for application, resources, and flows. If not configured, they default to -1.
3Amount of flows in the application.
4Amount of event processors in the application.
5Amount of covered event processors.
6Name of that file.
7Amount of flows in that file.
8Coverage percentage of that file.
9Amount of event processors in that file.
10Contribution of that file to the coverage percentage of the whole application.
11Name of the flow.
12Type of the top level element.
Other type of top level element in coverage is error-handler.
13Coverage percentage of that flow.
14Amount of event processors in that flow.
15Amount of event processors covered in that flow.
16XML line numbers containing event processors in that file, and whether they were covered or not.
## See Also - [Coverage in Maven](https://docs.mulesoft.com/munit/latest/coverage-maven-concept) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit DataWeave Assertions Library > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit DataWeave Assertions Library is a set of DataWeave matcher functions for writing assertions in MUnit tests. Use it with the Assert Expression processor to validate values such as strings, numbers, arrays, and objects using DataWeave syntax. ## dw::test::Asserts This module contains the set of core Matchers to use in your tests Example ```dataweave %dw 2.0 import dw::test::Asserts --- payload must beObject() ``` Validates if a payload is of type Object ## Functions ### anyOf #### anyOf(Array>): Matcher Validates that the value satisfies at least one of the given matchers ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must anyOf([beObject(), beString()]) ``` ### beArray #### beArray(): Matcher Validates that a given value is of type Array ```dataweave %dw 2.0 import dw::test::Asserts --- [1, 4, 7] must beArray() ``` ### beBlank #### beBlank(): Matcher Validates that the String value is blank ```dataweave %dw 2.0 import dw::test::Asserts --- " " must beBlank() ``` ### beBoolean #### beBoolean(): Matcher Validates that a given value is of type Boolean ```dataweave %dw 2.0 import dw::test::Asserts --- true must beBoolean() ``` ### beEmpty #### beEmpty(): Matcher Validates that the value (String, Object or Array) is empty ```dataweave %dw 2.0 import dw::test::Asserts --- [] must beEmpty() ``` ### beGreaterThan #### beGreaterThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is greater than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::test::Asserts --- 3 must beGreaterThan(2) ``` ### beLowerThan #### beLowerThan(Comparable, Boolean): Matcher Validates that the asserted Comparable value is lower than the given one Can be equal to when using the _inclusive_ argument ```dataweave %dw 2.0 import dw::test::Asserts --- 1 must beLowerThan(2) ``` ### beNull #### beNull(): Matcher Validates that a given value is of type Null ```dataweave %dw 2.0 import dw::test::Asserts --- null must beNull() ``` ### beNumber #### beNumber(): Matcher Validates that a given value is of type Number ```dataweave %dw 2.0 import dw::test::Asserts --- 123 must beNumber() ``` ### beObject #### beObject(): Matcher Validates that a given value is of type Object ```dataweave %dw 2.0 import dw::test::Asserts --- { name : "Lionel", lastName: "Messi"} must beObject() ``` ### beOneOf #### beOneOf(Array): Matcher Validates that the value is contained in the given Array ```dataweave %dw 2.0 import dw::test::Asserts --- 1 must beOneOf([1, "A Text", true]) ``` ### beString #### beString(): Matcher Validates that a given value is of type String ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must beString() ``` ### contain #### contain(String): Matcher Validates that the asserted String contains the given String ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must contain("ex") ``` #### contain(Any): Matcher> Validates that the asserted Array contains the given value ```dataweave %dw 2.0 import dw::test::Asserts --- [1, "A Text", true] must contain(1) ``` ### eachItem #### eachItem(Matcher): Matcher> Validates that each item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::test::Asserts --- [1,2,3] must eachItem(beNumber()) ``` ### endWith #### endWith(String): Matcher Validates that the asserted String ends with the given String ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must endWith("xt") ``` ### equalTo #### equalTo(Any, { unordered?: Boolean }): Matcher Validates that a value is equal to another one ```dataweave %dw 2.0 import dw::test::Asserts --- (1 + 2) must equalTo(3) ``` ### equalToResource #### equalToResource(String, String, Object): Matcher Validates that the given value is equal to the content of a resource file The resource file must belong to the classpath ```dataweave %dw 2.0 import dw::test::Asserts --- { name: "Lionel", lastName: "Messi" } must equalToResource("user.json", "application/json") ``` ### haveItem #### haveItem(Matcher): Matcher> Validates that at least one item of the array satisfies the given matcher ```dataweave %dw 2.0 import dw::test::Asserts --- [1, true, "a text"] must haveItem(beNumber()) ``` ### haveKey #### haveKey(String): Matcher Validates that the Object has the given key ```dataweave %dw 2.0 import dw::test::Asserts --- { name: "Lionel", lastName: "Messi" } must haveKey("name") ``` ### haveSize #### haveSize(Number): Matcher Validates that the array has the given size ```dataweave %dw 2.0 import dw::test::Asserts --- [1, 4, 7] must haveSize(3) ``` ### haveValue #### haveValue(Any): Matcher Validates that the Object has the given value ```dataweave %dw 2.0 import dw::test::Asserts --- { name: "Lionel", lastName: "Messi" } must haveValue("Messi") ``` ### must #### must(T, Array<(value: T) → Matcher | MatcherResult | Boolean>): MatcherResult This function allows to assert a value with a list of Matcher of Expressions Example ```dataweave %dw 2.0 import dw::test::Asserts --- payload must [ beObject(), $.foo is Null ] ``` #### must(T, (value: T) → Matcher | Boolean): MatcherResult This function allows to assert a value with a Matcher of Expressions Example ```dataweave %dw 2.0 import dw::test::Asserts --- payload must beObject() ``` ### notBe #### notBe(Matcher): Matcher Validates that the value doesn’t satisfy the given matcher ```dataweave %dw 2.0 import dw::test::Asserts --- 1 must notBe(equalTo(2)) ``` ### notBeNull #### notBeNull(): Matcher Validates that a given value isn’t of type Null ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must notBeNull() ``` ### startWith #### startWith(String): Matcher Validates that the asserted String starts with the given String ```dataweave %dw 2.0 import dw::test::Asserts --- "A Text" must startWith("A") ``` ## Variables ### MATCHED Constant that represents a successful match ## Types ### Matcher Data Type that represents a Matcher to perform assertions Example ```dataweave %dw 2.0 import dw::test::Asserts fun beEqualToOne(): Matcher = (actual) -> do { { matches: actual == 1, description: { expected: "To be 1", actual: write(actual) as String } } } ``` Definition ```dataweave (value: T) -> MatcherResult ``` ### MatcherResult Data Type that represents the result of an Assertion Example ```dataweave { "matches": false, description : { expected : "Number type", actual: "A Text" } } ``` Definition ```dataweave { matches: Boolean, description: { expected: String, actual: String }, reasons?: Array } ``` --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Dynamic Directories > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit dynamic directories feature provides the `munit.temporary.directory` property to create and manage temporary files and folders during a MUnit test. The temporary directory is deleted automatically at the end of each test. For example, using the file connector, you could configure the working directory as follows: ```xml ``` And then use it to create files/folders inside it: ```xml ``` ## See Also - [Dynamic Ports](https://docs.mulesoft.com/munit/latest/dynamic-ports) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Dynamic Ports > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Dynamic Ports element binds a free port to a property at test runtime, preventing port conflicts when running MUnit tests in parallel. You can optionally restrict the port search to a specific range using min and max values. For example, a dynamic port would look something like this: ```xml ``` And it can be used in the http configuration: ```xml ``` Additionally you can set min and max values from where to get the port: ```xml ``` ## See Also - [Dynamic Directories](https://docs.mulesoft.com/munit/latest/dynamic-directories) - [Storage Event Processors](https://docs.mulesoft.com/munit/latest/storage-event-processors) --- product: MUnit version: 2.3 --- # MUnit Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit has a set of dedicated event processors to validate, assert, and mock the content and status of the Mule event so you can run automatic tests against your Mule applications. ## See Also - [Assertion Event Processor](https://docs.mulesoft.com/munit/2.3/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/2.3/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/2.3/verify-event-processor) - [Spy Event Processor](https://docs.mulesoft.com/munit/2.3/spy-event-processor) - [Storage Event Processors](https://docs.mulesoft.com/munit/2.3/storage-event-processors) - [Queue Event Processors](https://docs.mulesoft.com/munit/2.3/queue-processors) --- product: MUnit version: 3.6 --- # MUnit Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit has a set of dedicated event processors to validate, assert, and mock the content and status of the Mule event so you can run automatic tests against your Mule applications. ## See Also - [Assertion Event Processor](https://docs.mulesoft.com/munit/3.6/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/3.6/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/3.6/verify-event-processor) - [Spy Event Processor](https://docs.mulesoft.com/munit/3.6/spy-event-processor) - [Storage Event Processors](https://docs.mulesoft.com/munit/3.6/storage-event-processors) - [Queue Event Processors](https://docs.mulesoft.com/munit/3.6/queue-processors) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit event processors let you validate, assert, and mock the content and status of Mule events in automated MUnit tests. Use them to verify that your Mule application behaves as expected during test execution. ## See Also - [Assertion Event Processor](https://docs.mulesoft.com/munit/latest/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/latest/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/latest/verify-event-processor) - [Spy Event Processor](https://docs.mulesoft.com/munit/latest/spy-event-processor) - [Storage Event Processors](https://docs.mulesoft.com/munit/latest/storage-event-processors) - [Queue Event Processors](https://docs.mulesoft.com/munit/latest/queue-processors) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Fail Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Fail event processor forces a MUnit test to fail at a specific point in the flow, which is useful for validating that certain code paths are never reached. Use it to catch unexpected execution paths during testing. ```xml ``` The message field is optional and defines the error message to print when the assertion fails. The processor throws a `MUNIT-TOOLS:ASSERTION_ERROR`. --- product: MUnit version: 3.6 --- # MUnit in Anypoint Code Builder > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder MUnit is integrated with Anypoint Code Builder and you can: - Create and design MUnit tests - Run your tests - View test results - Debug your tests --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit in Anypoint Code Builder > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit is integrated with Anypoint Code Builder, letting you create, design, run, debug, and view results of MUnit tests directly from the IDE. You can generate test structures from flows, configure tests visually on the canvas, or write XML directly in the code editor. A dedicated Testing panel lets you run all suites, individual suites, or specific test cases, and view results alongside coverage metrics. For full instructions, see [Testing Projects with MUnit in Anypoint Code Builder](https://docs.mulesoft.com/anypoint-code-builder/int-test-munit). --- product: MUnit version: 3.6 --- # MUnit in Anypoint Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit is fully integrated with Anypoint Studio. You can use the Studio graphical interface to: - Create and design MUnit tests - Run your tests - View test results and coverage - Debug your tests ## See Also - [Scaffold a Template for an MUnit Test from an API Specification](https://docs.mulesoft.com/munit/3.6/munit-scaffold-test-task) - [Test Recorder in Studio](https://docs.mulesoft.com/munit/3.6/test-recorder) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit in Anypoint Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit is fully integrated with Anypoint Studio, letting you create, design, run, debug, and view results of MUnit tests directly from the IDE. You can configure tests visually on the canvas or write XML in the editor, and view test results and coverage metrics from the MUnit panel. For full instructions, see [Testing Projects with MUnit in Studio](https://docs.mulesoft.com/studio/test-with-munit-in-studio). ## See Also - [Scaffold an MUnit Test Suite from an API Specification](https://docs.mulesoft.com/munit/latest/munit-scaffold-test-task) - [MUnit Test Recorder in Anypoint Studio](https://docs.mulesoft.com/munit/latest/test-recorder) --- product: MUnit version: 2.3 --- # MUnit in Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit is fully integrated with Anypoint Studio. You can use Studio’s graphical interface to: - Create and design MUnit tests. - Run your tests. - View test results and coverage. - Debug your tests. ## See Also - [Scaffold a Template for an MUnit Test from an API Specification](https://docs.mulesoft.com/munit/2.3/munit-scaffold-test-task) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Iterable and Map Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Iterable and Map matchers are matcher functions for asserting conditions on collections and maps during a MUnit test. Use them with the Assert That processor to check items, keys, values, and sizes of iterables and maps. ## everyItem(Matcher) Checks that every element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasItem(Object) Checks that any element in the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasSize(Matcher|Integer) Checks that the size of the expression matches the specified matcher. Example ```xml ``` Example ```xml ``` ## isEmpty() Checks that the expression is an empty collection. Example ```xml ``` ## hasKey(Matcher|String) Checks that the expression has a key that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## hasValue(Object) Checks that the expression has a value that matches the specified matcher. Example ```xml ``` Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/latest/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/latest/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference) --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # MUnit Matchers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit matchers are a set of DataWeave functions to define assertion conditions for any value in an expression. When defining matchers, include the prefix `MunitTools::` in the expression, as illustrated in the following examples. Matchers are grouped according to the type of conditions you want to validate. ## Match Core Values Core matchers evaluate core values in the expression: - Is the expression null? - What is the media type or encoding of the expression? - Does the expression return false? - Are two evaluations successful? Core Matchers: - [nullValue()](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#nullvalue) checks that the expression is null. Example: ```DataWeave #[MunitTools::nullValue()] ``` - [notNullValue()](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#notnullvalue) checks that the expression is not null. Example: ```DataWeave #[MunitTools::notNullValue()] ``` - [withMediaType(String)](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#withmediatype-string) checks that the expression’s media type is the one specified. Example: ```DataWeave #[MunitTools::withMediaType('text/xml')] ``` - [withEncoding(String)](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#withencoding-string) checks that the expression’s encoding is the one specified. Example: ```DataWeave #[MunitTools::withEncoding('UTF-8')] ``` - [both(Matcher, Matcher)](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#both-matcher-matcher) checks that both provided matchers are successful. Example: ```DataWeave #[MunitTools::both(MunitTools::notNullValue(), MunitTools::equalTo('example'))] ``` - [either(Matcher,Matcher)](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#either-matcher-matcher) checks that at least one of the matchers is successful. Example: ```DataWeave #[MunitTools::either(MunitTools::nullValue(), MunitTools::equalTo(0))] ``` - [not(Matcher)](https://docs.mulesoft.com/munit/2.3/core-matchers-reference#not-matcher) checks if the provided matcher is not successful. Example: ```DataWeave #[MunitTools::not(MunitTools::equalTo(0))] ``` - [anyOf(Matchers\[\])](core-matchers-reference#anyof-matchers) checks if any of the matchers are successful. Example: ```DataWeave #[MunitTools::anyOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` - [allOf(Matchers\[\])](core-matchers-reference#allof-matchers) checks if all of the matchers are successful. Example: ```DataWeave #[MunitTools::allOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` ## Match Strings String Matchers perform assertions on String expressions: - Does the expression contain a specified string? - Does the expression start or end with a specified string? - Does the string in the expression have zero length? - Does the string in the expression match a specified string? String Matchers: - [containsString(String)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#containsstring-string) checks that the expression contains the specified String. Example: ```DataWeave #[MunitTools::containsString('example')] ``` - [startsWith(String)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#startswith-string) checks that the expression starts with the specified String. Example: ```DataWeave #[MunitTools::startsWith('exam')] ``` - [endsWith(String)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#endswith-string) checks that the expression ends with the specified String. Example: ```DataWeave #[MunitTools::endsWith('ple')] ``` - [isEmptyString()](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#isemptystring) checks that the expression has zero length. Example: ```DataWeave #[MunitTools::isEmptyString()] ``` - [isEmptyOrNullString()](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#isemptyornullstring) checks that the expression is null, or has zero length. Example: ```DataWeave #[MunitTools::isEmptyOrNullString()] ``` - [equalToIgnoringCase(String)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#equaltoignoringcase-string) checks that the expression is equal to the specified String, ignoring case. Example: ```DataWeave #[MunitTools::equalToIgnoringCase('example')] ``` - [equalToIgnoringWhiteSpace(String)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#equaltoignoringwhitespace-string) checks that the expression is equal to the string disregarding leading and trailing white spaces, and compressing all inner white spaces to a single space. Example: ```DataWeave #[MunitTools::equalToIgnoringWhiteSpace('An Example')] ``` - [stringContainsInOrder(String, String,…​)](https://docs.mulesoft.com/munit/2.3/string-matchers-reference#stringcontainsinorder-array-string) checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example: ```DataWeave is="#[MunitTools::stringContainsInOrder(['an', 'example'])]"/> ``` ## Match Comparable Expressions Comparable matchers compare the expression against a specified value: - Is the expression’s value bigger or smaller than a specified value? - Is the expression’s value closer to a specific number? Some comparable matchers take a `Comparable` type. `Comparable` is a DataWeave type that represents all the types that can be compared to each other. Allowed primitives are `String`, `Number`, `Boolean`, `DateTime`, `LocalDateTime`, `LocalTime`, `Time`, and `TimeZone`. Comparable Matchers: - [greaterThan(Comparable)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#greaterthan-comparable) checks that the expression is greater than the specified value. Examples: ```DataWeave #[MunitTools::greaterThan(20)] ``` ```DataWeave #[MunitTools::greaterThan(|2017-08-09|)] ``` - [greaterThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#greaterthanorequalto-comparable) checks that the expression is greater than or equal to the specified value. Examples: ```DataWeave #[MunitTools::greaterThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::greaterThanOrEqualTo(|2017-08-09|)] ``` - [lessThan(Comparable)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#lessthan-comparable) checks that the expression is less than the specified value. Examples: ```DataWeave #[MunitTools::lessThan(20) ``` ```DataWeave #[MunitTools::lessThan(|2017-08-09|)] ``` - [lessThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#lessthanorequalto-comparable) checks that the expression is less than or equal to the specified value. Examples: ```DataWeave #[MunitTools::lessThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::lessThanOrEqualTo(|2017-08-09|)] ``` - [closeTo(Number, Number)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#closeto-number-number) checks that the expression is in the range defined by the first and second number. Example: ```DataWeave #[MunitTools::closeTo(1, 0.01)] ``` - [equalTo(Object)](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference#equalto-object) checks that the expression is equal to a specified value. This matcher also accepts DataWeave objects. Examples: ```DataWeave #[MunitTools::equalTo('example')] ``` ```DataWeave #[MunitTools::equalTo({example1: 1 , example2: 2}] ``` ## Match Maps and Iterations Use iterable matchers and maps matchers when your expression is an array or a map of data: - Is the map or array in the expression empty? - Does the map or array in the expression have a specific key? - Is every item in the array from the expression greater than or less than a specific number? - Does any item in the array from the expression start or end with a specified string? Iterable and Map Matchers: - [everyItem(Matcher)](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#everyitem-matcher) checks that every element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::everyItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::everyItem(MunitTools::startsWith('a'))] ``` - [hasItem(Matcher)](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#hasitem-matcher) checks that any element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::hasItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::hasItem(MunitTools::startsWith('a'))] ``` - [hasSize(Matcher)](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#hassize-matcher) checks that the size of the expression matches the specified matcher. Examples: ```DataWeave #[MunitTools::hasSize(MunitTools::equalTo(5))] ``` ```DataWeave #[MunitTools::hasSize(MunitTools::greaterThan(5))] ``` - [isEmpty()](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#isempty) checks that the expression is an empty collection. Examples: ```DataWeave #[MunitTools::isEmpty()] ``` - [hasKey(Matcher)](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#haskey-matcher) checks that the expression has a key that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasKey(MunitTools::equalTo('myKey'))] ``` ```DataWeave #[MunitTools::hasKey(MunitTools::startsWith('a'))] ``` - [hasValue(Matcher)](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference#hasvalue-matcher) checks that the expression has a value that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasValue(MunitTools::equalTo('myValue'))] ``` ```DataWeave #[MunitTools::hasValue(MunitTools::startsWith('a'))] ``` ## See Also - [Core Matchers Reference](https://docs.mulesoft.com/munit/2.3/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/2.3/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference) - [Assert That Event Processor](https://docs.mulesoft.com/munit/2.3/assertion-event-processor) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # MUnit Matchers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit matchers are a set of DataWeave functions to define assertion conditions for any value in an expression. When defining matchers, include the prefix `MunitTools::` in the expression, as illustrated in the following examples. Matchers are grouped according to the type of conditions you want to validate. ## Match Core Values Core matchers evaluate core values in the expression: - Is the expression null? - What is the media type or encoding of the expression? - Does the expression return false? - Are two evaluations successful? Core Matchers: - [nullValue()](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#nullvalue) checks that the expression is null. Example: ```DataWeave #[MunitTools::nullValue()] ``` - [notNullValue()](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#notnullvalue) checks that the expression is not null. Example: ```DataWeave #[MunitTools::notNullValue()] ``` - [withMediaType(String)](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#withmediatype-string) checks that the expression’s media type is the one specified. Example: ```DataWeave #[MunitTools::withMediaType('text/xml')] ``` - [withEncoding(String)](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#withencoding-string) checks that the expression’s encoding is the one specified. Example: ```DataWeave #[MunitTools::withEncoding('UTF-8')] ``` - [both(Matcher, Matcher)](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#both-matcher-matcher) checks that both provided matchers are successful. Example: ```DataWeave #[MunitTools::both(MunitTools::notNullValue(), MunitTools::equalTo('example'))] ``` - [either(Matcher,Matcher)](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#either-matcher-matcher) checks that at least one of the matchers is successful. Example: ```DataWeave #[MunitTools::either(MunitTools::nullValue(), MunitTools::equalTo(0))] ``` - [not(Matcher)](https://docs.mulesoft.com/munit/3.6/core-matchers-reference#not-matcher) checks if the provided matcher is not successful. Example: ```DataWeave #[MunitTools::not(MunitTools::equalTo(0))] ``` - [anyOf(Matchers\[\])](core-matchers-reference#anyof-matchers) checks if any of the matchers are successful. Example: ```DataWeave #[MunitTools::anyOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` - [allOf(Matchers\[\])](core-matchers-reference#allof-matchers) checks if all of the matchers are successful. Example: ```DataWeave #[MunitTools::allOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` ## Match Strings String Matchers perform assertions on String expressions: - Does the expression contain a specified string? - Does the expression start or end with a specified string? - Does the string in the expression have zero length? - Does the string in the expression match a specified string? String Matchers: - [containsString(String)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#containsstring-string) checks that the expression contains the specified String. Example: ```DataWeave #[MunitTools::containsString('example')] ``` - [startsWith(String)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#startswith-string) checks that the expression starts with the specified String. Example: ```DataWeave #[MunitTools::startsWith('exam')] ``` - [endsWith(String)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#endswith-string) checks that the expression ends with the specified String. Example: ```DataWeave #[MunitTools::endsWith('ple')] ``` - [isEmptyString()](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#isemptystring) checks that the expression has zero length. Example: ```DataWeave #[MunitTools::isEmptyString()] ``` - [isEmptyOrNullString()](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#isemptyornullstring) checks that the expression is null, or has zero length. Example: ```DataWeave #[MunitTools::isEmptyOrNullString()] ``` - [equalToIgnoringCase(String)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#equaltoignoringcase-string) checks that the expression is equal to the specified String, ignoring case. Example: ```DataWeave #[MunitTools::equalToIgnoringCase('example')] ``` - [equalToIgnoringWhiteSpace(String)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#equaltoignoringwhitespace-string) checks that the expression is equal to the string disregarding leading and trailing white spaces, and compressing all inner white spaces to a single space. Example: ```DataWeave #[MunitTools::equalToIgnoringWhiteSpace('An Example')] ``` - [stringContainsInOrder(String, String,…​)](https://docs.mulesoft.com/munit/3.6/string-matchers-reference#stringcontainsinorder-array-string) checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example: ```DataWeave is="#[MunitTools::stringContainsInOrder(['an', 'example'])]"/> ``` ## Match Comparable Expressions Comparable matchers compare the expression against a specified value: - Is the expression’s value bigger or smaller than a specified value? - Is the expression’s value closer to a specific number? Some comparable matchers take a `Comparable` type. `Comparable` is a DataWeave type that represents all the types that can be compared to each other. Allowed primitives are `String`, `Number`, `Boolean`, `DateTime`, `LocalDateTime`, `LocalTime`, `Time`, and `TimeZone`. Comparable Matchers: - [greaterThan(Comparable)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#greaterthan-comparable) checks that the expression is greater than the specified value. Examples: ```DataWeave #[MunitTools::greaterThan(20)] ``` ```DataWeave #[MunitTools::greaterThan(|2017-08-09|)] ``` - [greaterThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#greaterthanorequalto-comparable) checks that the expression is greater than or equal to the specified value. Examples: ```DataWeave #[MunitTools::greaterThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::greaterThanOrEqualTo(|2017-08-09|)] ``` - [lessThan(Comparable)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#lessthan-comparable) checks that the expression is less than the specified value. Examples: ```DataWeave #[MunitTools::lessThan(20) ``` ```DataWeave #[MunitTools::lessThan(|2017-08-09|)] ``` - [lessThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#lessthanorequalto-comparable) checks that the expression is less than or equal to the specified value. Examples: ```DataWeave #[MunitTools::lessThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::lessThanOrEqualTo(|2017-08-09|)] ``` - [closeTo(Number, Number)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#closeto-number-number) checks that the expression is in the range defined by the first and second number. Example: ```DataWeave #[MunitTools::closeTo(1, 0.01)] ``` - [equalTo(Object)](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference#equalto-object) checks that the expression is equal to a specified value. This matcher also accepts DataWeave objects. Examples: ```DataWeave #[MunitTools::equalTo('example')] ``` ```DataWeave #[MunitTools::equalTo({example1: 1 , example2: 2}] ``` ## Match Maps and Iterations Use iterable matchers and maps matchers when your expression is an array or a map of data: - Is the map or array in the expression empty? - Does the map or array in the expression have a specific key? - Is every item in the array from the expression greater than or less than a specific number? - Does any item in the array from the expression start or end with a specified string? Iterable and Map Matchers: - [everyItem(Matcher)](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#everyitem-matcher) checks that every element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::everyItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::everyItem(MunitTools::startsWith('a'))] ``` - [hasItem(Matcher)](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#hasitem-matcher) checks that any element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::hasItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::hasItem(MunitTools::startsWith('a'))] ``` - [hasSize(Matcher)](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#hassize-matcher) checks that the size of the expression matches the specified matcher. Examples: ```DataWeave #[MunitTools::hasSize(MunitTools::equalTo(5))] ``` ```DataWeave #[MunitTools::hasSize(MunitTools::greaterThan(5))] ``` - [isEmpty()](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#isempty) checks that the expression is an empty collection. Examples: ```DataWeave #[MunitTools::isEmpty()] ``` - [hasKey(Matcher)](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#haskey-matcher) checks that the expression has a key that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasKey(MunitTools::equalTo('myKey'))] ``` ```DataWeave #[MunitTools::hasKey(MunitTools::startsWith('a'))] ``` - [hasValue(Matcher)](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference#hasvalue-matcher) checks that the expression has a value that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasValue(MunitTools::equalTo('myValue'))] ``` ```DataWeave #[MunitTools::hasValue(MunitTools::startsWith('a'))] ``` ## See Also - [Core Matchers Reference](https://docs.mulesoft.com/munit/3.6/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/3.6/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference) - [Assert That Event Processor](https://docs.mulesoft.com/munit/3.6/assertion-event-processor) --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Matchers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit matchers are DataWeave functions that define assertion conditions for any value in an expression, used with the Assert That processor. Include the prefix `MunitTools::` when using them, and choose from core, string, comparable, or iterable and map matcher groups depending on the type of value you want to validate. ## Match Core Values Core matchers evaluate core values in the expression: - Is the expression null? - What is the media type or encoding of the expression? - Does the expression return false? - Are two evaluations successful? Core Matchers: - [nullValue()](https://docs.mulesoft.com/munit/latest/core-matchers-reference#nullvalue) checks that the expression is null. Example: ```DataWeave #[MunitTools::nullValue()] ``` - [notNullValue()](https://docs.mulesoft.com/munit/latest/core-matchers-reference#notnullvalue) checks that the expression is not null. Example: ```DataWeave #[MunitTools::notNullValue()] ``` - [withMediaType(String)](https://docs.mulesoft.com/munit/latest/core-matchers-reference#withmediatype-string) checks that the expression’s media type is the one specified. Example: ```DataWeave #[MunitTools::withMediaType('text/xml')] ``` - [withEncoding(String)](https://docs.mulesoft.com/munit/latest/core-matchers-reference#withencoding-string) checks that the expression’s encoding is the one specified. Example: ```DataWeave #[MunitTools::withEncoding('UTF-8')] ``` - [both(Matcher, Matcher)](https://docs.mulesoft.com/munit/latest/core-matchers-reference#both-matcher-matcher) checks that both provided matchers are successful. Example: ```DataWeave #[MunitTools::both(MunitTools::notNullValue(), MunitTools::equalTo('example'))] ``` - [either(Matcher,Matcher)](https://docs.mulesoft.com/munit/latest/core-matchers-reference#either-matcher-matcher) checks that at least one of the matchers is successful. Example: ```DataWeave #[MunitTools::either(MunitTools::nullValue(), MunitTools::equalTo(0))] ``` - [not(Matcher)](https://docs.mulesoft.com/munit/latest/core-matchers-reference#not-matcher) checks if the provided matcher is not successful. Example: ```DataWeave #[MunitTools::not(MunitTools::equalTo(0))] ``` - [anyOf(Matchers\[\])](core-matchers-reference#anyof-matchers) checks if any of the matchers are successful. Example: ```DataWeave #[MunitTools::anyOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` - [allOf(Matchers\[\])](core-matchers-reference#allof-matchers) checks if all of the matchers are successful. Example: ```DataWeave #[MunitTools::allOf([MunitTools::notNullValue(),MunitTools::withMediaType('text/xml'),MunitTools::isEmptyString()])] ``` ## Match Strings String Matchers perform assertions on String expressions: - Does the expression contain a specified string? - Does the expression start or end with a specified string? - Does the string in the expression have zero length? - Does the string in the expression match a specified string? String Matchers: - [containsString(String)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#containsstring-string) checks that the expression contains the specified String. Example: ```DataWeave #[MunitTools::containsString('example')] ``` - [startsWith(String)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#startswith-string) checks that the expression starts with the specified String. Example: ```DataWeave #[MunitTools::startsWith('exam')] ``` - [endsWith(String)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#endswith-string) checks that the expression ends with the specified String. Example: ```DataWeave #[MunitTools::endsWith('ple')] ``` - [isEmptyString()](https://docs.mulesoft.com/munit/latest/string-matchers-reference#isemptystring) checks that the expression has zero length. Example: ```DataWeave #[MunitTools::isEmptyString()] ``` - [isEmptyOrNullString()](https://docs.mulesoft.com/munit/latest/string-matchers-reference#isemptyornullstring) checks that the expression is null, or has zero length. Example: ```DataWeave #[MunitTools::isEmptyOrNullString()] ``` - [equalToIgnoringCase(String)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#equaltoignoringcase-string) checks that the expression is equal to the specified String, ignoring case. Example: ```DataWeave #[MunitTools::equalToIgnoringCase('example')] ``` - [equalToIgnoringWhiteSpace(String)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#equaltoignoringwhitespace-string) checks that the expression is equal to the string disregarding leading and trailing white spaces, and compressing all inner white spaces to a single space. Example: ```DataWeave #[MunitTools::equalToIgnoringWhiteSpace('An Example')] ``` - [stringContainsInOrder(String, String,…​)](https://docs.mulesoft.com/munit/latest/string-matchers-reference#stringcontainsinorder-array-string) checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example: ```DataWeave is="#[MunitTools::stringContainsInOrder(['an', 'example'])]"/> ``` ## Match Comparable Expressions Comparable matchers compare the expression against a specified value: - Is the expression’s value bigger or smaller than a specified value? - Is the expression’s value closer to a specific number? Some comparable matchers take a `Comparable` type. `Comparable` is a DataWeave type that represents all the types that can be compared to each other. Allowed primitives are `String`, `Number`, `Boolean`, `DateTime`, `LocalDateTime`, `LocalTime`, `Time`, and `TimeZone`. Comparable Matchers: - [greaterThan(Comparable)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#greaterthan-comparable) checks that the expression is greater than the specified value. Examples: ```DataWeave #[MunitTools::greaterThan(20)] ``` ```DataWeave #[MunitTools::greaterThan(|2017-08-09|)] ``` - [greaterThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#greaterthanorequalto-comparable) checks that the expression is greater than or equal to the specified value. Examples: ```DataWeave #[MunitTools::greaterThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::greaterThanOrEqualTo(|2017-08-09|)] ``` - [lessThan(Comparable)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#lessthan-comparable) checks that the expression is less than the specified value. Examples: ```DataWeave #[MunitTools::lessThan(20) ``` ```DataWeave #[MunitTools::lessThan(|2017-08-09|)] ``` - [lessThanOrEqualTo(Comparable)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#lessthanorequalto-comparable) checks that the expression is less than or equal to the specified value. Examples: ```DataWeave #[MunitTools::lessThanOrEqualTo(20)] ``` ```DataWeave #[MunitTools::lessThanOrEqualTo(|2017-08-09|)] ``` - [closeTo(Number, Number)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#closeto-number-number) checks that the expression is in the range defined by the first and second number. Example: ```DataWeave #[MunitTools::closeTo(1, 0.01)] ``` - [equalTo(Object)](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference#equalto-object) checks that the expression is equal to a specified value. This matcher also accepts DataWeave objects. Examples: ```DataWeave #[MunitTools::equalTo('example')] ``` ```DataWeave #[MunitTools::equalTo({example1: 1 , example2: 2}] ``` ## Match Maps and Iterations Use iterable matchers and maps matchers when your expression is an array or a map of data: - Is the map or array in the expression empty? - Does the map or array in the expression have a specific key? - Is every item in the array from the expression greater than or less than a specific number? - Does any item in the array from the expression start or end with a specified string? Iterable and Map Matchers: - [everyItem(Matcher)](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#everyitem-matcher) checks that every element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::everyItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::everyItem(MunitTools::startsWith('a'))] ``` - [hasItem(Matcher)](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#hasitem-matcher) checks that any element in the expression matches the specified matcher. This matcher works only for arrays. Examples: ```DataWeave #[MunitTools::hasItem(MunitTools::notNullValue())] ``` ```DataWeave #[MunitTools::hasItem(MunitTools::startsWith('a'))] ``` - [hasSize(Matcher)](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#hassize-matcher) checks that the size of the expression matches the specified matcher. Examples: ```DataWeave #[MunitTools::hasSize(MunitTools::equalTo(5))] ``` ```DataWeave #[MunitTools::hasSize(MunitTools::greaterThan(5))] ``` - [isEmpty()](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#isempty) checks that the expression is an empty collection. Examples: ```DataWeave #[MunitTools::isEmpty()] ``` - [hasKey(Matcher)](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#haskey-matcher) checks that the expression has a key that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasKey(MunitTools::equalTo('myKey'))] ``` ```DataWeave #[MunitTools::hasKey(MunitTools::startsWith('a'))] ``` - [hasValue(Matcher)](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference#hasvalue-matcher) checks that the expression has a value that matches the specified matcher. This matcher works only for maps. Examples: ```DataWeave #[MunitTools::hasValue(MunitTools::equalTo('myValue'))] ``` ```DataWeave #[MunitTools::hasValue(MunitTools::startsWith('a'))] ``` ## See Also - [Core Matchers Reference](https://docs.mulesoft.com/munit/latest/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/latest/string-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference) - [Assert That Event Processor](https://docs.mulesoft.com/munit/latest/assertion-event-processor) --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # MUnit Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit provides a Maven plugin that enables you to run your MUnit tests as part of your continuous integration environment. The following configurations to the `pom.xml` or `settings.xml` files of your Maven installation apply only when running Munit through Maven. ## Set Up MUnit Maven Plugin This documentation assumes you have the `` property in your pom.xml. - Enable the MUnit Maven plugin in your `pom.xml` file: MUnit Maven Plugin ```xml ... com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test ... ``` - Add MUnit dependencies to your `pom.xml` file: Dependencies ```xml ... com.mulesoft.munit munit-runner ${munit.version} mule-plugin test com.mulesoft.munit munit-tools ${munit.version} mule-plugin test ... ``` - Configure the repositories for the MUnit dependencies and plugin: Repositories ```xml mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default ``` Plugin Repositories ```xml mulesoft-release mulesoft release repository default https://repository.mulesoft.org/releases/ false ``` MUnit has Surefire support built in. The reports output to `target/surefire-reports`. ### Handle Parent POM Files You can declare the MUnit plugin in a parent `pom.xml` file and every child project under this file can reference this definition. To configure the MUnit Maven plugin in a parent-child POM relationship, include the MUnit plugin declaration in the `` section of your parent `pom.xml` file. In the following example, the `pirate-pom` project declares the MUnit Maven plugin in its plugin management section, which defines a global configuration that each child under this parent can reference, override or even ignore. ```xml 4.1.0 org.pirate pirate-pom 1.0-SNAPSHOT pom 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test true false 0 0 0 console html ``` ### Inherit a Parent Plugin To inherit the MUnit plugin in your child `pom.xml` files, reference it in the `` section of each child POM file individually. The following sample references `pirate-pom` file as its parent and then declares the MUnit plugin in a `` section without specifying its `` because the MUnit plugin configuration is inherited from the `` section in the parent POM file: POM child file sample ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.4 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ``` ### Ignore a Parent Plugin Each child project under a parent `pom.xml` file can ignore the plugin referenced in the parent plugin management section and not implement the plugin configuration declared there. By not declaring the Munit Plugin in your `` section, you avoid inheriting the plugin declared in **pirate-pom**: Child POM file not inheriting the MUnit Maven Plugin ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.0 2.3.0 ``` ### Override a Parent Plugin When inheriting the plugin from a parent POM file, you can also override the parent configuration. Overriding the plugin configuration from your parent POM file suppresses the original configuration requiring you to declare all necessary configurations again. The following example overrides the console coverage report from its parent POM file, replacing it by the HTML report. Because the values from the other elements in the parent (``, ``, ``, ``) are not being referenced, this child file won’t inherit them and the default values will apply: Coverage configuration in parent POM file ```xml true false 0 0 0 console html ``` POM child file overriding coverage report’s format ```xml com.mulesoft.munit.tools munit-maven-plugin true html ``` ## Set Up Coverage The following configurations only apply when you execute your MUnit tests using the Maven plugin. They do not apply when running tests from Studio. See [Using Coverage in Maven](https://docs.mulesoft.com/munit/2.3/coverage-maven-concept) for more information. Since MUnit 2.x, the coverage report goal is integrated with the maven reporting section. Coverage Reports are generated during Maven’s `site` lifecycle, during the `coverage-report` goal. The following configurations apply only when you execute your MUnit tests using the Maven plugin. They do not apply when running tests from Studio. To run coverage reports in Studio see [Using Coverage in Studio](https://docs.mulesoft.com/munit/2.3/coverage-studio-concept). MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ### Set up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level is not reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each individual Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage is not defined, it defaults to -1, which indicates that no requirements are defined for said level so the build will not fail due to low coverage.
If you define coverage levels but set the property `failBuild` to **false**, and then the levels are not reached, a warning shows up in the MUnit coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level was not met, and where it happened.
### Ignore a flow or a file Another feature is the ability to ignore either a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow is not tested or if the flow does not reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore both flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## Dynamic Ports MUnit 2.2 and later introduce the `dynamic-port` global element, that allows you to define dynamic ports at the MUnit suite level. Using this element instead of the plugin configuration described as follows allows you to set the dynamic port both from Maven and Studio. See [Dynamic Ports](https://docs.mulesoft.com/munit/2.3/dynamic-ports) to learn how to configure this element. When testing a Mule application in a continuous integration (CI) environment, you might encounter the following scenario: Your application tries to open a specific port. The port is already in use. The application fails with a port binding exception. The MUnit Maven Plugin comes with a built-in feature to make your application use a free port. MUnit Dynamic Ports instructs the MUnit Maven Plugin to look for unbound ports and reserve them before running the tests over the Mule application. Each port selected is placed in a system property under the name indicated in the configuration. The application can acquire the port number through the use of placeholders afterward. The Ports to be selected by the plugin are taken from the range: `[40000,50000]` > [!CAUTION] Dynamic Ports feature is only available as part of the MUnit Maven Plugin. This feature > does not work when running tests from inside Anypoint Studio. ### Enable Dynamic Ports To enable the feature, you need to add the following code to the `configuration` section of the MUnit Maven Plugin: Dynamic Ports Configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ... a.dynamic.port ... ``` If you have the `${http.port}` placeholder in your application, the configuration looks something like: Example ```xml http.port ``` ### Prepare Your Application A placeholder must parameterize the part of the application trying to make use of a port. For example, to have your Mule application listening for HTTP traffic, provide the following configuration: HTTP Application ```xml ``` The previous application always listens in port `8081`. To make it dynamic, change it to: HTTP Application with dynamic port ```xml (1) ```
1Notice the placeholder ${http.port}.
With the application coded in this way and the configuration of Dynamic Ports in place, your application starts each run listening on a different port. ## Enable Surefire Reports MUnit has built-in support for Surefire. No additional configuration is needed, but you can disable it if you don’t need it: Disable surefire reports ```none false ``` The reports can be found under `${project.build.directory}/surefire-reports`. By default, it is set to `true`. ## Enable Sonar Reports MUnit has built-in support for SonarQube, with a default setting of `true` for `enableSonarReports`. No additional configuration is needed. You can find the reports under `${project.build.directory}/sonar-reports`. You can disable SONAR reports if you don’t need them: Disable sonar reports ```none false ``` The reports can be found under `${project.build.directory}/sonar-reports`. By default, it is set to `true`. ## Run Tests Using the Plugin ### Run MUnit Tests for a Mule Application Run MUnit tests in a Single Resource Mule project. ```none mvn clean test ``` ### Run a Specific MUnit Test Suite By using the property `munit.test`, you can instruct the MUnit Maven plugin to run only tests that belong to a specific test suite: ```maven mvn clean test -Dmunit.test= ``` This path is relative to `src/test/munit`. The property `munit.test` accepts regular expressions. The expression is applied to the name of the MUnit Test Suite file. The regular expression language is the Java implementation. For example: ```console mvn clean test -Dmunit.test=.*my-test.* ``` You can leverage this feature by adding naming conventions to your MUnit Test suites. ### Run Specific MUnit Tests In the same way that you instruct MUnit to run one test suite, you can also configure it to run a specific test inside that test suite. You must use the property `munit.test` with the addition of the the special character `#` to append the test name: ```console mvn clean test -Dmunit.test=# ``` It also accepts regular expressions. The expression is applied to the attribute `name` of the MUnit Test. For example: ```console mvn clean test -Dmunit.test=.*my-test.*#.*test-scenario-1.* ``` The tests inside the MUnit Test Suite that don’t match the regular expression are flagged as **ignored**. You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... example-MunitTest-suite.xml ... ``` ### Run Tests Using a Specific Tag You can run only the tests that you grouped under one specific tag: ```console mvn clean test -Dmunit.tags= ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleMunitTag ... ``` You can specify more than one tag by separating them using a comma. ### Skip All Tests MUnit leverages the same mechanism as Maven. To skip tests, you must use the `skipTests` parameter: Skip Tests example ```console mvn clean package -DskipTests ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` ### Skip Tests After One Suite Fails MUnit allows you to skip the rest of the tests if one test suite fails: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` If not specified, this value is `false` by default. ## Specify The Runtime Product You can specify the type of runtime in which your applications being tested will run. Accepted values are: - `MULE` for community edition. - `MULE_EE` for enterprise edition. ```xml com.mulesoft.munit.tools munit-maven-plugin ... MULE ... ``` ### Specify the Runtime Product Version MUnit allows you to specify the runtime version in which your applications being tested will run. ```xml com.mulesoft.munit.tools munit-maven-plugin ... 4.2.2 ... ``` ## Specify The JVM You can specify the JVM (or the java executable) in which your applications being tested run. You must populate the `munit.jvm` parameter with the path to the executable: Specify the JVM ```console mvn clean package -Dmunit.jvm=/path/to/jdk/bin/java ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... /path/to/jdk/bin/java ... ``` ### Additional Argument Lines You can pass additional argument lines to the JVM. Specify each argument in a separate `argLine`: Argument lines ```xml com.mulesoft.munit.tools munit-maven-plugin ... -XX:MaxPermSize=512m -Xmx1024m ... ``` ### Environment Variables To set additional environment variables during the test run, you can specify them with the respective key and value: Additional Environment Variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleValue val2 ... ``` As shown in the previous example, you can use environment variables to replace placeholders such as `${MY_ENV}`. ### System Properties Variables You may need to define specific system variables so that your MUnit test runs successfully: Setting system property variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... my.property.value ... ``` Depending on the execution context, the system properties values may vary. When referencing these properties, it is a good practice to override their value to enforce test reproducibility. You can do so using the ­`-D` argument when running MUnit with Maven. Variables passed with the `-D` argument take full priority over any other property. For example: ```none -Dmy.property.key=my.property.another.value ``` ## Redirect Test Output to File When running several tests, the build output can get very complex to read. MUnit allows you to redirect the output of each test suite to a file. This way, only the test results will remain in the build output and to you can check the respective file to check the standard output of each test suite. These files are located in the `testOutputDirectory` folder following the naming convention: `munit.${suiteName}-output.txt`, where the `suiteName` represents the name of the XML file relative to the MUnit test folder. The test’s output that doesn’t belong to a particular suite won’t be printed to keep the build output clean, but it can be enabled by running maven in debug mode. To redirect the output of each test suite to a file: Redirect test output to file ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` By default, it is set to `false` ### Test Output Directory You may want to choose the location where the test output files will be created. The path specified can be absolute or written as a Maven placeholder: Test output directory with absolute path ```xml com.mulesoft.munit.tools munit-maven-plugin ... /my/absolute/path ... ``` Test output directory using maven placeholders ```xml ${project.build.directory}/my/output/folder ``` By default, the files are created in `${project.build.directory}/munit-reports/output/`. ## MUnit Maven Plugin Configuration Reference The MUnit Maven Plugin offers a set of optional parameters that can be configured.
Table 1. Maven Plugin Parameters
NameTypeDescription

argLines

List

Additional JVM argument lines to set on the test run.

coverage

Configuration

Coverage configuration to be set on the test run.

dynamicPorts

List

Dynamic ports to be set on the test run.

enableSurefireReports

boolean

Set value to true to generate MUnit test results in the surefire format.
Default value: true

munitTest

String

Name of the MUnit tests to run.

munitTags

String

Name of the MUnit tags. Only tests tagged with these names will run.

skipMunitTests

boolean

Set to true when you want to skip all MUnit tests.
Default value: false

skipAfterFailure

boolean

Skip all tests if one fails.
Default value: false

munitTestsDirectory

File

Directory where the MUnit tests reside.
Default value: ${project.build.directory}/test-mule/munit

runtimeVersion

String

Version of the Mule runtime
When you run your tests from Maven, this value is taken from the minMuleVersion parameter in the mule-artifact.json file.
To modify the Mule runtime version used to run your MUnit tests in Studio, see Runtime Patching in Studio.

runtimeProduct

String

Type of runtime. Expected values are:

  • MULE for community edition

  • MULE_EE for enterprise edition.

By default, this value is taken from the requiredProduct parameter in the mule-artifact.json file.

jvm

String

Option to specify the JVM (or path to the java executable) to use.

By default, the JVM will the same VM as the one used to run Maven.

environmentVariables

Map

Additional environment variables to be set on the test run.

redirectTestOutputToFile

boolean

Set value to true to redirect the MUnit tests standard output to a file.
Default value: false

systemPropertyVariables

Map

System properties to be set on the test run.

testOutputDirectory

File

Directory where the test outputs will be written to.
Default value: ${project.build.directory}/munit-reports/output/

--- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # MUnit Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit provides a Maven plugin that enables you to run your MUnit tests as part of your continuous integration environment. The following configurations to the `pom.xml` or `settings.xml` files of your Maven installation apply only when running MUnit through Maven. ## Set Up MUnit Maven Plugin You must have the `` property in your pom.xml to set up MUnit Maven Plugin. - Enable MUnit Maven Plugin in your `pom.xml` file: MUnit Maven Plugin ```xml ... com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test ... ``` - Add MUnit dependencies to your `pom.xml` file: Dependencies ```xml ... com.mulesoft.munit munit-runner ${munit.version} mule-plugin test com.mulesoft.munit munit-tools ${munit.version} mule-plugin test ... ``` - Configure the repositories for the MUnit dependencies and plugin: Repositories ```xml mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default ``` Plugin Repositories ```xml mulesoft-release mulesoft release repository default https://repository.mulesoft.org/releases/ false ``` > [!NOTE] MUnit has Surefire support built in. The reports output to `target/surefire-reports`. ### Handle Parent POM Files You can declare the MUnit plugin in a parent `pom.xml` file and every child project under this file can reference this definition. To configure MUnit Maven Plugin in a parent-child POM relationship, include the MUnit plugin declaration in the `` section of your parent `pom.xml` file. In the following example, the `pirate-pom` project declares MUnit Maven Plugin in its plugin management section. This section also defines a global configuration that each child under this parent can reference, override, or ignore. ```xml 4.1.0 org.pirate pirate-pom 1.0-SNAPSHOT pom 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test true false 0 0 0 console html ``` ### Inherit a Parent Plugin To inherit the MUnit plugin in your child `pom.xml` files, reference it in the `` section of each child POM file individually. The following sample references the `pirate-pom` file as its parent. It declares the MUnit plugin in a `` section without specifying its `` because the MUnit plugin configuration is inherited from the `` section in the parent POM file: POM child file sample ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.4 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ``` ### Ignore a Parent Plugin Each child project under a parent `pom.xml` file can ignore the plugin referenced in the parent plugin management section and not implement the plugin configuration declared there. By not declaring the MUnit Plugin in your `` section, you avoid inheriting the plugin declared in **pirate-pom**: Child POM file not inheriting the MUnit Maven Plugin ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.0 2.3.0 ``` ### Override a Parent Plugin When inheriting the plugin from a parent POM file, you can also override the parent configuration. Overriding the plugin configuration from your parent POM file suppresses the original configuration requiring you to declare all necessary configurations again. The following example overrides the console coverage report from its parent POM file, replacing it with the HTML report. Because the values from the other elements in the parent (``, ``, ``, ``) aren’t being referenced, this child file won’t inherit them and the default values are applied: Coverage configuration in parent POM file ```xml true false 0 0 0 console html ``` POM child file overriding coverage report format ```xml com.mulesoft.munit.tools munit-maven-plugin true html ``` ## Set Up Coverage The following configurations only apply when you execute your MUnit tests using the Maven plugin. They don’t apply when running tests from Studio. See [Using Coverage in Maven](https://docs.mulesoft.com/munit/3.6/coverage-maven-concept) for additional information. From MUnit 2.x and later, the coverage report goal is integrated with the Maven reporting section. MUnit generates coverage reports during the Maven `site` lifecycle, during the `coverage-report` goal. The following configurations apply if you execute your MUnit tests using the Maven plugin. They don’t apply when running tests from Anypoint Code Builder or Anypoint Studio. MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ### Set up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level isn’t reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage isn’t defined, it defaults to -1, which sets no requirements for said level so the build doesn’t fail due to low coverage.
If you define coverage levels but set the property `failBuild` to `false`, and then the levels aren’t reached, a warning shows up in the MUnit Coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level isn’t met, and where it happens.
### Ignore a Flow or a File You can also ignore a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow isn’t tested or if the flow doesn’t reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## Dynamic Ports MUnit 2.2 and later introduce the `dynamic-port` global element, that allows you to define dynamic ports at the MUnit suite level. Using this element instead of the plugin configuration described as follows allows you to set the dynamic port both from Maven and Studio. See [Dynamic Ports](https://docs.mulesoft.com/munit/3.6/dynamic-ports) to learn how to configure this element. When testing a Mule application in a continuous integration (CI) environment, you might encounter the following scenario: Your application tries to open a specific port. The port is already in use. The application fails with a port binding exception. The MUnit Maven Plugin comes with a built-in feature to make your application use a free port. MUnit Dynamic Ports instructs the MUnit Maven Plugin to look for unbound ports and reserve them before running the tests over the Mule application. Each port selected is placed in a system property under the name indicated in the configuration. The application can get the port number through the use of placeholders afterward. The plugin selects the ports from the range: `[40000,50000]` > [!CAUTION] Dynamic Ports feature is only available as part of the MUnit Maven Plugin. This feature > does not work when running tests in Anypoint Studio. ### Enable Dynamic Ports To enable the feature, you must add the following code to the `configuration` section of the MUnit Maven Plugin: Dynamic Ports Configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ... a.dynamic.port ... ``` If you have the `${http.port}` placeholder in your application, the configuration looks something like: Example ```xml http.port ``` ### Prepare Your Application A placeholder must parameterize the part of the application trying to make use of a port. For example, to have your Mule application listening for HTTP traffic, provide the following configuration: HTTP Application ```xml ``` The previous application always listens in port `8081`. To make it dynamic, change it to: HTTP Application with dynamic port ```xml (1) ```
1Notice the placeholder ${http.port}.
With the application coded in this way and the configuration of Dynamic Ports in place, your application starts each run listening on a different port. ## Enable Surefire Reports MUnit has built-in support for Surefire. You mustn’t do additional configurations, and you can disable it if not needed: Disable Surefire reports ```none false ``` You can find the reports under `${project.build.directory}/surefire-reports`. By default, it’s set to `true`. ## Enable Sonar Reports MUnit has built-in support for SonarQube, with a default setting of `true` for `enableSonarReports`. No other configuration is required. You can find the reports under `${project.build.directory}/sonar-reports`. You can disable SONAR reports if not needed: Disable Sonar reports ```none false ``` You can find the reports under `${project.build.directory}/sonar-reports`. By default, it’s set to `true`. ## Run Tests Using the Plugin ### Run MUnit Tests for a Mule Application Run MUnit tests in a Single Resource Mule project. ```none mvn clean test ``` ### Run a Specific MUnit Test Suite By using the property `munit.test`, you can instruct the MUnit Maven plugin to run certain tests that belong to a specific test suite: ```maven mvn clean test -Dmunit.test= ``` This path is relative to `src/test/munit`. The property `munit.test` accepts regular expressions. The expression is applied to the name of the MUnit Test Suite file. The regular expression language is the Java implementation. For example: ```console mvn clean test -Dmunit.test=.*my-test.* ``` You can leverage this feature by adding naming conventions to your MUnit Test suites. ### Run Specific MUnit Tests In the same way that you instruct MUnit to run one test suite, you can also configure it to run a specific test in that test suite. You must use the property `munit.test` with the addition of the special character `#` to append the test name: ```console mvn clean test -Dmunit.test=# ``` It also accepts regular expressions. The expression is applied to the attribute `name` of the MUnit Test. For example: ```console mvn clean test -Dmunit.test=.*my-test.*#.*test-scenario-1.* ``` MUnit flags the tests in the MUnit Test Suite that don’t match the regular expression as **ignored**. You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... example-MunitTest-suite.xml ... ``` ### Run Tests Using a Specific Tag You can run the tests that you grouped under one specific tag: ```console mvn clean test -Dmunit.tags= ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleMunitTag ... ``` You can specify more than one tag by separating them with a comma. ### Skip All Tests MUnit leverages the same mechanism as Maven. To skip tests, you must use the `skipTests` parameter: Skip Tests example ```console mvn clean package -DskipTests ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` ### Skip Tests After One Suite Fails MUnit allows you to skip the rest of the tests if one test suite fails: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` If not specified, it’s default value is `false`. ## Specify the Runtime Product You can specify the type of runtime in which the applications you test run. Accepted values are: - `MULE` for the Mule Kernel (formerly called Mule Community Edition) - `MULE_EE` for the Mule Enterprise Edition ```xml com.mulesoft.munit.tools munit-maven-plugin ... MULE ... ``` ### Specify the Runtime Product Version You can specify the runtime version in which the applications you test run. ```xml com.mulesoft.munit.tools munit-maven-plugin ... 4.2.2 ... ``` ## Specify the JVM You can specify the JVM (or the Java executable) in which the applications you test run. You must populate the `munit.jvm` parameter with the path to the executable: Specify the JVM ```console mvn clean package -Dmunit.jvm=/path/to/jdk/bin/java ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... /path/to/jdk/bin/java ... ``` ### Additional Argument Lines You can pass additional argument lines to the JVM. Specify each argument in a separate `argLine`: Argument lines ```xml com.mulesoft.munit.tools munit-maven-plugin ... -XX:MaxPermSize=512m -Xmx1024m ... ``` ### Environment Variables To set additional environment variables during the test run, you can specify them with the respective key and value: Additional Environment Variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleValue val2 ... ``` As shown in the previous example, you can use environment variables to replace placeholders such as `${MY_ENV}`. ### System Properties Variables If you must define specific system variables to run your MUnit test successfully: Setting system property variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... my.property.value ... ``` Depending on the execution context, the system property values can vary. When referencing these properties, you must override their value to enforce test reproducibility. You can do so by using the ­`-D` argument when running MUnit with Maven. Variables passed with the `-D` argument take full priority over any other property. For example: ```none -Dmy.property.key=my.property.another.value ``` ## Redirect Test Output to File When running several tests, the build output can get very complex to read. MUnit allows you to redirect the output of each test suite to a file. This way, the test results remain in the build output and you can check the respective file to check the standard output of each test suite. You can find these files in the `testOutputDirectory` folder following the naming convention: `munit.${suiteName}-output.txt`, where `suiteName` represents the name of the XML file relative to the MUnit test folder. The test output that doesn’t belong to a particular suite isn’t printed to keep the build output clean. You can enable it by running Maven in debug mode. To redirect the output of each test suite to a file: Redirect test output to a file ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` By default, it’s set to `false`. ### Test Output Directory If you want to choose the location where the test creates the output files, the path specified can be absolute or written as a Maven placeholder: Test output directory with absolute path ```xml com.mulesoft.munit.tools munit-maven-plugin ... /my/absolute/path ... ``` Test output directory using Maven placeholders ```xml ${project.build.directory}/my/output/folder ``` By default, the files are created in `${project.build.directory}/munit-reports/output/`. ## MUnit Maven Plugin Configuration Reference The MUnit Maven Plugin offers a set of optional configurable parameters.
Table 1. Maven Plugin Parameters
NameTypeDescription

argLines

List

Additional JVM argument lines to set on the test run.

coverage

Configuration

Coverage configuration to set on the test run.

dynamicPorts

List

Dynamic ports to set on the test run.

enableSurefireReports

boolean

Set value to true to generate MUnit test results in the Surefire format.
Its default value is true.

munitTest

String

Name of the MUnit tests to run.

munitTags

String

Name of the MUnit tags. Tests tagged with these names run.

skipMunitTests

boolean

Setting this parameter to true skips all MUnit tests.
Its default value is false.

skipAfterFailure

boolean

Skip all tests if one fails.
Its default value is false.

munitTestsDirectory

File

Directory where the MUnit tests reside.
Its default value is ${project.build.directory}/test-mule/munit.

runtimeVersion

String

Version of the Mule runtime
When you run your tests from Maven, this value comes from the minMuleVersion parameter in the mule-artifact.json file.
To modify the Mule runtime version used to run your MUnit tests, see Runtime Patching.

runtimeProduct

String

Type of runtime. Expected values are:

  • MULE for the Mule Kernel (formerly called Mule Community Edition)

  • MULE_EE for the Mule Enterprise Edition

By default, this value comes from the requiredProduct parameter in the mule-artifact.json file.

jvm

String

Option to specify the JVM (or path to the Java executable) to use.

By default, the JVM is the same VM as the one used to run Maven.

environmentVariables

Map

Additional environment variables to set on the test run.

redirectTestOutputToFile

boolean

Setting this value to true redirects the MUnit tests standard output to a file.
Its default value is false.

systemPropertyVariables

Map

System properties set on the test run.

testOutputDirectory

File

Directory where the test outputs are written.
Its default value is ${project.build.directory}/munit-reports/output/.

--- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Maven Plugin runs MUnit tests as part of a continuous integration environment by integrating with the Maven build lifecycle. These configurations apply only when running MUnit through Maven, not from Anypoint Studio or Anypoint Code Builder. ## Set Up MUnit Maven Plugin You must have the `` property in your pom.xml to set up MUnit Maven Plugin. - Enable MUnit Maven Plugin in your `pom.xml` file: MUnit Maven Plugin ```xml ... com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test ... ``` - Add MUnit dependencies to your `pom.xml` file: Dependencies ```xml ... com.mulesoft.munit munit-runner ${munit.version} mule-plugin test com.mulesoft.munit munit-tools ${munit.version} mule-plugin test ... ``` - Configure the repositories for the MUnit dependencies and plugin: Repositories ```xml mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default ``` Plugin Repositories ```xml mulesoft-release mulesoft release repository default https://repository.mulesoft.org/releases/ false ``` Most applications require Mule runtime engine Enterprise Edition to run MUnit tests. Maven downloads the Enterprise runtime from a plugin repository. 1. Configure your Enterprise repository credentials. See [Configure MuleSoft Enterprise Repository](https://docs.mulesoft.com/mule-runtime/latest/maven-reference#configure-mulesoft-enterprise-repository). 2. Add the Enterprise repository as a plugin repository in the `pluginRepositories` section of your `pom.xml` file, together with the MuleSoft releases plugin repository. Set `id` to the same value as the `` in the `` entry of your `settings.xml` file: Enterprise Plugin Repository ```xml ... MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ``` > [!NOTE] MUnit has Surefire support built in. The reports output to `target/surefire-reports`. ### Handle Parent POM Files You can declare the MUnit plugin in a parent `pom.xml` file and every child project under this file can reference this definition. To configure MUnit Maven Plugin in a parent-child POM relationship, include the MUnit plugin declaration in the `` section of your parent `pom.xml` file. In the following example, the `pirate-pom` project declares MUnit Maven Plugin in its plugin management section. This section also defines a global configuration that each child under this parent can reference, override, or ignore. ```xml 4.1.0 org.pirate pirate-pom 1.0-SNAPSHOT pom 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test true false 0 0 0 console html ``` ### Inherit a Parent Plugin To inherit the MUnit plugin in your child `pom.xml` files, reference it in the `` section of each child POM file individually. The following sample references the `pirate-pom` file as its parent. It declares the MUnit plugin in a `` section without specifying its `` because the MUnit plugin configuration is inherited from the `` section in the parent POM file: POM child file sample ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.4 2.3.0 com.mulesoft.munit.tools munit-maven-plugin ``` ### Ignore a Parent Plugin Each child project under a parent `pom.xml` file can ignore the plugin referenced in the parent plugin management section and not implement the plugin configuration declared there. By not declaring the MUnit Plugin in your `` section, you avoid inheriting the plugin declared in **pirate-pom**: Child POM file not inheriting the MUnit Maven Plugin ```xml org.pirate pirate-pom 1.0-SNAPSHOT 4.0.0 com.mycompany ninja 1.0.0-SNAPSHOT mule Mule ninja Application UTF-8 UTF-8 4.1.0 2.3.0 ``` ### Override a Parent Plugin When inheriting the plugin from a parent POM file, you can also override the parent configuration. Overriding the plugin configuration from your parent POM file suppresses the original configuration requiring you to declare all necessary configurations again. The following example overrides the console coverage report from its parent POM file, replacing it with the HTML report. Because the values from the other elements in the parent (``, ``, ``, ``) aren’t being referenced, this child file won’t inherit them and the default values are applied: Coverage configuration in parent POM file ```xml true false 0 0 0 console html ``` POM child file overriding coverage report format ```xml com.mulesoft.munit.tools munit-maven-plugin true html ``` ## Set Up Coverage The following configurations only apply when you execute your MUnit tests using the Maven plugin. They don’t apply when running tests from Studio. See [Using Coverage in Maven](https://docs.mulesoft.com/munit/latest/coverage-maven-concept) for additional information. Configure MUnit coverage reports in Maven by adding the munit-maven-plugin to your pom.xml and enabling the coverage-report goal. Coverage reports are generated during the Maven site lifecycle and are not available when running tests from Anypoint Code Builder or Anypoint Studio. MUnit Coverage - Sample Maven configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test coverage-report true false 75 50 50 console html ``` ### Set Up a Minimum Coverage Level One of the features of MUnit Coverage is to fail the build if a certain coverage level isn’t reached. MUnit Coverage handles three different levels: - **Application**: The overall coverage of all your application. - **Resource**: The coverage level of each Mule configuration file. - **Flow**: The coverage of event processors in each flow. To define the required coverage levels: MUnit Coverage - Require Coverage ```xml true true 75 (1) 50 50 ```
1Each value represents a percentage.
If a percentage isn’t defined, it defaults to -1, which sets no requirements for said level so the build doesn’t fail due to low coverage.
If you define coverage levels but set the property `failBuild` to `false`, and then the levels aren’t reached, a warning shows up in the MUnit Coverage summary: ```console =============================================================================== MUnit Coverage Summary =============================================================================== * Resources: 2 - Flows: 3 - Processors: 4 * Application Coverage: 75.00% ----------------------------- WARNING -------------------------------------- * Flow: file2.xml -> file2Flow1 coverage is below defined limit. Required: 50.0% - Current: 00.00% (1) ==================================================================================== ```
1Warning detailing which coverage level isn’t met, and where it happens.
### Ignore a Flow or a File You can also ignore a flow or a file. This way, the ignored resource: - Does not count as coverage data. - Does not affect the overall number of message processors. - Does not cause a build to fail if the flow isn’t tested or if the flow doesn’t reach coverage metrics. To ignore flows and files: MUnit Coverage - Ignore flows and files ```xml true true 100 100 100 flow-1 flow-2 ... flow-n mule-config-1.xml mule-config-2.xml ... mule-config-n.xml ``` ## Dynamic Ports MUnit 2.2 and later introduce the `dynamic-port` global element, that allows you to define dynamic ports at the MUnit suite level. Using this element instead of the plugin configuration described as follows allows you to set the dynamic port both from Maven and Studio. See [Dynamic Ports](https://docs.mulesoft.com/munit/latest/dynamic-ports) to learn how to configure this element. When testing a Mule application in a continuous integration (CI) environment, you might encounter the following scenario: Your application tries to open a specific port. The port is already in use. The application fails with a port binding exception. The MUnit Maven Plugin comes with a built-in feature to make your application use a free port. MUnit Dynamic Ports instructs the MUnit Maven Plugin to look for unbound ports and reserve them before running the tests over the Mule application. Each port selected is placed in a system property under the name indicated in the configuration. The application can get the port number through the use of placeholders afterward. The plugin selects the ports from the range: `[40000,50000]` > [!CAUTION] Dynamic Ports feature is only available as part of the MUnit Maven Plugin. This feature > does not work when running tests in Anypoint Studio. ### Enable Dynamic Ports To enable the feature, you must add the following code to the `configuration` section of the MUnit Maven Plugin: Dynamic Ports Configuration ```xml com.mulesoft.munit.tools munit-maven-plugin ... a.dynamic.port ... ``` If you have the `${http.port}` placeholder in your application, the configuration looks something like: Example ```xml http.port ``` ### Prepare Your Application A placeholder must parameterize the part of the application trying to make use of a port. For example, to have your Mule application listening for HTTP traffic, provide the following configuration: HTTP Application ```xml ``` The previous application always listens in port `8081`. To make it dynamic, change it to: HTTP Application with dynamic port ```xml (1) ```
1Notice the placeholder ${http.port}.
With the application coded in this way and the configuration of Dynamic Ports in place, your application starts each run listening on a different port. ## Enable Surefire Reports MUnit has built-in support for Surefire. You mustn’t do additional configurations, and you can disable it if not needed: Disable Surefire reports ```none false ``` You can find the reports under `${project.build.directory}/surefire-reports`. By default, it’s set to `true`. ## Enable Sonar Reports MUnit has built-in support for SonarQube, with a default setting of `true` for `enableSonarReports`. No other configuration is required. You can find the reports under `${project.build.directory}/sonar-reports`. You can disable SONAR reports if not needed: Disable Sonar reports ```none false ``` You can find the reports under `${project.build.directory}/sonar-reports`. By default, it’s set to `true`. ## Run Tests Using the Plugin ### Run MUnit Tests for a Mule Application Run MUnit tests in a Single Resource Mule project. ```none mvn clean test ``` ### Run a Specific MUnit Test Suite By using the property `munit.test`, you can instruct the MUnit Maven plugin to run certain tests that belong to a specific test suite: ```maven mvn clean test -Dmunit.test= ``` This path is relative to `src/test/munit`. The property `munit.test` accepts regular expressions. The expression is applied to the name of the MUnit Test Suite file. The regular expression language is the Java implementation. For example: ```console mvn clean test -Dmunit.test=.*my-test.* ``` You can leverage this feature by adding naming conventions to your MUnit Test suites. ### Run Specific MUnit Tests In the same way that you instruct MUnit to run one test suite, you can also configure it to run a specific test in that test suite. You must use the property `munit.test` with the addition of the special character `#` to append the test name: ```console mvn clean test -Dmunit.test=# ``` It also accepts regular expressions. The expression is applied to the attribute `name` of the MUnit Test. For example: ```console mvn clean test -Dmunit.test=.*my-test.*#.*test-scenario-1.* ``` MUnit flags the tests in the MUnit Test Suite that don’t match the regular expression as **ignored**. You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... example-MunitTest-suite.xml ... ``` ### Run Tests Using a Specific Tag You can run the tests that you grouped under one specific tag: ```console mvn clean test -Dmunit.tags= ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleMunitTag ... ``` You can specify more than one tag by separating them with a comma. ### Fail When No Tests Run By default, MUnit fails the Maven build if it can’t find any MUnit test suites or if no tests run from the discovered suites. This behavior helps ensure that applications in a CI pipeline include and run MUnit tests. To allow a build to succeed when no MUnit tests run, set `munitFailIfNoTests` to `false` in the MUnit Maven Plugin configuration: Allow builds with no MUnit tests ```xml com.mulesoft.munit.tools munit-maven-plugin ... false ... ``` You can also disable this behavior from the command line: ```console mvn clean test -Dmunit.failIfNoTests=false ``` Use this setting only when no MUnit tests are expected to run. Maven’s `skipTests` parameter and MUnit’s `skipMunitTests` parameter skip MUnit test execution and don’t run this validation. ### Skip All Tests MUnit leverages the same mechanism as Maven. To skip tests, you must use the `skipTests` parameter: Skip Tests example ```console mvn clean package -DskipTests ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` ### Skip Tests After One Suite Fails MUnit allows you to skip the rest of the tests if one test suite fails: ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` If not specified, it’s default value is `false`. ## Specify the Runtime Product You can specify the type of runtime in which the applications you test run. Accepted values are: - `MULE` for the Mule Kernel (formerly called Mule Community Edition) - `MULE_EE` for the Mule Enterprise Edition ```xml com.mulesoft.munit.tools munit-maven-plugin ... MULE ... ``` ### Specify the Runtime Product Version You can specify the runtime version in which the applications you test run. ```xml com.mulesoft.munit.tools munit-maven-plugin ... 4.2.2 ... ``` The `munit.runtimeversion` property replaces the deprecated `runtimeVersion` property. The `runtimeVersion` property remains supported. If you use `runtimeVersion`, MUnit displays a warning message that indicates the property is deprecated and that you must migrate to `munit.runtimeversion`. ## Specify the JVM You can specify the JVM (or the Java executable) in which the applications you test run. You must populate the `munit.jvm` parameter with the path to the executable: Specify the JVM ```console mvn clean package -Dmunit.jvm=/path/to/jdk/bin/java ``` You can also configure this from the `pom.xml` configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ... /path/to/jdk/bin/java ... ``` ### Additional Argument Lines You can pass additional argument lines to the JVM. Specify each argument in a separate `argLine`: Argument lines ```xml com.mulesoft.munit.tools munit-maven-plugin ... -XX:MaxPermSize=512m -Xmx1024m ... ``` ### Environment Variables To set additional environment variables during the test run, you can specify them with the respective key and value: Additional Environment Variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... exampleValue val2 ... ``` As shown in the previous example, you can use environment variables to replace placeholders such as `${MY_ENV}`. ### System Properties Variables If you must define specific system variables to run your MUnit test successfully: Setting system property variables ```xml com.mulesoft.munit.tools munit-maven-plugin ... my.property.value ... ``` Depending on the execution context, the system property values can vary. When referencing these properties, you must override their value to enforce test reproducibility. You can do so by using the ­`-D` argument when running MUnit with Maven. Variables passed with the `-D` argument take full priority over any other property. For example: ```none -Dmy.property.key=my.property.another.value ``` ## Redirect Test Output to File When running several tests, the build output can get very complex to read. MUnit allows you to redirect the output of each test suite to a file. This way, the test results remain in the build output and you can check the respective file to check the standard output of each test suite. You can find these files in the `testOutputDirectory` folder following the naming convention: `munit.${suiteName}-output.txt`, where `suiteName` represents the name of the XML file relative to the MUnit test folder. The test output that doesn’t belong to a particular suite isn’t printed to keep the build output clean. You can enable it by running Maven in debug mode. To redirect the output of each test suite to a file: Redirect test output to a file ```xml com.mulesoft.munit.tools munit-maven-plugin ... true ... ``` By default, it’s set to `false`. ### Test Output Directory If you want to choose the location where the test creates the output files, the path specified can be absolute or written as a Maven placeholder: Test output directory with absolute path ```xml com.mulesoft.munit.tools munit-maven-plugin ... /my/absolute/path ... ``` Test output directory using Maven placeholders ```xml ${project.build.directory}/my/output/folder ``` By default, the files are created in `${project.build.directory}/munit-reports/output/`. ## MUnit Maven Plugin Configuration Reference The MUnit Maven Plugin offers a set of optional configurable parameters.
Table 1. Maven Plugin Parameters
NameTypeDescription

argLines

List

Additional JVM argument lines to set on the test run.

coverage

Configuration

Coverage configuration to set on the test run.

dynamicPorts

List

Dynamic ports to set on the test run.

enableSurefireReports

boolean

Set value to true to generate MUnit test results in the Surefire format.
Its default value is true.

munitTest

String

Name of the MUnit tests to run.

munitTags

String

Name of the MUnit tags. Tests tagged with these names run.

munitFailIfNoTests

boolean

Fails the Maven build if no MUnit test suites are found or no tests run from the discovered suites.
Its default value is true.

skipMunitTests

boolean

Setting this parameter to true skips all MUnit tests.
Its default value is false.

skipAfterFailure

boolean

Skip all tests if one fails.
Its default value is false.

munitTestsDirectory

File

Directory where the MUnit tests reside.
Its default value is ${project.build.directory}/test-mule/munit.

munit.runtimeversion

String

Version of the Mule runtime
When you run your tests from Maven, this value comes from the minMuleVersion parameter in the mule-artifact.json file.
To modify the Mule runtime version used to run your MUnit tests, see Runtime Patching.

runtimeVersion (deprecated)

String

Deprecated alias for munit.runtimeversion.
This property remains supported for backward compatibility.
When you use this property, MUnit displays a warning message and instructs you to migrate to munit.runtimeversion.

runtimeProduct

String

Type of runtime. Expected values are:

  • MULE for the Mule Kernel (formerly called Mule Community Edition)

  • MULE_EE for the Mule Enterprise Edition

By default, this value comes from the requiredProduct parameter in the mule-artifact.json file.

jvm

String

Option to specify the JVM (or path to the Java executable) to use.

By default, the JVM is the same VM as the one used to run Maven.

environmentVariables

Map

Additional environment variables to set on the test run.

redirectTestOutputToFile

boolean

Setting this value to true redirects the MUnit tests standard output to a file.
Its default value is false.

systemPropertyVariables

Map

System properties set on the test run.

testOutputDirectory

File

Directory where the test outputs are written.
Its default value is ${project.build.directory}/munit-reports/output/.

--- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Mock When Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Mock When processor intercepts a specified event processor during a MUnit test and returns a configured response instead of executing the real operation. Use it to isolate the flow under test from external dependencies such as HTTP requests, database calls, or web service operations. For example, you can use the **Mock Event** processor to mock a POST request with a mocked payload: ```xml ``` You can set the **processor** attribute to define the processor to mock and set the **with-attribute** element to define the attribute name and value. In the previous example, you define a POST method. You can also use DataWeave functions and mappings to set the `value` attribute in the **then-return** element. For example, create a **mockPost.dwl** in the **src/test/resources/sample\_data** file: ```none %dw 2.0 output application/json --- { "foo" : "var" } ``` This DataWeave file creates the payload to send in a POST request. You can then use the **readUrl** DataWeave function to read the mapping file: ```xml ``` Finally, you can configure a **then-return** element to define the type of response the mocked processor returns. It can be a payload, a variable, a list of attributes, or an error. You can use either a **then-return** to return a static, constant value, or you can use a **then-call** to invoke a flow for cases where the returned value can change over time, or to have different responses according to certain inputs. > [!NOTE] The mocking of the processors is executed after the initialization of the Mule app, and > some connectors can require credentials or configurations to start the app, even when its > processors are mocked. > [!NOTE] Logger processor and Transform Message processor (DataWeave) cannot be mocked. ## Mock Using Then-Return For example, you can mock a web service consumer such as this one: ```xml ``` By configuring the **mock-when** processor as shown in the following example: ```xml ``` This **mock-when** processor mocks a call to the **OrderTshirt** operation in the WSDL definition. You can also mock specific variables: ```xml ``` ### Mock Errors The **Mock When** processor also enables you to mock errors in your operations. Assume that you have an HTTP requester in your flow with an On-Error scope that catches any connectivity errors and returns a custom payload if the connection fails: ```xml ``` You can assert that every time the HTTP request fails, your application returns your custom payload: ```xml (1) (2) (3) (4) ```
1Mock an HTTP Requester with the configuration of the requester in your flow.
2Configure a then-return element to throw an HTTP:CONNECTIVITY error.
This triggers the On-error scope in your application.
3Execute the flow containing the requester.
4Assert that the returned payload is the one you set in the On-error scope.
You cannot return all known error types of a Mule application. You can return the type of errors defined in the modules the current flow uses. If you try to return an error type that is out of the scope of the flow you’re testing, you get a **MULE:UNKNOWN** error instead of the configured one. ### Parameters If you create a mock error, choose one of the following parameters to provide the trigger for the error in the **Then-return** tab: - **TypeId**: Follows a Mule Error type definition. For example, the HTTP:CONNECTIVITY error explained before. - **Cause**: Expects the instance of the exception with a message for the error. For example, using Java, write the expression: ```java #[java!java::lang::Exception::new("Exception Message")] ``` ## Mock Using Then-Call To dynamically mock a variable, use **then-call** as follows: ```xml (1) (2) (3) ```
1This is the processor you mock.
2The mock calls this flow. The mock sets a variable that changes depending on the incoming event.
3Configure the mock to call the desired flow.
## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/latest/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/latest/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/latest/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/latest/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/latest/verify-event-processor) --- product: MUnit version: 3.6 --- # MUnit Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Build automated tests for your integrations and APIs with MUnit. MUnit is a Mule application testing framework that provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. MUnit version 3.0 and later works with all Mule versions since 4.3. With MUnit you can: - Create your test by writing Mule code - Mock processors - Spy any processor - Verify processor calls - Enable or ignore particular tests - Tag tests - Generate coverage reports You can create, design, and run MUnit tests in Anypoint Studio and Anypoint Code Builder. MUnit has two main sub modules: - MUnit - MUnit Tools Each module has its dependency: ## MUnit Dependencies ```xml com.mulesoft.munit munit-runner LATEST_VERSION (1) mule-plugin test ```
1Check the MUnit Release Notes to get the LATEST_VERSION.
## MUnit Tools Dependencies ```xml com.mulesoft.munit munit-tools LATEST_VERSION (1) mule-plugin test ```
1Check the MUnit Release Notes to get the LATEST_VERSION.
## See Also - [MUnit Test Structure Fundamentals](https://docs.mulesoft.com/munit/3.6/munit-test-concept) - [MUnit Cookbook](https://docs.mulesoft.com/munit/3.6/munit-cookbook) - [Testing Projects with MUnit in Studio](https://docs.mulesoft.com/studio/test-with-munit-in-studio) - [Testing Projects with MUnit in Anypoint Code Builder](https://docs.mulesoft.com/anypoint-code-builder/int-test-munit) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Build automated tests for your integrations and APIs with MUnit. MUnit is a Mule application testing framework that provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. MUnit version 3.0 and later works with all Mule versions since 4.3. With MUnit you can: - Create your test by writing Mule code - Mock processors - Spy any processor - Verify processor calls - Enable or ignore particular tests - Tag tests - Generate coverage reports You can create, design, and run MUnit tests in Anypoint Studio and Anypoint Code Builder. MUnit has two main sub modules: - MUnit - MUnit Tools Each module has its dependency: ## MUnit Dependencies ```xml com.mulesoft.munit munit-runner LATEST_VERSION (1) mule-plugin test ```
1Check the MUnit Release Notes to get the LATEST_VERSION.
## MUnit Tools Dependencies ```xml com.mulesoft.munit munit-tools LATEST_VERSION (1) mule-plugin test ```
1Check the MUnit Release Notes to get the LATEST_VERSION.
## See Also - [MUnit Test Structure Fundamentals](https://docs.mulesoft.com/munit/latest/munit-test-concept) - [MUnit Cookbook](https://docs.mulesoft.com/munit/latest/munit-cookbook) - [Testing Projects with MUnit in Studio](https://docs.mulesoft.com/studio/test-with-munit-in-studio) - [Testing Projects with MUnit in Anypoint Code Builder](https://docs.mulesoft.com/anypoint-code-builder/int-test-munit) --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Parameterized Test Suites > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit parameterized test suites run the same tests multiple times with different input values, reducing duplication in your test code. Define parameterizations inline in the test suite configuration or load them from a YAML file in your project’s test resources. The test suite parameterization is defined at a configuration level as follows: ```xml ``` The Test Suite runs twice: Firstly, with the `firstParameterization` parameters. Secondly, with the `secondParameterization` parameters. For example, if you have a test that sets a payload for a flow and expects a result: Parameterization Example ```xml ``` ## Access Parameters from DataWeave Use the DataWeave `p()` function to access parameter values inside DataWeave expressions, concatenate parameter values with other strings, perform comparisons or calculations, and use parameters in complex DataWeave transformations. Using the parameterization from the first example, the following test uses `p()` to build a greeting message and validate that the payload contains the expected name: Accessing Parameters with the p() Function ```xml ``` ## Parameterization from File To use the same parameterized values on different test suites, you must save your parameterizations values in a YAML file in the `/test/resources` directory of your Mule application project: parameterizations.yaml Example ```yaml firstParameterization: name: "Robert" lastname: "Plant" secondParameterization: name: "Jimmy" lastname: "Page" ``` And reference it from your test suite configuration: Example Parameterization From File ```xml ``` You can combine both methods to add parameterized values to a test suite: Example Parameterization From File and in the Test Suite Configuration ```xml ``` If you define the same parameterization key in a YAML file and your test suite configuration, the test suite parameterization overrides your YAML parameterization. ## See Also - [DataWeave Function: p(propertyName: String): String](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing, queue --- # MUnit Queue Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Queue event processors manage temporary in-memory queues during MUnit test runs, letting you enqueue and dequeue values to test asynchronous flows. All queues are cleared automatically when each test ends. ## Queue Adds the value to the queue. If not specified, the value is taken from the `payload`. ```xml #[1] ``` You can specify the queue’s name to which the value should be added. If not specified, the default queue will be used. ```xml #[1] ``` ## Dequeue Removes the last element of the queue, if the queue is empty, it waits until an element is queued. ```xml ``` You can specify a timeout when waiting for an element to be queued: ```xml ``` Like the queue operation, you can specify the queue’s name from which to dequeue. If not specified, the default queue will be used. ```xml ``` ## Queue Size Function that obtains the queue size. ```xml ``` Like the other operations, you can specify the queue from which to the get the size. If not specified, the default queue will be used. ```xml ``` --- product: MUnit version: 2.3 keywords: munit, testing, unit testing, release notes --- # MUnit Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt These release notes are provided for MUnit. ## MUnit 3.x - [MUnit 3.7.5 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.5-release-notes) - [MUnit 3.7.4 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.4-release-notes) - [MUnit 3.7.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.3-release-notes) - [MUnit 3.7.2 Release Notes (Deprecated)](https://docs.mulesoft.com/release-notes/munit/munit-3.7.2-release-notes) - [MUnit 3.7.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.1-release-notes) - [MUnit 3.7.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.0-release-notes) - [MUnit 3.6.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.3-release-notes) - [MUnit 3.6.2 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.2-release-notes) - [MUnit 3.6.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.1-release-notes) - [MUnit 3.6.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.0-release-notes) ## MUnit 2.x - [MUnit 2.3.18 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-2.3.18-release-notes) > [!NOTE] For previous versions of MUnit 1.x, 2.x, and 3.x that reached > [end of life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf), > see the > [MUnit Release Notes Archive](https://archive.docs.mulesoft.com/release-notes/munit/munit-archive). ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing, release notes --- # MUnit Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt These release notes are provided for MUnit. ## MUnit 3.x - [MUnit 3.7.5 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.5-release-notes) - [MUnit 3.7.4 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.4-release-notes) - [MUnit 3.7.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.3-release-notes) - [MUnit 3.7.2 Release Notes (Deprecated)](https://docs.mulesoft.com/release-notes/munit/munit-3.7.2-release-notes) - [MUnit 3.7.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.1-release-notes) - [MUnit 3.7.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.0-release-notes) - [MUnit 3.6.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.3-release-notes) - [MUnit 3.6.2 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.2-release-notes) - [MUnit 3.6.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.1-release-notes) - [MUnit 3.6.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.0-release-notes) ## MUnit 2.x - [MUnit 2.3.18 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-2.3.18-release-notes) > [!NOTE] For previous versions of MUnit 1.x, 2.x, and 3.x that reached > [end of life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf), > see the > [MUnit Release Notes Archive](https://archive.docs.mulesoft.com/release-notes/munit/munit-archive). ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing, release notes --- # MUnit Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt These release notes are provided for MUnit. ## MUnit 3.x - [MUnit 3.7.5 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.5-release-notes) - [MUnit 3.7.4 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.4-release-notes) - [MUnit 3.7.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.3-release-notes) - [MUnit 3.7.2 Release Notes (Deprecated)](https://docs.mulesoft.com/release-notes/munit/munit-3.7.2-release-notes) - [MUnit 3.7.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.1-release-notes) - [MUnit 3.7.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.7.0-release-notes) - [MUnit 3.6.3 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.3-release-notes) - [MUnit 3.6.2 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.2-release-notes) - [MUnit 3.6.1 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.1-release-notes) - [MUnit 3.6.0 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-3.6.0-release-notes) ## MUnit 2.x - [MUnit 2.3.18 Release Notes](https://docs.mulesoft.com/release-notes/munit/munit-2.3.18-release-notes) > [!NOTE] For previous versions of MUnit 1.x, 2.x, and 3.x that reached > [end of life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf), > see the > [MUnit Release Notes Archive](https://archive.docs.mulesoft.com/release-notes/munit/munit-archive). ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Resource Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit resource matchers are utility functions that read test resource files and create Mule messages during a MUnit test. Use them to load file contents as streams, strings, or byte arrays, and to inspect queue sizes in your test validations. ## getResourceAsStream(String) Returns the resource from the path String as a stream. Example ```xml ``` ## getResourceAsReusableStream(String) Returns the resource from the path String as a reusable stream. Example ```xml ``` ## getResourceAsString(path:String,encoding:String) Returns the resource from the path String as a String, where the second parameter (encoding) is optional. Example ```xml ``` You can also specify the encoding: Example ```xml ``` ## getResourceAsByteArray(String) Returns the resource from the path String as a byte array. Example ```xml ``` ## queueSize(String) Returns the size of the queue specified inside `#[MunitTools::queueSize()]`. For example, to assert the size of a queue named `QUEUE_SIZE`: Example ```xml #['EXAMPLE'] ``` ## createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) Creates a Mule message with the specified attributes. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/latest/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/latest/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference) --- product: MUnit version: 3.7 is-latest-version: true keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # MUnit Run Custom Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Run Custom event processor runs a custom Java assertion class against a Mule event during a MUnit test. Use it when built-in matchers are not sufficient and you need to implement custom validation logic in Java. To add the **Run Custom processor** to your project, add the following dependency to your `pom.xml` file: ```xml com.mulesoft.munit munit-assert ${munit.version} test ``` You also have to add your custom assertion class to the `mule-artifact.json` file as an exported resource. For example, you can define the following assertion in Java: ```java package org.mule.custom; import org.mule.munit.assertion.api.MunitAssertion; import org.mule.munit.assertion.api.TypedValue; public class CustomAssertion implements MunitAssertion { @Override public void execute(TypedValue expression, Object params) throws AssertionError { (1) if (!"Hello World".equals(expression.getValue())) { (2) throw new AssertionError("Error the payload is incorrect"); } } } ```
1Implement the only method in the interface public void execute(TypedValue expression, Object params) throws AssertionError.
2Run your custom logic, which in this case validates that the message payload is Hello World.
The `CustomAssertion` class must be located in the scr/test/java directory. And use the **Run Custom Event Processor** to run it: ```xml ```
1The assertion field needs to have the canonical class name of your custom assertion and the class needs to be exported.
To export it when packaging your application, add the `org.mule.custom` package to your `mule-artifact.json` ```json { "name": "mule-application", "minMuleVersion": "4.2.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.custom"] } } } ``` > [!NOTE] You only need to configure the package name in the `exportedPackages` collection. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [Assert That Event Processor](https://docs.mulesoft.com/munit/latest/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/latest/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/latest/verify-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/latest/fail-event-processor) --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Set Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Set Event processor defines the initial Mule event, including payload, attributes, and variables that a MUnit test sends to the flow under test. Use it at the beginning of an MUnit test to set up the input conditions for your flow. The example below shows how to define a simple payload of a Mule Message: ```xml ``` The set-event has the cloneOriginalEvent property. If set to true, it clones the event produced by your code. By default, the value of this property is false. The payload element in the Set Event processor has the following attributes:
Attribute NameDescription

value

Defines the value of the payload’s message.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can also use the Set Event processor to define message attributes and event variables: ```xml ``` All the properties have the same set of attributes:
Table 1. Property Message Processor’s Attributes
Attribute NameDescription

key

The key of the property being set.

value

The content of the property.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can define as many properties per each scope as you need for your test. > [!WARNING] If you define two properties in the same scope with the _same_ key, be aware that one > would end up overwriting the other. ## See Also - [Testing and Mocking Errors](https://docs.mulesoft.com/munit/latest/test-mock-errors-cookbook) - [Fail Event Processor](https://docs.mulesoft.com/munit/latest/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/latest/run-custom-event-processor) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Sleep Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Sleep processor pauses a MUnit test for a specified duration, simulating processing delays in the flow under test. Use it to test time-dependent behavior or introduce controlled waits between test steps. ```xml ``` `time` Numerical value for the unit of time that your test waits before going to sleep. `timeUnit` The unit in which the `time` value is measured. Possible values are: - `MILLISECONDS` (default) - `MICROSECONDS` - `MINUTES` - `NANOSECONDS` - `SECONDS` - `HOURS` --- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Spy Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Spy event processor observes a specified event processor during a MUnit test, running assertions or verifications before and after the processor executes without modifying the original Mule event. Use it to validate the state of the event at specific points in a flow. Assume that you have this configuration: ```xml ``` You can configure the spy processor to spy on any Http Request and assert that the payload is null before reaching the component, and not null after it’s been processed: ```xml ``` Or even to spy on any Http Request, whose path is '/my/api'. ```xml ``` As shown above, this processor enables you to define actions for before and after calling the spied processor. However, keep in mind that the spy processor does not modify the original Mule Event. If you set variables, attributes, or modify the payload inside a Spy, these changes won’t persist outside the processor. Overall, you should use the Spy processor to verify or assert. ## See Also - [MUnit Event Processors](https://docs.mulesoft.com/munit/latest/event-processors) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Storage Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Storage event processors manage temporary key-value storage during a MUnit test, letting you store, retrieve, and remove data across test steps. All stored data is cleared automatically when each test ends. ## Store Operation Stores the given data associated with the given key. If `value` not set, it defaults to the `payload`. ```xml #[person : { name: 'John', lastName: 'Smith' }] ``` ## Retrieve Operation Retrieves the data associated with the given key ```xml ``` ## Remove Operation Removes and returns the data associated with the given key ```xml ``` ## Clear Stored Data Operation Clears all stored data ```xml ``` --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit String Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit String matchers are matcher functions for asserting conditions on String expressions during a MUnit test. Use them with the Assert That processor to check for substrings, prefixes, suffixes, empty values, and case-insensitive equality. ## containsString(String) Checks that the expression contains the specified String. Example ```xml ``` ## startsWith(String) Checks that the expression starts with the specified String. Example ```xml ``` ## endsWith(String) Checks that the expression ends with the specified String. Example ```xml ``` ## isEmptyString() Checks that the expression has zero length. Example ```xml ``` ## isEmptyOrNullString() Checks that the expression is null, or has zero length. Example ```xml ``` ## equalToIgnoringCase(String) Checks that the expression is equal to the specified String, ignoring case. Example ```xml ``` ## equalToIgnoringWhiteSpace(String) Checks that the expression is equal to the string disregarding leading and trailing white spaces, and compression all inner white spaces to a single space. Example ```xml ``` ## stringContainsInOrder(Array) Checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/latest/core-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/latest/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/latest/iterable-map-matchers-reference) --- product: MUnit version: 2.3 --- # MUnit Support for Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit allows you to test applications that run referencing a Mule Domain. MUnit support for domain based applications is designed to require the minimum change of code from your end to implement it. However if your Mule Application depends on a Mule Domain, there are a few considerations to take into account: - When working in Anypoint Studio, your Mule Domain must always be part of your workspace. - Your Folder must have the same name as your artifact. Regardless if it’s a Mule application or a Mule domain if, the folder in your workspace containing your Mule project must have the same name as the artifact ID defined in your pom file. For example, if your mule project’s artifact Id is: ```xml mule-project ``` Then, the folder in your Studio workspace must be named `mule-project`. This is case sensitive. If your folder is named `Mule-Project`, MUnit won’t recognize your project. - Your resources need to be installed in an M2 repository. You need to handle domains and mule apps as regular dependencies. Setting them as an artifact requires for them to be installed in an .M2 repository. - Your resources need to be in your test suite pom file. If your Mule domain project looks like this: ```xml 4.0.0 org.mule.app domain-project mule-domain 1.0.0-SNAPSHOT Domain domain-project Project ``` Then your dependency in your Mule application should look like this: ```xml org.mule.app domain-project 1.0.0-SNAPSHOT mule-domain provided ``` > [!TIP] Remember to keep consistency with `` artifact in your repository and in your > test suite’s pom file ## See Also - [Domain Support (Anypoint Studio)](https://docs.mulesoft.com/studio/domain-support-concept) --- product: MUnit version: 3.6 --- # MUnit Support for Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit allows you to test applications that run referencing a Mule Domain. MUnit support for domain based applications is designed to require the minimum change of code from your end to implement it. However if your Mule Application depends on a Mule Domain, there are a few considerations to take into account: - When working in Anypoint Studio, your Mule Domain must always be part of your workspace. - Your Folder must have the same name as your artifact. Regardless if it’s a Mule application or a Mule domain if, the folder in your workspace containing your Mule project must have the same name as the artifact ID defined in your pom file. For example, if your mule project’s artifact Id is: ```xml mule-project ``` Then, the folder in your Studio workspace must be named `mule-project`. This is case sensitive. If your folder is named `Mule-Project`, MUnit won’t recognize your project. - Your resources need to be installed in an M2 repository. You need to handle domains and mule apps as regular dependencies. Setting them as an artifact requires for them to be installed in an .M2 repository. - Your resources need to be in your test suite pom file. If your Mule domain project looks like this: ```xml 4.0.0 org.mule.app domain-project mule-domain 1.0.0-SNAPSHOT Domain domain-project Project ``` Then your dependency in your Mule application should look like this: ```xml org.mule.app domain-project 1.0.0-SNAPSHOT mule-domain provided ``` > [!TIP] Remember to keep consistency with `` artifact in your repository and in your > test suite’s pom file ## See Also - [Domain Support (Anypoint Studio)](https://docs.mulesoft.com/studio/domain-support-concept) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Support for Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit supports testing Mule applications that reference a Mule domain, with minimal code changes required. Before running domain-based tests, ensure your domain is in your workspace, folder names match artifact IDs, and domain resources are installed in your M2 repository. - When working in Anypoint Studio, your Mule Domain must always be part of your workspace. - Your Folder must have the same name as your artifact. Regardless if it’s a Mule application or a Mule domain if, the folder in your workspace containing your Mule project must have the same name as the artifact ID defined in your pom file. For example, if your mule project’s artifact Id is: ```xml mule-project ``` Then, the folder in your Studio workspace must be named `mule-project`. This is case sensitive. If your folder is named `Mule-Project`, MUnit won’t recognize your project. - Your resources need to be installed in an M2 repository. You need to handle domains and mule apps as regular dependencies. Setting them as an artifact requires for them to be installed in an .M2 repository. - Your resources need to be in your test suite pom file. If your Mule domain project looks like this: ```xml 4.0.0 org.mule.app domain-project mule-domain 1.0.0-SNAPSHOT Domain domain-project Project ``` Then your dependency in your Mule application should look like this: ```xml org.mule.app domain-project 1.0.0-SNAPSHOT mule-domain provided ``` > [!TIP] Remember to keep consistency with `` artifact in your repository and in your > test suite’s pom file ## See Also - [Domain Support (Anypoint Studio)](https://docs.mulesoft.com/studio/domain-support-concept) --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Test Recorder in Anypoint Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The MUnit Test Recorder captures real flow execution data in Anypoint Studio and automatically generates an MUnit test with configured mocks and assertions. Use it to quickly create tests based on actual application behavior without writing test code from scratch. See [Record an MUnit Test from an Anypoint Exchange Example](https://docs.mulesoft.com/munit/latest/test-recorder-examples) for a fully working example. ## Compatibility The following table describes the product versions required to use the Test Recorder.
ProductVersion

Anypoint Studio

7.5.0 and later

MUnit

2.2.5 and later

MUnit Anypoint Studio Plugin

2.5.0 and later

Mule runtime engine

4.3.0 and later

## Limitations The test recorder has the following limitations when you create MUnit tests: - You cannot create tests for flows with Mule errors raised inside the flow or already existing in the incoming event, even if an **on error continue** error handler controls them. - A recorded flow execution ends successfully, but the result does not reach its destination because the application is killed. - Your validations fail every time your test runs if you configure `spy` or `assert` processors to assert values for random data, time-dependent information (such as timestamps), or values resulting from parallel processes, because those values change in every execution. - Mocking values resulting from parallel processes causes a mixture of real and mocked data that compromises the execution of the processors that follow in your test. - Although the recorder supports data iteration in the flow, such as recursions or loops, it does not support cases in which the structure of the data being tested changes inside the iteration. - The recorder does not support mocking a message before or inside a `foreach` processor. - When using the Test Recorder to generate a test over your flow, you can only mock parameters included in your flow. You cannot mock parameters in sub-flows or in referenced flows through the Test Recorder UI. If you need to mock parameters in sub-flows of any other process in the project, you can modify the mocking component after creating the test. ## See Also - [Record an MUnit Test from an Anypoint Exchange Example](https://docs.mulesoft.com/munit/latest/test-recorder-examples) - [Mock Messages Before and Inside a Foreach Processor in MUnit](https://docs.mulesoft.com/munit/latest/mock-before-after-foreach-cookbook) --- product: MUnit version: 2.3 --- # MUnit Test Structure Fundamentals > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## MUnit Test Suite The base file in MUnit is the test suite file, an XML file located in the `src/test/munit` directory of your Mule application project. You can have as many MUnit test suite files as you need. Each MUnit test suite file is a collection of MUnit tests, and runs independently from other MUnit test suites. An MUnit test suite can contain any combination of the following components: - Before/After Suites - Before/After Tests - MUnit tests Each MUnit test suite is, behind the scenes, no different than a Mule configuration file. You can use several of the Mule top level elements such as flow, sub-flow, and scripts. ### MUnit Configuration The MUnit configuration element (`munit:config`) identifies a Mule configuration file as an MUnit suite file: ```xml ``` #### Ignore a Suite To ignore a whole suite from running, you can use the `ignore` attribute of the configuration: ```xml ``` #### Minimum Mule Version To specify that a suite should run if the Mule version that is equal or newer than a specific version, use the `minMuleVersion` attribute of the configuration: ```xml ``` ## MUnit Test An MUnit test is the basic processor of an MUnit test suite. It represents each test scenario you want to try. The MUnit test is divided in three scopes:
ScopeDescription

Behavior

The behavior scope sets all the preconditions before executing the test logic.

Execution

The execution scope contains the testing logic which waits for all processes to finish before executing the next scope.

Validation

The validation scope contains all the validations for the results of the execution scope.

These scopes are optional. ```xml > ``` ![munit-test](/mulesoft/current/en-us/munit/2.3/_images/munit-test-concept-9c736.png) Figure 1. A Studio representation of the MUnit Test ### MUnit Test Reference
NameDescription

name

Defines the name of the test. The name must be unique inside the test suite.
This attribute is mandatory.

description

Describes the scenario being tested.

ignore

Defines if the test should be ignored. If not present, the test is not ignored.

tags

Comma separated list of tags to assign to the test.

expectedErrorType

Defines the error Type that should be received after the execution of this test.

expectedException

Defines the exception that should be received after the execution of this test.

expectedErrorDescription

Defines the error description that should be received after the execution of this test.

timeOut

Defines maximum time in milliseconds that the test can run before failing.

#### MUnit Test Description Attribute In MUnit, you must write a description for your test. Ideally, you should write a useful, representative description of the scenario you are testing. This description displays in the test console before running the test, and also in the reports. The more representative the description, the easier to read and troubleshoot any failures. #### Ignore a Test There may be scenarios where you need to shut down a test. Whether this be because the test is failing or because it has inconvenient side effects. MUnit allows you to ignore a specific test so that you don’t have to manually comment out the code. You can ignore any of your tests by adding the ignore boolean to the test definition: ```xml ``` The default value for the ignore attribute is `false`. In Anypoint Studio, you can check the **Ignore Test** option. ![ignore-test](/mulesoft/current/en-us/munit/2.3/_images/munit-test-concept-de4c9.png) You can also use expressions to ignore a test based on your current mule version or on your current operating system: Ignore a Test Based on Operating System ```xml ``` Ignore a Test Based on Mule Runtime Engine Version ```xml ``` This test will be ignored if the Mule version is prior to `4.1.4`. Other possible functions are `muleVersionEqualTo` and `muleVersionNewerThan`. #### Test TimeOut Attribute Each MUnit test automatically fails if it takes more than 2 minutes to complete. Use the `timeOut` attribute to set a custom maximum time --in milliseconds-- that the test can run before failing: ```xml .... ``` #### Test Tag Attribute MUnit allows you to tag your tests, so you can choose to run tests under a specific tag. For example: ```xml … ``` ![test-tags](/mulesoft/current/en-us/munit/2.3/_images/munit-test-concept-c2d9f.png) Figure 2. In Anypoint Studio, you can define tags in the proper field. #### MUnit Test Expected Error and Exception Attributes Assume that you want to validate that the flow or sub-flow you are testing fails and throws a specific error. MUnit allows you to add the attributes `expectedErrorType`, `expectException`, and `expectedErrorDescription`, as follows: ```xml ... ``` ![munit test concept e7280](/mulesoft/current/en-us/munit/2.3/_images/munit-test-concept-e7280.png) Figure 3. A visual representation on Anypoint Studio - The `expectedErrorType` attribute expects an error ID defined inside the application being tested. This attribute allows you to validate that a defined error type in your application is thrown. If you define an `errorType` that does not exist in your application, the test does not run. ```xml ... ``` This Error Type test expects that an FTP operation will throw an `FTP:ILLEGAL_PATH` error. If none of your flows are using an FTP connector, then the error type is not defined within your application and the test will not run. ErrorTypes that belong to the Mule Runtime do not need to be typified. For example, `MULE:RETRY_EXHAUSTED` can be defined as simply `RETRY_EXHAUSTED`. - The attribute `expectException` expects a literal exception class name. You must provide the canonical class name of the exception that you expect. MUnit then validates that the underlying cause for the exception thrown is of the exact same type of the class name you are expecting. ```xml ... ``` If you define that your test expects an exception and none is thrown, the test fails immediately. - The attribute expectedErrorDescription expects an error description. This attribute allows you to validate that an error is thrown and this error has description that is equals or contains the expected error description. If you define that your test expects an error and none is thrown or the error thrown description doesn’t match, the test fails immediately. ```xml ... ``` ## Before and After Scopes As with other testing frameworks, MUnit provides a set of scopes that allow you to add processing or actions to run before and/or after the entire MUnit test or MUnit test suite execute: - Before and After Suite Scopes. - Before and After Test Scopes. The ID field for each component must be unique across all your application. The before and after scopes cannot share the same name between them, nor have the same name as any flow in your application. See [Before/After scopes](https://docs.mulesoft.com/munit/2.3/before-after-scopes-reference) reference for more information. --- product: MUnit version: 3.6 --- # MUnit Test Structure Fundamentals > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## MUnit Test Suite The base file in MUnit is the test suite file, an XML file located in the `src/test/munit` directory of your Mule application project. You can use multiple MUnit test suite files. Each MUnit test suite file is a collection of MUnit tests and runs independently from other MUnit test suites. An MUnit test suite can contain any combination of the following components: - Before/After Suites - Before/After Tests - MUnit tests Each MUnit test suite is similar to a Mule configuration file. You can use several of the Mule top-level elements such as flow, sub-flow, and scripts. ### MUnit Configuration The MUnit configuration element (`munit:config`) identifies a Mule configuration file as an MUnit suite file: ```xml ``` #### Ignore a Suite To ignore a whole suite from running, you can use the `ignore` attribute of the configuration: ```xml ``` #### Minimum Mule Version Specify the minimum required Mule version to run a test suite by defining the `minMuleVersion` attribute of the configuration: ```xml ``` ## MUnit Test An MUnit test is the basic processor of an MUnit test suite and it represents the scenario to test. Three optional scopes divide MUnit tests:
ScopeDescription

Behavior

The behavior scope sets all the preconditions before executing the test logic.

Execution

The execution scope contains the testing logic which waits for all processes to finish before executing the next scope.

Validation

The validation scope contains all the validations for the results of the execution scope.

```xml > ``` ![munit-test](/mulesoft/current/en-us/munit/3.6/_images/munit-test-concept-9c736.png) Figure 1. A Studio representation of the MUnit Test ### MUnit Test Reference
NameDescription

name

Defines the name of the test. The name must be unique in the test suite.
This attribute is mandatory.

description

Describes the scenario to test.

ignore

Defines if the test must be ignored. If not present, the test isn’t ignored.

tags

Comma-separated list of tags to assign to the test.

expectedErrorType

Defines the error Type to receive after executing the test.

expectedException

Defines the exception to receive after executing the test.

expectedErrorDescription

Defines the error description to receive after executing the test.

timeOut

Defines the maximum time in milliseconds that the test can run before failing.

#### MUnit Test Description Attribute MUnit tests require a description. The description must be useful and representative of the tested scenario. This description shows in the test console before running the test, and also in the reports. The more representative the description, the easier it is to read and troubleshoot failures. #### Ignore a Test When a test fails or has inconvenient side effects, you can shut it down without commenting out the code. To ignore a test, add the `ignore` boolean to its definition: ```xml ``` The default value for the ignore attribute is `false`. You can also use expressions to ignore a test based on your current Mule version or on your current operating system: Ignore a Test Based on the Operating System ```xml ``` Ignore a Test Based on Mule Runtime Engine Version ```xml ``` MUnit ignores this test if the Mule version is earlier than `4.1.4`. Other possible functions are `muleVersionEqualTo` and `muleVersionNewerThan`. #### Test TimeOut Attribute An MUnit test automatically fails if it takes more than 2 minutes to complete. Use the `timeOut` attribute to set a custom maximum time --in milliseconds-- that the test can run before failing: ```xml .... ``` #### Test Tag Attribute You can tag your tests and choose to run tests under a specific tag. For example: ```xml … ``` ![Tags field highlighted in Studio.](/mulesoft/current/en-us/munit/3.6/_images/munit-test-concept-c2d9f.png) Figure 2. In Anypoint Studio, you can define tags in the **Tags** field. #### MUnit Test Expected Error and Exception Attributes To validate that a flow or sub-flow you’re testing fails and throws a specific error, add the `expectedErrorType`, `expectException`, and `expectedErrorDescription` attributes as follows: ```xml ... ``` ![Failure Expectation section highlighted in Studio.](/mulesoft/current/en-us/munit/3.6/_images/munit-test-concept-e7280.png) Figure 3. A visual representation on Anypoint Studio - The `expectedErrorType` attribute expects an error ID defined in the tested application. This attribute validates that your application throws a defined error type. If you define an `errorType` that does not exist in your application, the test doesn’t run. ```xml ... ``` This Error Type test expects that an FTP operation throws an `FTP:ILLEGAL_PATH` error. If none of your flows are using an FTP connector, then the error type isn’t defined within your application and the test doesn’t run. You mustn’t typify `ErrorTypes` that belong to the Mule Runtime. For example, you can define `MULE:RETRY_EXHAUSTED` as `RETRY_EXHAUSTED`. - The attribute `expectException` expects a literal exception class name. You must provide the canonical class name of the exception that you expect. MUnit then validates that the underlying cause for the exception thrown is of the same type of the class name you’re expecting. ```xml ... ``` If you define that your test expects an exception and none is thrown, the test fails immediately. - The attribute `expectedErrorDescription` expects an error description. This attribute validates that your application throws an error and the error has a description that is equal to or contains the expected error description. If you define that your test expects an error and none is thrown or the error description doesn’t match, the test fails immediately. ```xml ... ``` ## Before and After Scopes As with other testing frameworks, MUnit provides a set of scopes so you can add processing or actions to run before and after the entire MUnit test or MUnit test suite executes: - Before and After Suite Scopes. - Before and After Test Scopes. The ID field for each component must be unique across all your applications. The before and after scopes can’t share the same name, nor have the same name as any flow in your application. See [Before and After Scopes](https://docs.mulesoft.com/munit/3.6/before-after-scopes-reference) reference for additional information. --- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Test Structure Fundamentals > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio An MUnit test suite is an XML file that contains MUnit tests organized into behavior, execution, and validation scopes. Use test suite files in the src/test/munit directory to define, configure, and run automated tests against your Mule application flows. ## MUnit Test Suite The base file in MUnit is the test suite file, an XML file located in the `src/test/munit` directory of your Mule application project. You can use multiple MUnit test suite files. Each MUnit test suite file is a collection of MUnit tests and runs independently from other MUnit test suites. An MUnit test suite can contain any combination of the following components: - Before/After Suites - Before/After Tests - MUnit tests Each MUnit test suite is similar to a Mule configuration file. You can use several of the Mule top-level elements such as flow, sub-flow, and scripts. ### MUnit Configuration The MUnit configuration element (`munit:config`) identifies a Mule configuration file as an MUnit suite file: ```xml ``` #### Ignore a Suite To ignore a whole suite from running, you can use the `ignore` attribute of the configuration: ```xml ``` #### Minimum Mule Version Specify the minimum required Mule version to run a test suite by defining the `minMuleVersion` attribute of the configuration: ```xml ``` ## MUnit Test An MUnit test is the basic processor of an MUnit test suite and it represents the scenario to test. Three optional scopes divide MUnit tests:
ScopeDescription

Behavior

The behavior scope sets all the preconditions before executing the test logic.

Execution

The execution scope contains the testing logic which waits for all processes to finish before executing the next scope.

Validation

The validation scope contains all the validations for the results of the execution scope.

```xml > ``` ![munit-test](/mulesoft/current/en-us/munit/latest/_images/munit-test-concept-9c736.png) Figure 1. A Studio representation of the MUnit Test ### MUnit Test Reference
NameDescription

name

Defines the name of the test. The name must be unique in the test suite.
This attribute is mandatory.

description

Describes the scenario to test.

ignore

Defines if the test must be ignored. If not present, the test isn’t ignored.

tags

Comma-separated list of tags to assign to the test.

expectedErrorType

Defines the error Type to receive after executing the test.

expectedException

Defines the exception to receive after executing the test.

expectedErrorDescription

Defines the error description to receive after executing the test.

timeOut

Defines the maximum time in milliseconds that the test can run before failing.

#### MUnit Test Description Attribute MUnit tests require a description. The description must be useful and representative of the tested scenario. This description shows in the test console before running the test, and also in the reports. The more representative the description, the easier it is to read and troubleshoot failures. #### Ignore a Test When a test fails or has inconvenient side effects, you can shut it down without commenting out the code. To ignore a test, add the `ignore` boolean to its definition: ```xml ``` The default value for the ignore attribute is `false`. You can also use expressions to ignore a test based on your current Mule version or on your current operating system: Ignore a Test Based on the Operating System ```xml ``` Ignore a Test Based on Mule Runtime Engine Version ```xml ``` MUnit ignores this test if the Mule version is earlier than `4.1.4`. Other possible functions are `muleVersionEqualTo` and `muleVersionNewerThan`. #### Test Timeout Attribute An MUnit test automatically fails if it takes more than 2 minutes to complete. Use the `timeOut` attribute to set a custom maximum time --in milliseconds-- that the test can run before failing: ```xml .... ``` #### Test Tag Attribute You can tag your tests and choose to run tests under a specific tag. For example: ```xml … ``` ![Tags field highlighted in Studio.](/mulesoft/current/en-us/munit/latest/_images/munit-test-concept-c2d9f.png) Figure 2. In Anypoint Studio, you can define tags in the **Tags** field. #### MUnit Test Expected Error and Exception Attributes To validate that a flow or sub-flow you’re testing fails and throws a specific error, add the `expectedErrorType`, `expectException`, and `expectedErrorDescription` attributes as follows: ```xml ... ``` ![Failure Expectation section highlighted in Studio.](/mulesoft/current/en-us/munit/latest/_images/munit-test-concept-e7280.png) Figure 3. A visual representation on Anypoint Studio - The `expectedErrorType` attribute expects an error ID defined in the tested application. This attribute validates that your application throws a defined error type. If you define an `errorType` that does not exist in your application, the test doesn’t run. ```xml ... ``` This Error Type test expects that an FTP operation throws an `FTP:ILLEGAL_PATH` error. If none of your flows are using an FTP connector, then the error type isn’t defined within your application and the test doesn’t run. You mustn’t typify `ErrorTypes` that belong to the Mule Runtime. For example, you can define `MULE:RETRY_EXHAUSTED` as `RETRY_EXHAUSTED`. - The attribute `expectException` expects a literal exception class name. You must provide the canonical class name of the exception that you expect. MUnit then validates that the underlying cause for the exception thrown is of the same type of the class name you’re expecting. ```xml ... ``` If you define that your test expects an exception and none is thrown, the test fails immediately. - The attribute `expectedErrorDescription` expects an error description. This attribute validates that your application throws an error and the error has a description that is equal to or contains the expected error description. If you define that your test expects an error and none is thrown or the error description doesn’t match, the test fails immediately. ```xml ... ``` ## Before and After Scopes As with other testing frameworks, MUnit provides a set of scopes so you can add processing or actions to run before and after the entire MUnit test or MUnit test suite executes: - Before and After Suite Scopes. - Before and After Test Scopes. The ID field for each component must be unique across all your applications. The before and after scopes can’t share the same name, nor have the same name as any flow in your application. See [MUnit Before and After Scopes](https://docs.mulesoft.com/munit/latest/before-after-scopes-reference) reference for additional information. --- product: MUnit version: 2.3 --- # MUnit Utils > For the full documentation index, see: https://docs.mulesoft.com/llms.txt One of the main problems of testing production code are external system connections. MUnit provides a set of utilities for you to write your tests in a portable way and mock external system connections from your tests.
UtilityDescription

Implement a DB server in your local environment to test connections.

Implement an FTP server in your local environment to test connections.

Manage temporary queues during your test runs.

--- product: MUnit version: 3.6 --- # MUnit Utils > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio One of the main problems of testing production code are external system connections. MUnit provides a set of utilities for you to write your tests in a portable way and mock external system connections from your tests.
UtilityDescription

Implement a DB server in your local environment to test connections.

Implement an FTP server in your local environment to test connections.

Manage temporary queues during your test runs.

--- product: MUnit version: 3.7 is-latest-version: true --- # MUnit Utils > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit Utils are utilities that let you mock external system connections in MUnit tests, making your test suites portable and independent from external infrastructure. Use them to implement in-memory database and FTP servers, or manage temporary queues during test runs.
UtilityDescription

Implement a DB server in your local environment to test connections.

Implement an FTP server in your local environment to test connections.

Manage temporary queues during your test runs.

--- product: MUnit version: 3.7 is-latest-version: true keywords: munit, testing, unit testing --- # MUnit Verify Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The MUnit Verify event processor validates that a specified event processor was called a certain number of times during a MUnit test. Use it to confirm that your flow executed the expected processors with the expected attributes, even without creating a mock for them. ```xml ```
Attribute NameDescription

eventProcessor

Describes which event processor you want to mock. The description takes the form {name-space}:{event-processor-name}. It supports regular expressions.

times

(Default = 1.) Defines the verification as successful if the event processor was called N and only N number of times.

atLeast

Defines the verification as successful if the event processor was called a minimum of N number of times.

atMost

Defines the verification as successful if the event processor was called maximum of N number of times.

The attributes `times`, `atLeast`, `atMost`, are mutually exclusive. The `eventProcessor` attribute accepts regular expressions. For example, you can create the same verification as `.*:request` to verify for an event processor named request, disregarding which namespace the event processor belongs to. The regular expression language is the same as Java. ## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/latest/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/latest/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/latest/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/latest/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) --- product: MUnit version: 2.3 --- # Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit is a Mule application testing framework that allows you to easily build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. MUnit version 2.3, works with all Mule versions since 4.0 With MUnit you can: - Create your test by writing Mule code - Mock processors - Spy any processor - Verify processor calls - Enable or ignore particular tests - Tag tests - Check visual coverage in Studio - Generate coverage reports MUnit is fully integrated with Anypoint Studio, allowing you to create, design and run MUnit tests just like you would Mule applications. MUnit is divided in two main sub modules: - MUnit - MUnit Tools Each module has its own dependency: MUnit Dependencies ```xml com.mulesoft.munit munit-runner 2.3.0 mule-plugin test ``` MUnit Tools dependencies ```xml com.mulesoft.munit munit-tools 2.3.0 mule-plugin test ``` ## See Also - [MUnit Event Processors](https://docs.mulesoft.com/munit/2.3/event-processors) --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # Parameterized > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A parameterized test suite runs the same tests but with different inputs. The test suite parameterization is defined at a configuration level as follows: ```xml ``` The Test Suite runs twice: Firstly, with the `firstParameterization` parameters. Secondly, with the `secondParameterization` parameters. For example, if you have a test that sets a payload for a flow and expects a result: Parameterization Example ```xml ``` ## Parameterization from File To use the same parameterized values on different test suites, you must save your parameterizations values in a YAML file in the `/test/resources` directory of your Mule application project: parameterizations.yaml Example ```yaml firstParameterization: name: "Robert" lastname: "Plant" secondParameterization: name: "Jimmy" lastname: "Page" ``` And reference it from your test suite configuration: Example Parameterization From File ```xml ``` You can combine both methods to add parameterized values to a test suite: Example Parameterization From File and in the Test Suite Configuration ```xml ``` If you define the same parameterization key in a YAML file and your test suite configuration, the test suite parameterization overrides your YAML parameterization. --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # Parameterized > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio A parameterized test suite runs the same tests but with different inputs. The test suite parameterization is defined at a configuration level as follows: ```xml ``` The Test Suite runs twice: Firstly, with the `firstParameterization` parameters. Secondly, with the `secondParameterization` parameters. For example, if you have a test that sets a payload for a flow and expects a result: Parameterization Example ```xml ``` ## Parameterization from File To use the same parameterized values on different test suites, you must save your parameterizations values in a YAML file in the `/test/resources` directory of your Mule application project: parameterizations.yaml Example ```yaml firstParameterization: name: "Robert" lastname: "Plant" secondParameterization: name: "Jimmy" lastname: "Page" ``` And reference it from your test suite configuration: Example Parameterization From File ```xml ``` You can combine both methods to add parameterized values to a test suite: Example Parameterization From File and in the Test Suite Configuration ```xml ``` If you define the same parameterization key in a YAML file and your test suite configuration, the test suite parameterization overrides your YAML parameterization. --- product: MUnit version: 3.7 is-latest-version: true --- # Patch the Embedded Mule Runtime Engine Version in MUnit > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Patch the embedded Mule runtime engine version that MUnit uses to run tests, overriding the default version defined in your `mule-artifact.json` file. You can configure the patched version from Maven or Anypoint Studio. ## Patch MUnit Using Maven By default, MUnit runs against the Mule version corresponding to the `minMuleVersion` defined in the `mule-artifact.json` file. You can override this version by using the `munit.runtimeversion` property in the `munit-maven-plugin` artifact configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test 4.3.0-20200727 (1) ```
1Be sure to replace the placeholder version in this example with your version, as provided by MuleSoft.
The `munit.runtimeversion` property replaces the deprecated `runtimeVersion` property. The `runtimeVersion` property remains supported for backward compatibility. If you use `runtimeVersion`, MUnit displays a warning message that indicates the property is deprecated and that you must migrate to `munit.runtimeversion`. ## Patch MUnit Using Studio By default, MUnit runs in Anypoint Studio with the Mule runtime engine version of the project server. You can override this version by specifying the patched Mule version in the MUnit run configuration menu: 1. In the menu bar, select **Run** and **Run Configurations**. 2. Under **MUnit**, select your MUnit test file. 3. In the **Mule Runtime Version** field under **Advanced Settings**, type the Mule patched version to use. ![Patched Mule runtime version used for the test.](/mulesoft/current/en-us/munit/latest/_images/runtime-patching-studio.png) If you already set the `munit.runtimeversion` property in the POM file of your project, click **Load configuration from POM file** to automatically load this version into the **Mule Runtime Version** field. ## See Also - [Mule Runtime Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-esb) - [MUnit Maven Plugin](https://docs.mulesoft.com/munit/latest/munit-maven-plugin) --- product: MUnit version: 2.3 --- # Patching the Embedded Mule Runtime Engine Version > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Patching in MUnit is different from patching in Mule runtime engine. MUnit runs using an embedded Mule container, which downloads all required dependencies to start Mule based on a given version. To use a patched Mule version (for example, `4.3.0-20200727`), you must point MUnit to run specifically against it. You can do this from either Maven or Anypoint Studio. ## Patch MUnit Using Maven By default, MUnit runs against the Mule version corresponding to the `minMuleVersion` defined in the `mule-artifact.json` file. You can override this version by using the `runtimeVersion` attribute of the `munit-maven-plugin` artifact configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test 4.3.0-20200727 (1) ```
1Be sure to replace the placeholder version in this example with your version, as provided by MuleSoft.
## Patch MUnit Using Studio By default, MUnit runs in Anypoint Studio with the Mule runtime engine version of the project server. You can override this version by specifying the patched Mule version in the MUnit run configuration menu: 1. In the top menu bar, select **Run** and **Run Configurations…**. 2. Under **MUnit**, select your MUnit test file. 3. In the **Mule Runtime Version** field under **Advanced Settings** type the Mule patched version you want to use. ![runtime patching studio](/mulesoft/current/en-us/munit/2.3/_images/runtime-patching-studio.png) If you already set the `runtimeVersion` attribute in the POM file of your project, click **Load configuration from POM file** to automatically load this version into the **Mule Runtime Version** field. ## See Also - [Mule Runtime Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-esb) - [MUnit Maven Plugin](https://docs.mulesoft.com/munit/2.3/munit-maven-plugin) --- product: MUnit version: 3.6 --- # Patching the Embedded Mule Runtime Engine Version > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Patching in MUnit is different from patching in Mule runtime engine. MUnit runs using an embedded Mule container, which downloads all required dependencies to start Mule based on a given version. To use a patched Mule version (for example, `4.3.0-20200727`), you must point MUnit to run specifically against it. You can do this from either Maven or Anypoint Studio. ## Patch MUnit Using Maven By default, MUnit runs against the Mule version corresponding to the `minMuleVersion` defined in the `mule-artifact.json` file. You can override this version by using the `runtimeVersion` attribute of the `munit-maven-plugin` artifact configuration: ```xml com.mulesoft.munit.tools munit-maven-plugin ${munit.version} test test test 4.3.0-20200727 (1) ```
1Be sure to replace the placeholder version in this example with your version, as provided by MuleSoft.
## Patch MUnit Using Studio By default, MUnit runs in Anypoint Studio with the Mule runtime engine version of the project server. You can override this version by specifying the patched Mule version in the MUnit run configuration menu: 1. In the menu bar, select **Run** and **Run Configurations**. 2. Under **MUnit**, select your MUnit test file. 3. In the **Mule Runtime Version** field under **Advanced Settings**, type the Mule patched version to use. ![Patched Mule runtime version used for the test.](/mulesoft/current/en-us/munit/3.6/_images/runtime-patching-studio.png) If you already set the `runtimeVersion` attribute in the POM file of your project, click **Load configuration from POM file** to automatically load this version into the **Mule Runtime Version** field. ## See Also - [Mule Runtime Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-esb) - [MUnit Maven Plugin](https://docs.mulesoft.com/munit/3.6/munit-maven-plugin) --- product: MUnit version: 2.3 keywords: munit, testing, unit testing, queue --- # Queue Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Queue event processors allow you to manage temporary queues during your test runs. All queues are emptied as soon as the test ends. ## Queue Adds the value to the queue. If not specified, the value is taken from the `payload`. ```xml #[1] ``` You can specify the queue’s name to which the value should be added. If not specified, the default queue will be used. ```xml #[1] ``` ## Dequeue Removes the last element of the queue, if the queue is empty, it waits until an element is queued. ```xml ``` You can specify a timeout when waiting for an element to be queued: ```xml ``` Like the queue operation, you can specify the queue’s name from which to dequeue. If not specified, the default queue will be used. ```xml ``` ## Queue Size Function that obtains the queue size. ```xml ``` Like the other operations, you can specify the queue from which to the get the size. If not specified, the default queue will be used. ```xml ``` --- product: MUnit version: 3.6 keywords: munit, testing, unit testing, queue --- # Queue Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Queue event processors allow you to manage temporary queues during your test runs. All queues are emptied as soon as the test ends. ## Queue Adds the value to the queue. If not specified, the value is taken from the `payload`. ```xml #[1] ``` You can specify the queue’s name to which the value should be added. If not specified, the default queue will be used. ```xml #[1] ``` ## Dequeue Removes the last element of the queue, if the queue is empty, it waits until an element is queued. ```xml ``` You can specify a timeout when waiting for an element to be queued: ```xml ``` Like the queue operation, you can specify the queue’s name from which to dequeue. If not specified, the default queue will be used. ```xml ``` ## Queue Size Function that obtains the queue size. ```xml ``` Like the other operations, you can specify the queue from which to the get the size. If not specified, the default queue will be used. ```xml ``` --- product: MUnit version: 2.3 --- # Reading MUnit Results > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section briefly explains how to read the MUnit console logs. Successful Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + SUCCESS - Test test-suite finished successfully - Time elapsed: 2227ms + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 0 - Errors: 0 - Skipped: 0 - Time elapsed: 2241ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 0, Skipped: 0 [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== ``` Failed Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + FAILURE - The test test-suite finished with a failure - Time elapsed: 2399ms + java.lang.AssertionError: Expected: "Bye World!" but: was "Hello World" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at org.mule.munit.assertion.internal.AssertModule.assertThat(AssertModule.java:34) at org.mule.munit.tools.assertion.AssertOperations.assertThat(AssertOperations.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 1 - Errors: 0 - Skipped: 0 - Time elapsed: 2416ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 1, Skipped: 0 [INFO] --- test-suite <<< FAILED [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 1 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.400 s [INFO] Finished at: 2017-11-16T14:37:32-03:00 [INFO] Final Memory: 19M/302M [INFO] ------------------------------------------------------------------------ ``` Build Error ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ERROR 2017-11-16 14:40:20,239 [[coverage].http.requester.HTTP_Request_configuration.01: [coverage].http.requester.HTTP_Request_configuration @55ccbf06 SelectorRunner] org.mule.extension.http.internal.request.HttpRequester: Error sending HTTP request to http://0.0.0.0:8081/ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + ERROR - The test test-suite finished with an error - Time elapsed: 218ms + java.util.concurrent.ExecutionException: org.mule.runtime.api.component.execution.ComponentExecutionException: org.mule.extension.http.api.error.HttpRequestFailedException: HTTP GET on resource 'http://0.0.0.0:8081/' failed: Connection refused. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 1, Failures: 0, Skipped: 0 [INFO] --- test-suite <<< ERROR [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 1 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 20.167 s [INFO] Finished at: 2017-11-16T14:40:27-03:00 [INFO] Final Memory: 25M/315M [INFO] ------------------------------------------------------------------------ ``` ## See Also --- product: MUnit version: 3.6 --- # Reading MUnit Results > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio This section briefly explains how to read the MUnit console logs. Successful Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + SUCCESS - Test test-suite finished successfully - Time elapsed: 2227ms + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 0 - Errors: 0 - Skipped: 0 - Time elapsed: 2241ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 0, Skipped: 0 [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== ``` Failed Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + FAILURE - The test test-suite finished with a failure - Time elapsed: 2399ms + java.lang.AssertionError: Expected: "Bye World!" but: was "Hello World" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at org.mule.munit.assertion.internal.AssertModule.assertThat(AssertModule.java:34) at org.mule.munit.tools.assertion.AssertOperations.assertThat(AssertOperations.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 1 - Errors: 0 - Skipped: 0 - Time elapsed: 2416ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 1, Skipped: 0 [INFO] --- test-suite <<< FAILED [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 1 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.400 s [INFO] Finished at: 2017-11-16T14:37:32-03:00 [INFO] Final Memory: 19M/302M [INFO] ------------------------------------------------------------------------ ``` Build Error ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ERROR 2017-11-16 14:40:20,239 [[coverage].http.requester.HTTP_Request_configuration.01: [coverage].http.requester.HTTP_Request_configuration @55ccbf06 SelectorRunner] org.mule.extension.http.internal.request.HttpRequester: Error sending HTTP request to http://0.0.0.0:8081/ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + ERROR - The test test-suite finished with an error - Time elapsed: 218ms + java.util.concurrent.ExecutionException: org.mule.runtime.api.component.execution.ComponentExecutionException: org.mule.extension.http.api.error.HttpRequestFailedException: HTTP GET on resource 'http://0.0.0.0:8081/' failed: Connection refused. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 1, Failures: 0, Skipped: 0 [INFO] --- test-suite <<< ERROR [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 1 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 20.167 s [INFO] Finished at: 2017-11-16T14:40:27-03:00 [INFO] Final Memory: 25M/315M [INFO] ------------------------------------------------------------------------ ``` --- product: MUnit version: 3.7 is-latest-version: true --- # Reading MUnit Results > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit console logs report test results in three states: successful build, failed build, and build error. Use the MUnit Run Summary at the end of each run to quickly identify the number of tests, failures, errors, and skipped tests. Successful Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + SUCCESS - Test test-suite finished successfully - Time elapsed: 2227ms + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 0 - Errors: 0 - Skipped: 0 - Time elapsed: 2241ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 0, Skipped: 0 [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== ``` Failed Build ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + FAILURE - The test test-suite finished with a failure - Time elapsed: 2399ms + java.lang.AssertionError: Expected: "Bye World!" but: was "Hello World" at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) at org.mule.munit.assertion.internal.AssertModule.assertThat(AssertModule.java:34) at org.mule.munit.tools.assertion.AssertOperations.assertThat(AssertOperations.java:45) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ================================================================================== Number of tests run: 1 - Failed: 1 - Errors: 0 - Skipped: 0 - Time elapsed: 2416ms ================================================================================== [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 0, Failures: 1, Skipped: 0 [INFO] --- test-suite <<< FAILED [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 0 [INFO] > Failures: 1 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 22.400 s [INFO] Finished at: 2017-11-16T14:37:32-03:00 [INFO] Final Memory: 19M/302M [INFO] ------------------------------------------------------------------------ ``` Build Error ```console ============================================================ ============ Running new-test-suite.xml suite ============ ============================================================ ++++++++++++++++++++++++++++++++++++++++++++ + Running test: test-suite - Test + ++++++++++++++++++++++++++++++++++++++++++++ ERROR 2017-11-16 14:40:20,239 [[coverage].http.requester.HTTP_Request_configuration.01: [coverage].http.requester.HTTP_Request_configuration @55ccbf06 SelectorRunner] org.mule.extension.http.internal.request.HttpRequester: Error sending HTTP request to http://0.0.0.0:8081/ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + ERROR - The test test-suite finished with an error - Time elapsed: 218ms + java.util.concurrent.ExecutionException: org.mule.runtime.api.component.execution.ComponentExecutionException: org.mule.extension.http.api.error.HttpRequestFailedException: HTTP GET on resource 'http://0.0.0.0:8081/' failed: Connection refused. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [INFO] ==================================================================================== [INFO] MUnit Run Summary [INFO] ==================================================================================== [INFO] >> new-test-suite.xml test result: Tests: 1, Errors: 1, Failures: 0, Skipped: 0 [INFO] --- test-suite <<< ERROR [NOTE] [INFO] ==================================================================================== [INFO] > Tests: 1 [INFO] > Errors: 1 [INFO] > Failures: 0 [INFO] > Skipped: 0 [INFO] ==================================================================================== [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 20.167 s [INFO] Finished at: 2017-11-16T14:40:27-03:00 [INFO] Final Memory: 25M/315M [INFO] ------------------------------------------------------------------------ ``` --- product: MUnit version: 3.7 is-latest-version: true --- # Record an MUnit Test from an Anypoint Exchange Example > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Record an MUnit test in Anypoint Studio by importing an existing project from Anypoint Exchange and capturing flow processing with the MUnit test recorder. This example uses the Login Form Using the HTTP Connector project. ## Prerequisite - Your Anypoint Platform credentials are configured in Studio. See [Configuring Anypoint Platform Credentials](https://docs.mulesoft.com/studio/set-credentials-in-studio-to) for more information. ## Test the Login Form Using the HTTP Connector Example 1. Click the Open Exchange icon ![3%](/mulesoft/current/en-us/munit/latest/_images/exchange-icon.png). 2. Select **Provided by MuleSoft** in the pop-up Exchange window, filter per **Examples**, and look for the **Login Form Using the HTTP Connector**. 3. Click **Open**. Studio imports the example as a new working project. 4. If prompted, select **Perform Update** in **Update your Workspace**. 5. Select the Manage Mule Projects APIs icon ![2%](/mulesoft/current/en-us/munit/latest/_images/manage-project-api-icon.png). 6. Select **Modules** and update both **MUnit** and **Munit Tools**: ![update munit](/mulesoft/current/en-us/munit/latest/_images/update-munit.png) 7. Select **Apply and Close**. ### Test the Process for a Successful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/latest/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `mule` for both **Username** and **Password**, and click **Submit**. The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/latest/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-successfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In **Successful login**, select **Verify that this process was called** and set the counter **equal to** to `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login is successful. ### Test the Process for an Unsuccessful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/latest/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `admin` in both **Username** and **Password**, and click **Submit**: The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/latest/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-unsuccessfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In the **Unsuccessful login** parse template step, select **Verify that this process was called** and set the counter to **equal to** `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login fails. ## See Also - [Test Recorder in Studio](https://docs.mulesoft.com/munit/latest/test-recorder) --- product: MUnit version: 2.3 --- # Recording a Test from an Exchange Example > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The following example shows you how to import to Anypoint Studio an existing project from Anypoint Exchange and then record the flow processing to create a unit test for the flows. ## Prerequisite - Your Anypoint Platform credentials are configured in Studio. See [Configuring Anypoint Platform Credentials](https://docs.mulesoft.com/studio/set-credentials-in-studio-to) for more information. ## Test the Login Form Using the HTTP Connector Example 1. Click the Open Exchange icon ![3%](/mulesoft/current/en-us/munit/2.3/_images/exchange-icon.png). 2. Select **Provided by MuleSoft** in the pop-up Exchange window, filter per **Examples**, and look for the **Login Form Using the HTTP Connector**. 3. Click **Open**. Studio imports the example as a new working project. 4. If prompted, select **Perform Update** in **Update your Workspace**. 5. Select the Manage Mule Projects APIs icon ![2%](/mulesoft/current/en-us/munit/2.3/_images/manage-project-api-icon.png). 6. Select **Modules** and update both **MUnit** and **Munit Tools**: ![update munit](/mulesoft/current/en-us/munit/2.3/_images/update-munit.png) 7. Select **Apply and Close**. ### Test the Process for a Successful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/2.3/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `mule` for both **Username** and **Password**, and click **Submit**. The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/2.3/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-successfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In **Successful login**, select **Verify that this process was called** and set the counter **equal to** to `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login is successful. ### Test the Process for an Unsuccessful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/2.3/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `admin` in both **Username** and **Password**, and click **Submit**: The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/2.3/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-unsuccessfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In the **Unsuccessful login** parse template step, select **Verify that this process was called** and set the counter to **equal to** `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login fails. ## See Also - [Test Recorder in Studio](https://docs.mulesoft.com/munit/2.3/test-recorder) --- product: MUnit version: 3.6 --- # Recording a Test from an Exchange Example > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The following example shows you how to import to Anypoint Studio an existing project from Anypoint Exchange and then record the flow processing to create a unit test for the flows. ## Prerequisite - Your Anypoint Platform credentials are configured in Studio. See [Configuring Anypoint Platform Credentials](https://docs.mulesoft.com/studio/set-credentials-in-studio-to) for more information. ## Test the Login Form Using the HTTP Connector Example 1. Click the Open Exchange icon ![3%](/mulesoft/current/en-us/munit/3.6/_images/exchange-icon.png). 2. Select **Provided by MuleSoft** in the pop-up Exchange window, filter per **Examples**, and look for the **Login Form Using the HTTP Connector**. 3. Click **Open**. Studio imports the example as a new working project. 4. If prompted, select **Perform Update** in **Update your Workspace**. 5. Select the Manage Mule Projects APIs icon ![2%](/mulesoft/current/en-us/munit/3.6/_images/manage-project-api-icon.png). 6. Select **Modules** and update both **MUnit** and **Munit Tools**: ![update munit](/mulesoft/current/en-us/munit/3.6/_images/update-munit.png) 7. Select **Apply and Close**. ### Test the Process for a Successful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/3.6/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `mule` for both **Username** and **Password**, and click **Submit**. The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/3.6/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-successfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In **Successful login**, select **Verify that this process was called** and set the counter **equal to** to `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login is successful. ### Test the Process for an Unsuccessful Login Attempt 1. In your project, right-click `DoLoginFlow` and select **Munit** > **Record new test for this flow**: ![login flow test recorder example](/mulesoft/current/en-us/munit/3.6/_images/login-flow-test-recorder-example.png) The test recorder starts your project and starts recording the event going through that flow. 2. Open a browser and navigate to `http://0.0.0.0:8081/login`. 3. Type `admin` in both **Username** and **Password**, and click **Submit**: The test recorder captures this event and stops the recording. 4. Return to Studio and click **Configure Test**: ![stops recording](/mulesoft/current/en-us/munit/3.6/_images/stops-recording.png) 5. Select the file name for the MUnit test suite in which you want to record your test. 6. Under **Test name**, type `_DoLoginFlow-unsuccessfull_`. 7. Set the test recorder to set the recorded input of the flow, and assert that the recorded output is the expected output by the test. 8. In the **Unsuccessful login** parse template step, select **Verify that this process was called** and set the counter to **equal to** `_1_` time. 9. Click **Next** and then **Finish**. A fully functional MUnit test is generated to assert that the process in your application works as expected when the login fails. ## See Also - [Test Recorder in Studio](https://docs.mulesoft.com/munit/3.6/test-recorder) --- product: MUnit version: 2.3 --- # Resource Matchers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## getResourceAsStream(String) Returns the resource from the path String as a stream. Example ```xml ``` ## getResourceAsReusableStream(String) Returns the resource from the path String as a reusable stream. Example ```xml ``` ## getResourceAsString(path:String,encoding:String) Returns the resource from the path String as a String, where the second parameter (encoding) is optional. Example ```xml ``` You can also specify the encoding: Example ```xml ``` ## getResourceAsByteArray(String) Returns the resource from the path String as a byte array. Example ```xml ``` ## queueSize(String) Returns the size of the queue specified inside `#[MunitTools::queueSize()]`. For example, to assert the size of a queue named `QUEUE_SIZE`: Example ```xml #['EXAMPLE'] ``` ## createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) Creates a Mule message with the specified attributes. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/2.3/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/2.3/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference) --- product: MUnit version: 3.6 --- # Resource Matchers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## getResourceAsStream(String) Returns the resource from the path String as a stream. Example ```xml ``` ## getResourceAsReusableStream(String) Returns the resource from the path String as a reusable stream. Example ```xml ``` ## getResourceAsString(path:String,encoding:String) Returns the resource from the path String as a String, where the second parameter (encoding) is optional. Example ```xml ``` You can also specify the encoding: Example ```xml ``` ## getResourceAsByteArray(String) Returns the resource from the path String as a byte array. Example ```xml ``` ## queueSize(String) Returns the size of the queue specified inside `#[MunitTools::queueSize()]`. For example, to assert the size of a queue named `QUEUE_SIZE`: Example ```xml #['EXAMPLE'] ``` ## createMessage(payload: Any, mimeType: String|Null , attributes: Any, attributeMimeType: String|Null) Creates a Mule message with the specified attributes. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/3.6/core-matchers-reference) - [String Matchers Reference](https://docs.mulesoft.com/munit/3.6/string-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference) --- product: MUnit version: 2.3 keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # Run Custom Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The **Run Custom event processor** enables you to assert the Mule event content against a custom assertion. To add the **Run Custom processor** to your project, add the following dependency to your `pom.xml` file: ```xml com.mulesoft.munit munit-assert ${munit.version} test ``` You also have to add your custom assertion class to the `mule-artifact.json` file as an exported resource. For example, you can define the following assertion in Java: ```java package org.mule.custom; import org.mule.munit.assertion.api.MunitAssertion; import org.mule.munit.assertion.api.TypedValue; public class CustomAssertion implements MunitAssertion { @Override public void execute(TypedValue expression, Object params) throws AssertionError { (1) if (!"Hello World".equals(expression.getValue())) { (2) throw new AssertionError("Error the payload is incorrect"); } } } ```
1Implement the only method in the interface public void execute(TypedValue expression, Object params) throws AssertionError.
2Run your custom logic, which in this case validates that the message payload is Hello World.
The `CustomAssertion` class must be located in the scr/test/java directory. And use the **Run Custom Event Processor** to run it: ```xml ```
1The assertion field needs to have the canonical class name of your custom assertion and the class needs to be exported.
To export it when packaging your application, add the `org.mule.custom` package to your `mule-artifact.json` ```json { "name": "mule-application", "minMuleVersion": "4.2.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.custom"] } } } ``` > [!NOTE] You only need to configure the package name in the `exportedPackages` collection. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [Assert That Event Processor](https://docs.mulesoft.com/munit/2.3/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/2.3/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/2.3/verify-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/2.3/fail-event-processor) --- product: MUnit version: 3.6 keywords: mule, esb, tests, qa, quality assurance, verify, functional testing, unit testing, stress testing --- # Run Custom Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The **Run Custom event processor** enables you to assert the Mule event content against a custom assertion. To add the **Run Custom processor** to your project, add the following dependency to your `pom.xml` file: ```xml com.mulesoft.munit munit-assert ${munit.version} test ``` You also have to add your custom assertion class to the `mule-artifact.json` file as an exported resource. For example, you can define the following assertion in Java: ```java package org.mule.custom; import org.mule.munit.assertion.api.MunitAssertion; import org.mule.munit.assertion.api.TypedValue; public class CustomAssertion implements MunitAssertion { @Override public void execute(TypedValue expression, Object params) throws AssertionError { (1) if (!"Hello World".equals(expression.getValue())) { (2) throw new AssertionError("Error the payload is incorrect"); } } } ```
1Implement the only method in the interface public void execute(TypedValue expression, Object params) throws AssertionError.
2Run your custom logic, which in this case validates that the message payload is Hello World.
The `CustomAssertion` class must be located in the scr/test/java directory. And use the **Run Custom Event Processor** to run it: ```xml ```
1The assertion field needs to have the canonical class name of your custom assertion and the class needs to be exported.
To export it when packaging your application, add the `org.mule.custom` package to your `mule-artifact.json` ```json { "name": "mule-application", "minMuleVersion": "4.2.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.custom"] } } } ``` > [!NOTE] You only need to configure the package name in the `exportedPackages` collection. ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [Assert That Event Processor](https://docs.mulesoft.com/munit/3.6/assertion-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/3.6/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/3.6/verify-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/3.6/fail-event-processor) --- product: MUnit version: 3.7 is-latest-version: true --- # Run MUnit Coverage Reports in Anypoint Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Run MUnit coverage reports in Anypoint Studio to see which flows and event processors your tests cover. These configurations apply only when running MUnit tests in Studio, not from Maven in a CI/CD environment. ## Enable Coverage Reports in Anypoint Studio You can see which flows, and which percentage of event processors in those flows the test covers by clicking on the Coverage button: ![MUnit Coverage tab highlighted in the MUnit section](/mulesoft/current/en-us/munit/latest/_images/using-munit-coverage-in-anypoint-studio.png) The Overall Coverage value represents the percentage of the Mule application event processors that the MUnit test executes. You can click **Generate Report** to get the report that details the flows and event processors in the Mule configuration files that are included in the MUnit test. ![Files included in the report highlighted](/mulesoft/current/en-us/munit/latest/_images/munit-coverage-report-in-anypoint-studio.png)
ColumnDescription

Resource

Name of the Mule configuration file

Containers

Number of flows inside the Mule configuration file

Weight

Percentage of your application in a configuration file
A percentage of the overall number of event processors in the documentation and the number of event processors in the Mule configuration file

Coverage

Percentage of event processors in the Mule configuration file that the MUnit test executes

Additionally, you can click on each **Resource** to get a more specific and granular report of the Event Processors executed in that resource: ![MUnit Coverage Report with the Granular report highlighted](/mulesoft/current/en-us/munit/latest/_images/munit-granular-coverage-report-in-anypoint-studio.png)
ColumnDescription

Name

Name of the container

Type

Type of the container

Covered Processors

Processors inside the container that are executed during the MUnit test

Processors

Total amount of processors inside the container

Coverage

Percentage of the event processors inside the container executed in the MUnit test

## Disable Coverage Reports If you choose so, you can disable the coverage calculation from your project run configuration so you test your flow without a coverage report. Right-click **Package Explorer** and choose **Run As** > **Run Configurations**. Select your MUnit run configuration file to access your suite configuration, and deselect the **Run coverage** option in your coverage settings. ![MUnit run and Run coverage highlighted](/mulesoft/current/en-us/munit/latest/_images/disable-munit-coverage-in-anypoint-studio.png) ## Exclude XML Files from MUnit Coverage Report You can exclude one or more XML files from an MUnit Coverage report when testing your application. For example, you can exclude a third-party XML file that does not comply with your quality standards to improve your final report score. 1. Go to the flow to change. 2. Click **Run** > **Run Configuration**. 3. Click the name of your project. 4. In the **Ignored files** section, click **Add**. ![Add Ignored File window highlighted in the Test tab](/mulesoft/current/en-us/munit/latest/_images/add-ignored-files.png) 5. Type the name of the XML file to exclude from the Coverage report and click **OK**. 6. Click **Apply** and **Run**. ## See Also - [MUnit Coverage Report](https://docs.mulesoft.com/munit/latest/munit-coverage-report) - [Configure MUnit Coverage in Maven](https://docs.mulesoft.com/munit/latest/coverage-maven-concept) --- product: MUnit version: 2.3 --- # Scaffold a Template for an MUnit Test from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use APIKit to automatically generate an empty structure for an MUnit test suite based on your API specification. Because your Mule project is generated using APIKit, you can use APIKit to automatically scaffold an empty MUnit test suite, based on the endpoints described in your API specification. Scaffolding does not generate the test itself, but generates a tool to help you start writing the test. To create this empty test suite: 1. Locate and right-click the APIKit router in your project. 2. Select **Create Test Suite for Project From API Specification**. --- product: MUnit version: 3.6 --- # Scaffold a Template for an MUnit Test from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use APIkit to automatically generate an empty structure for an MUnit test suite based on your API specification. Because your Mule project is generated using APIkit, you can use APIkit to automatically scaffold an empty MUnit test suite, based on the endpoints described in your API specification. Scaffolding does not generate the test itself, but generates a tool to help you start writing the test. To create this empty test suite: 1. Locate and right-click the APIkit router in your project. 2. Select **Create Test Suite for Project From API Specification**. --- product: MUnit version: 3.7 is-latest-version: true --- # Scaffold an MUnit Test Suite from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use APIkit to scaffold an empty MUnit test suite structure based on the endpoints defined in your API specification. Scaffolding generates the test suite file but not the individual tests, giving you a starting point for writing your MUnit tests. To create this empty test suite: 1. Locate and right-click the APIkit router in your project. 2. Select **Create Test Suite for Project From API Specification**. --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # Set Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Set Event Processor allows you to define a Mule Event. This message processor is normally used at the beginning of an MUnit test, to define the first message to send to the flow being tested. The example below shows how to define a simple payload of a Mule Message: ```xml ``` The set-event has the cloneOriginalEvent property. If set to true, it clones the event produced by your code. By default, the value of this property is false. The payload element in the Set Event processor has the following attributes:
Attribute NameDescription

value

Defines the value of the payload’s message.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can also use the Set Event processor to define message attributes and event variables: ```xml ``` All the properties have the same set of attributes:
Table 1. Property Message Processor’s Attributes
Attribute NameDescription

key

The key of the property being set.

value

The content of the property.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can define as many properties per each scope as you need for your test. > [!WARNING] If you define two properties in the same scope with the _same_ key, be aware that one > would end up overwriting the other. ## See Also - [Testing and Mocking Errors](https://docs.mulesoft.com/munit/2.3/test-mock-errors-cookbook) - [Fail Event Processor](https://docs.mulesoft.com/munit/2.3/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/2.3/run-custom-event-processor) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # Set Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Set Event Processor allows you to define a Mule Event. This message processor is normally used at the beginning of an MUnit test, to define the first message to send to the flow being tested. The example below shows how to define a simple payload of a Mule Message: ```xml ``` The set-event has the cloneOriginalEvent property. If set to true, it clones the event produced by your code. By default, the value of this property is false. The payload element in the Set Event processor has the following attributes:
Attribute NameDescription

value

Defines the value of the payload’s message.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can also use the Set Event processor to define message attributes and event variables: ```xml ``` All the properties have the same set of attributes:
Table 1. Property Message Processor’s Attributes
Attribute NameDescription

key

The key of the property being set.

value

The content of the property.

encoding

Defines the encoding of the message. This attribute is optional.

mediaType

Defines the mime type of the message. This attribute is optional.

You can define as many properties per each scope as you need for your test. > [!WARNING] If you define two properties in the same scope with the _same_ key, be aware that one > would end up overwriting the other. ## See Also - [Testing and Mocking Errors](https://docs.mulesoft.com/munit/3.6/test-mock-errors-cookbook) - [Fail Event Processor](https://docs.mulesoft.com/munit/3.6/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/3.6/run-custom-event-processor) --- product: MUnit version: 2.3 --- # Sleep Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Sleep processor allows you to pause your test for a specific time. You can use this processor to simulate a delay in the processing of the flow: ```xml ``` `time` Numerical value for the unit of time that your test waits before going to sleep. `timeUnit` The unit in which the `time` value is measured. Possible values are: - `MILLISECONDS` (default) - `MICROSECONDS` - `MINUTES` - `NANOSECONDS` - `SECONDS` - `HOURS` --- product: MUnit version: 3.6 --- # Sleep Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Sleep processor allows you to pause your test for a specific time. You can use this processor to simulate a delay in the processing of the flow: ```xml ``` `time` Numerical value for the unit of time that your test waits before going to sleep. `timeUnit` The unit in which the `time` value is measured. Possible values are: - `MILLISECONDS` (default) - `MICROSECONDS` - `MINUTES` - `NANOSECONDS` - `SECONDS` - `HOURS` --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # Spy Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The **Spy Processor** enables you to spy on what happens before and after an event processor is called. This enables you to validate, for example that a selected Mule Event reaches a specific event processor containing a specific payload or variable. Setting a spy processor tells MUnit to run a set of instructions (usually assertions or verifications) before and/or after the execution of the spied event processor. Assume that you have this configuration: ```xml ``` You can configure the spy processor to spy on any Http Request and assert that the payload is null before reaching the component, and not null after it’s been processed: ```xml ``` Or even to spy on any Http Request, whose path is '/my/api'. ```xml ``` As shown above, this processor enables you to define actions for before and after calling the spied processor. However, keep in mind that the spy processor does not modify the original Mule Event. If you set variables, attributes, or modify the payload inside a Spy, these changes won’t persist outside the processor. Overall, you should use the Spy processor to verify or assert. ## See Also - [MUnit Event Processors](https://docs.mulesoft.com/munit/2.3/event-processors) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # Spy Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The **Spy Processor** enables you to spy on what happens before and after an event processor is called. This enables you to validate, for example that a selected Mule Event reaches a specific event processor containing a specific payload or variable. Setting a spy processor tells MUnit to run a set of instructions (usually assertions or verifications) before and/or after the execution of the spied event processor. Assume that you have this configuration: ```xml ``` You can configure the spy processor to spy on any Http Request and assert that the payload is null before reaching the component, and not null after it’s been processed: ```xml ``` Or even to spy on any Http Request, whose path is '/my/api'. ```xml ``` As shown above, this processor enables you to define actions for before and after calling the spied processor. However, keep in mind that the spy processor does not modify the original Mule Event. If you set variables, attributes, or modify the payload inside a Spy, these changes won’t persist outside the processor. Overall, you should use the Spy processor to verify or assert. ## See Also - [MUnit Event Processors](https://docs.mulesoft.com/munit/3.6/event-processors) --- product: MUnit version: 2.3 --- # Storage Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Storage processors allows you to manage temporary storage during your tests. All storage is cleared as soon as the test ends. ## Store operation Stores the given data associated with the given key. If `value` not set, it defaults to the `payload`. ```xml #[person : { name: 'John', lastName: 'Smith' }] ``` ## Retrieve operation Retrieves the data associated with the given key ```xml ``` ## Remove operation Removes and returns the data associated with the given key ```xml ``` ## Clear stored data operation Clears all stored data ```xml ``` --- product: MUnit version: 3.6 --- # Storage Event Processors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Storage processors allows you to manage temporary storage during your tests. All storage is cleared as soon as the test ends. ## Store operation Stores the given data associated with the given key. If `value` not set, it defaults to the `payload`. ```xml #[person : { name: 'John', lastName: 'Smith' }] ``` ## Retrieve operation Retrieves the data associated with the given key ```xml ``` ## Remove operation Removes and returns the data associated with the given key ```xml ``` ## Clear stored data operation Clears all stored data ```xml ``` --- product: MUnit version: 2.3 --- # String Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## containsString(String) Checks that the expression contains the specified String. Example ```xml ``` ## startsWith(String) Checks that the expression starts with the specified String. Example ```xml ``` ## endsWith(String) Checks that the expression ends with the specified String. Example ```xml ``` ## isEmptyString() Checks that the expression has zero length. Example ```xml ``` ## isEmptyOrNullString() Checks that the expression is null, or has zero length. Example ```xml ``` ## equalToIgnoringCase(String) Checks that the expression is equal to the specified String, ignoring case. Example ```xml ``` ## equalToIgnoringWhiteSpace(String) Checks that the expression is equal to the string disregarding leading and trailing white spaces, and compression all inner white spaces to a single space. Example ```xml ``` ## stringContainsInOrder(Array) Checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/2.3/core-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/2.3/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/2.3/iterable-map-matchers-reference) --- product: MUnit version: 3.6 --- # String Matchers Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## containsString(String) Checks that the expression contains the specified String. Example ```xml ``` ## startsWith(String) Checks that the expression starts with the specified String. Example ```xml ``` ## endsWith(String) Checks that the expression ends with the specified String. Example ```xml ``` ## isEmptyString() Checks that the expression has zero length. Example ```xml ``` ## isEmptyOrNullString() Checks that the expression is null, or has zero length. Example ```xml ``` ## equalToIgnoringCase(String) Checks that the expression is equal to the specified String, ignoring case. Example ```xml ``` ## equalToIgnoringWhiteSpace(String) Checks that the expression is equal to the string disregarding leading and trailing white spaces, and compression all inner white spaces to a single space. Example ```xml ``` ## stringContainsInOrder(Array) Checks that the expression contains all of the specified substrings, regardless of the order of their appearance. Example ```xml ``` ## See Also - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) - [Core Matchers Reference](https://docs.mulesoft.com/munit/3.6/core-matchers-reference) - [Comparable Matchers Reference](https://docs.mulesoft.com/munit/3.6/comparable-matchers-reference) - [Iterable and Map Matchers Reference](https://docs.mulesoft.com/munit/3.6/iterable-map-matchers-reference) --- product: MUnit version: 3.7 is-latest-version: true --- # Test a Flow with a Scheduler Source in MUnit > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Test a Mule flow triggered by a Scheduler component in MUnit by enabling flow sources and using the verify-call processor to confirm the flow executes. Wrap verify-call inside an until-successful scope to handle timing variations in the Scheduler. Assume that you want to both test the following flow triggered by a Scheduler component and validate that your flow is being triggered correctly: ```xml ``` 1. Enable flow sources. Because MUnit does not start any of the flow sources (such as triggers or listeners), you must configure which flow sources start for your tests. In this example, you enable the flow that contains the Scheduler: ```xml ``` 2. Verify that flow execution is triggered by the Scheduler. To verify that the processors inside your flow are being triggered, use the `munit-tools:verify-call` processor. Wrap `munit-tools:verify-call` inside an `until-successful` to shorten processing time when the Scheduler is not operating when you want to test. The following example validates three times that the payload was executed at least once during the test. ```xml ``` ## See Also - [Enable Flow Sources](https://docs.mulesoft.com/munit/latest/enable-flow-sources-concept) - [Verify Event Processor](https://docs.mulesoft.com/munit/latest/verify-event-processor) --- product: MUnit version: 3.7 is-latest-version: true --- # Test and Mock Errors in MUnit > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Test and mock error handling in MUnit by configuring expected error types, using mock-when to simulate errors, or setting errors directly on the Mule event. Use these techniques to validate on-error-continue and on-error-propagate scopes in your flows. ## Expect an Error in Your Test During the execution of a flow, components may throw errors which might be expected for the use case being tested. In these cases, you want to specify that your test expects a particular error type or exception. For example, lets look at the following Mule code: ```xml ``` The key is taken from the payload and if the key is `null`, the Object Store connector will throw an error with `OS:INVALID_KEY` error type. The test to validate this case would be something like this: ```xml ``` ## Error Handlers Testing In many cases, errors are handled by the user. They may want to perform some actions when an error is thrown, and decide to propagate the error or continue with the flow’s execution. We can have different tests for each of the following possibilities: ### On Error Continue For example, lets look at the following mule code: ```xml ``` The `OS:INVALID_KEY` error is being handled and the execution continues with a specific payload. Since the error is not propagated, the execution resumes and the event can be verified: ```xml ``` As you can see, in this case you don’t have to expect the `OS:INVALID_KEY` error type. ### On Error Propagate For example, if the user’s code is the following: ```xml ``` The `OS:INVALID_KEY` error is being handled and the error `APP:NULL_KEY` is raised. Since the test will fail with the raised custom error type, the test should expect it: ```xml ``` ## Mock Errors When you don’t want to trigger manually an error on a component (like the examples above), but you only want to make the processor fail with a specific error, you can use the `error` parameter of the mock-when processor. For example, if the user’s code is the following: ```xml ``` and you want to make the `http:request` fail with an `HTTP:CONNECTIVITY` error and also check that the logger was actually executed, the test may look something like this: Mock Error with On Error Continue ```xml ``` If the On Error scope is an `on-error-propagate`, the verifications won’t be executed since the flow will propagate the error and fail, then the `validation` section of the test will be skipped. In this case the error could be caught with a try scope and then the verifications can be performed: Mock Error with On Error Propagate ```xml ``` ## Set an Event with an Error When extracting error handling logic into a separated flow or sub flow, the input event must have an error that can be used in the error handling logic. For example, lets look at the following mule code: ```xml ``` If you wish to test the subFlow independently, you will need to set an error in the event. The test may look something like this: Set Error in the Event ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/latest/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/latest/verify-event-processor) --- product: MUnit version: 2.3 --- # Test Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MUnit 2.x enables you to write MUnit test suites for your Mule applications that share their resources with a Mule domain, without you performing any additional configuration. To understand how this works, it is helpful to consider a specific scenario populated with actual values, and then use those values in steps that illustrate how to write such a test. ## Example Domain-Based Mule Application to Be Tested Consider a Mule domain called `domain-config` that defines a global configuration for the HTTP listeners of all the Mule applications within it: ##### Studio Visual Editor ![domain munit example](/mulesoft/current/en-us/munit/2.3/_images/domain-munit-example.png) ##### XML Editor Mule domain ```XML ``` Mule domain pom.xml file ```XML com.mycompany domain-config 1.0.0-SNAPSHOT mule-domain domain-config ``` Consider also a basic Mule application that returns the path being pinged: ##### Studio Visual Editor ![mule app domain listener](/mulesoft/current/en-us/munit/2.3/_images/mule-app-domain-listener.png) Note that this application does not define a HTTP listener global configuration because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). ![mule app domain set payload](/mulesoft/current/en-us/munit/2.3/_images/mule-app-domain-set-payload.png) ##### XML Editor ```XML ``` Note that this application does not define an `http:listener-config` global element because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). The application declares the domain dependency in its `pom.xml` file: ```XML ... com.mycompany domain-config 1.0.0 mule-domain provided ... ``` ## Write an MUnit Test of the Example Domain-Based Application Because the Mule domain is a dependency of the Mule application, MUnit can start the Mule domain to retrieve the necessary global elements configuration for the application that it’s testing. Assume an MUnit test to validate that the path being pinged is indeed the expected `/api` path: ##### Studio Visual Editor ![munit domain sample](/mulesoft/current/en-us/munit/2.3/_images/munit-domain-sample.png) 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, set up an Assert Equals\` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. ##### XML Editor ```XML (1) ``` 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, you decide to set up an `assert-equals` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. --- product: MUnit version: 3.6 --- # Test Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio MUnit 2.x enables you to write MUnit test suites for your Mule applications that share their resources with a Mule domain, without you performing any additional configuration. To understand how this works, it is helpful to consider a specific scenario populated with actual values, and then use those values in steps that illustrate how to write such a test. ## Example Domain-Based Mule Application to Be Tested Consider a Mule domain called `domain-config` that defines a global configuration for the HTTP listeners of all the Mule applications within it: ##### Studio Visual Editor ![domain munit example](/mulesoft/current/en-us/munit/3.6/_images/domain-munit-example.png) ##### XML Editor Mule domain ```XML ``` Mule domain pom.xml file ```XML com.mycompany domain-config 1.0.0-SNAPSHOT mule-domain domain-config ``` Consider also a basic Mule application that returns the path being pinged: ##### Studio Visual Editor ![mule app domain listener](/mulesoft/current/en-us/munit/3.6/_images/mule-app-domain-listener.png) Note that this application does not define a HTTP listener global configuration because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). ![mule app domain set payload](/mulesoft/current/en-us/munit/3.6/_images/mule-app-domain-set-payload.png) ##### XML Editor ```XML ``` Note that this application does not define an `http:listener-config` global element because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). The application declares the domain dependency in its `pom.xml` file: ```XML ... com.mycompany domain-config 1.0.0 mule-domain provided ... ``` ## Write an MUnit Test of the Example Domain-Based Application Because the Mule domain is a dependency of the Mule application, MUnit can start the Mule domain to retrieve the necessary global elements configuration for the application that it’s testing. Assume an MUnit test to validate that the path being pinged is indeed the expected `/api` path: ##### Studio Visual Editor ![munit domain sample](/mulesoft/current/en-us/munit/3.6/_images/munit-domain-sample.png) 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, set up an Assert Equals\` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. ##### XML Editor ```XML (1) ``` 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, you decide to set up an `assert-equals` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. --- product: MUnit version: 3.7 is-latest-version: true --- # Test MUnit Domain-Based Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Test Mule applications that share resources with a Mule domain using MUnit, without additional configuration. Follow a step-by-step example using a domain-based HTTP listener application to see how MUnit resolves shared global configurations automatically. ## Example Domain-Based Mule Application to Be Tested Consider a Mule domain called `domain-config` that defines a global configuration for the HTTP listeners of all the Mule applications within it: ##### Studio Visual Editor ![domain munit example](/mulesoft/current/en-us/munit/latest/_images/domain-munit-example.png) ##### XML Editor Mule domain ```XML ``` Mule domain pom.xml file ```XML com.mycompany domain-config 1.0.0-SNAPSHOT mule-domain domain-config ``` Consider also a basic Mule application that returns the path being pinged: ##### Studio Visual Editor ![mule app domain listener](/mulesoft/current/en-us/munit/latest/_images/mule-app-domain-listener.png) Note that this application does not define a HTTP listener global configuration because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). ![mule app domain set payload](/mulesoft/current/en-us/munit/latest/_images/mule-app-domain-set-payload.png) ##### XML Editor ```XML ``` Note that this application does not define an `http:listener-config` global element because it inherits it from its Mule domain (`HTTP_Listener_config_domain`). The application declares the domain dependency in its `pom.xml` file: ```XML ... com.mycompany domain-config 1.0.0 mule-domain provided ... ``` ## Write an MUnit Test for a Domain-Based Application Because the Mule domain is a dependency of the Mule application, MUnit can start the Mule domain to retrieve the necessary global elements configuration for the application that it’s testing. Assume an MUnit test to validate that the path being pinged is indeed the expected `/api` path: ##### Studio Visual Editor ![munit domain sample](/mulesoft/current/en-us/munit/latest/_images/munit-domain-sample.png) 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, set up an Assert Equals\` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. ##### XML Editor ```XML (1) ``` 1. Inside the `execution` scope, an HTTP requester sends a `GET` request to your application’s endpoint. 2. Inside the `validation` scope, you decide to set up an `assert-equals` processor to assert the response from the `execution` scope against your expected response. 3. To compare the response against the expected text, you must convert the payload to plain text. --- product: MUnit version: 3.7 is-latest-version: true --- # Test MUnit Flows with Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Configure environment-specific properties in MUnit tests by extracting HTTP configuration values into separate properties files for each environment. Use the MUnit Maven plugin to load the correct properties file when running tests against a QA or production API endpoint. Assume that you have the following flow that obtains data from an external API and you need to consume it from a test environment when executing your MUnit tests: ```xml ``` To consume data from a QA API endpoint when running your MUnit tests: 1. Extract the HTTP Configuration values into a properties file for each environment where you will execute the validations. Those properties files must go under `src/main/resources`: prod.properties ```xml http.host=dummy.restapiexample.com/api/v1/ http.port=80 ``` qa.properties ```xml http.host=dummy.qax.restapiexample.com/api/v1/ http.port=8081 ``` You can set a properties file for each one of your environments. 2. Use a `configuration-properties` global configuration in your configuration file to load environment properties from the previously created file: ```xml ``` 3. Replace the HTTP configuration with placeholders matching the variables defined in the properties file: ```xml ``` 4. Define an environment variable in the MUnit Maven plugin: ```xml ... qa ... ``` During the execution of the MUnit tests, MUnit loads the properties from the `qa` properties file and connects to your test environment. --- product: MUnit version: 3.7 is-latest-version: true --- # Test MUnit Processors That Use Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio When testing a processor that stores its result in a target variable in MUnit, assert the content of the stored variable rather than the payload. If you mock the processor, define the target variable value in the mock configuration. ## Example Test of a Target Variable from an HTTP Request Operation Consider a Mule application with the following XML configuration: ```xml ``` When the HTTP listener receives a request, the app makes an HTTP request and the processor stores the received HTTP response in a target variable called `httpResponse`. You can create an MUnit test to assert that the stored variable contains, for example, a `200` HTTP status code: ```xml ``` If you want to test the behavior of this app without making the HTTP request, you can mock the processor and the stored target variable. ### Mock a Processor That Stores Data in a Target Variable The following test mocks the HTTP request and the resulting target variable from the previous Mule app example, and then asserts that the stored HTTP status code is `200`: ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/latest/mock-event-processor) - [MUnit Matchers](https://docs.mulesoft.com/munit/latest/munit-matchers) --- product: MUnit version: 2.3 --- # Test Recorder in Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Test Recorder enables you to record a processing flow and then configure a unit test based on the captured event. The test recorder captures real data as it goes through your application in Anypoint Studio. By capturing the flow execution, MUnit can automatically generate an MUnit test so that you can configure the necessary mocks and assertions for your test. See [Recording a Test from an Exchange Example](https://docs.mulesoft.com/munit/2.3/test-recorder-examples) for a fully working example. ## Compatibility The following table describes the product versions required to use the Test Recorder.
ProductVersion

Anypoint Studio

7.5.0 and later

MUnit

2.2.5 and later

MUnit Anypoint Studio Plugin

2.5.0 and later

Mule runtime engine

4.3.0 and later

## Limitations The test recorder has the following limitations when you create MUnit tests: - You cannot create tests for flows with Mule errors raised inside the flow or already existing in the incoming event, even if an **on error continue** error handler controls them. - A recorded flow execution ends successfully, but the result does not reach its destination because the application is killed. - Your validations fail every time your test runs if you configure `spy` or `assert` processors to assert values for random data, time-dependent information (such as timestamps), or values resulting from parallel processes, because those values change in every execution. - Mocking values resulting from parallel processes causes a mixture of real and mocked data that compromises the execution of the processors that follow in your test. - Although the recorder supports data iteration in the flow, such as recursions or loops, it does not support cases in which the structure of the data being tested changes inside the iteration. - The recorder does not support mocking a message before or inside a `foreach` processor. - When using the Test Recorder to generate a test over your flow, you can only mock parameters included in your flow. You cannot mock parameters in sub-flows or in referenced flows through the Test Recorder UI. If you need to mock parameters in sub-flows of any other process in the project, you can modify the mocking component after creating the test. ## See Also - [Recording a Test from an Exchange Example](https://docs.mulesoft.com/munit/2.3/test-recorder-examples) - [Mocking a Message Before and Inside a Foreach Processor](https://docs.mulesoft.com/munit/2.3/mock-before-after-foreach-cookbook) --- product: MUnit version: 3.6 --- # Test Recorder in Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Test Recorder enables you to record a processing flow and then configure a unit test based on the captured event. The test recorder captures real data as it goes through your application in Anypoint Studio. By capturing the flow execution, MUnit can automatically generate an MUnit test so that you can configure the necessary mocks and assertions for your test. See [Recording a Test from an Exchange Example](https://docs.mulesoft.com/munit/3.6/test-recorder-examples) for a fully working example. ## Compatibility The following table describes the product versions required to use the Test Recorder.
ProductVersion

Anypoint Studio

7.5.0 and later

MUnit

2.2.5 and later

MUnit Anypoint Studio Plugin

2.5.0 and later

Mule runtime engine

4.3.0 and later

## Limitations The test recorder has the following limitations when you create MUnit tests: - You cannot create tests for flows with Mule errors raised inside the flow or already existing in the incoming event, even if an **on error continue** error handler controls them. - A recorded flow execution ends successfully, but the result does not reach its destination because the application is killed. - Your validations fail every time your test runs if you configure `spy` or `assert` processors to assert values for random data, time-dependent information (such as timestamps), or values resulting from parallel processes, because those values change in every execution. - Mocking values resulting from parallel processes causes a mixture of real and mocked data that compromises the execution of the processors that follow in your test. - Although the recorder supports data iteration in the flow, such as recursions or loops, it does not support cases in which the structure of the data being tested changes inside the iteration. - The recorder does not support mocking a message before or inside a `foreach` processor. - When using the Test Recorder to generate a test over your flow, you can only mock parameters included in your flow. You cannot mock parameters in sub-flows or in referenced flows through the Test Recorder UI. If you need to mock parameters in sub-flows of any other process in the project, you can modify the mocking component after creating the test. ## See Also - [Recording a Test from an Exchange Example](https://docs.mulesoft.com/munit/3.6/test-recorder-examples) - [Mocking a Message Before and Inside a Foreach Processor](https://docs.mulesoft.com/munit/3.6/mock-before-after-foreach-cookbook) --- product: MUnit version: 2.3 --- # Testing a Flow with a Scheduler Source > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Assume that you want to both test the following flow triggered by a Scheduler component and validate that your flow is being triggered correctly: ```xml ``` 1. Enable flow sources. Because MUnit does not start any of the flow sources (such as triggers or listeners), you must configure which flow sources start for your tests. In this example, you enable the flow that contains the Scheduler: ```xml ``` 2. Verify that flow execution is triggered by the Scheduler. To verify that the processors inside your flow are being triggered, use the `munit-tools:verify-call` processor. Wrap `munit-tools:verify-call` inside an `until-successful` to shorten processing time when the Scheduler is not operating when you want to test. The following example validates three times that the payload was executed at least once during the test. ```xml ``` ## See Also - [Enable Flow Sources](https://docs.mulesoft.com/munit/2.3/enable-flow-sources-concept) - [Verify Event Processor](https://docs.mulesoft.com/munit/2.3/verify-event-processor) --- product: MUnit version: 3.6 --- # Testing a Flow with a Scheduler Source > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Assume that you want to both test the following flow triggered by a Scheduler component and validate that your flow is being triggered correctly: ```xml ``` 1. Enable flow sources. Because MUnit does not start any of the flow sources (such as triggers or listeners), you must configure which flow sources start for your tests. In this example, you enable the flow that contains the Scheduler: ```xml ``` 2. Verify that flow execution is triggered by the Scheduler. To verify that the processors inside your flow are being triggered, use the `munit-tools:verify-call` processor. Wrap `munit-tools:verify-call` inside an `until-successful` to shorten processing time when the Scheduler is not operating when you want to test. The following example validates three times that the payload was executed at least once during the test. ```xml ``` ## See Also - [Enable Flow Sources](https://docs.mulesoft.com/munit/3.6/enable-flow-sources-concept) - [Verify Event Processor](https://docs.mulesoft.com/munit/3.6/verify-event-processor) --- product: MUnit version: 2.3 --- # Testing a Processor That Stores Data in a Target Variable > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When you test a processor that stores its result in a target variable, ensure that the assertions check the content of the stored variable. If you mock the processor, define a value for the target variable. ## Example Test of a Target Variable from an HTTP Request Operation Consider a Mule application with the following XML configuration: ```xml ``` When the HTTP listener receives a request, the app makes an HTTP request and the processor stores the received HTTP response in a target variable called `httpResponse`. You can create an MUnit test to assert that the stored variable contains, for example, a `200` HTTP status code: ```xml ``` If you want to test the behavior of this app without making the HTTP request, you can mock the processor and the stored target variable. ### Mock a Processor that Stores Data in a Target Variable The following test mocks the HTTP request and the resulting target variable from the previous Mule app example, and then asserts that the stored HTTP status code is `200`: ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) - [MUnit Matchers](https://docs.mulesoft.com/munit/2.3/munit-matchers) --- product: MUnit version: 3.6 --- # Testing a Processor That Stores Data in a Target Variable > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio When you test a processor that stores its result in a target variable, ensure that the assertions check the content of the stored variable. If you mock the processor, define a value for the target variable. ## Example Test of a Target Variable from an HTTP Request Operation Consider a Mule application with the following XML configuration: ```xml ``` When the HTTP listener receives a request, the app makes an HTTP request and the processor stores the received HTTP response in a target variable called `httpResponse`. You can create an MUnit test to assert that the stored variable contains, for example, a `200` HTTP status code: ```xml ``` If you want to test the behavior of this app without making the HTTP request, you can mock the processor and the stored target variable. ### Mock a Processor that Stores Data in a Target Variable The following test mocks the HTTP request and the resulting target variable from the previous Mule app example, and then asserts that the stored HTTP status code is `200`: ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor) - [MUnit Matchers](https://docs.mulesoft.com/munit/3.6/munit-matchers) --- product: MUnit version: 2.3 --- # Testing and Mocking Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Expect an Error in your Test During the execution of a flow, components may throw errors which might be expected for the use case being tested. In these cases, you want to specify that your test expects a particular error type or exception. For example, lets look at the following Mule code: ```xml ``` The key is taken from the payload and if the key is `null`, the Object Store connector will throw an error with `OS:INVALID_KEY` error type. The test to validate this case would be something like this: ```xml ``` ## Error Handlers Testing In many cases, errors are handled by the user. They may want to perform some actions when an error is thrown, and decide to propagate the error or continue with the flow’s execution. We can have different tests for each of the following possibilities: ### On Error Continue For example, lets look at the following mule code: ```xml ``` The `OS:INVALID_KEY` error is being handled and the execution continues with a specific payload. Since the error is not propagated, the execution resumes and the event can be verified: ```xml ``` As you can see, in this case you don’t have to expect the `OS:INVALID_KEY` error type. ### On Error Propagate For example, if the user’s code is the following: ```xml ``` The `OS:INVALID_KEY` error is being handled and the error `APP:NULL_KEY` is raised. Since the test will fail with the raised custom error type, the test should expect it: ```xml ``` ## Mock Errors When you don’t want to trigger manually an error on a component (like the examples above), but you only want to make the processor fail with a specific error, you can use the `error` parameter of the mock-when processor. For example, if the user’s code is the following: ```xml ``` and you want to make the `http:request` fail with an `HTTP:CONNECTIVITY` error and also check that the logger was actually executed, the test may look something like this: Mock Error with On Error Continue ```xml ``` If the On Error scope is an `on-error-propagate`, the verifications won’t be executed since the flow will propagate the error and fail, then the `validation` section of the test will be skipped. In this case the error could be caught with a try scope and then the verifications can be performed: Mock Error with On Error Propagate ```xml ``` ## Set an Event with an Error When extracting error handling logic into a separated flow or sub flow, the input event must have an error that can be used in the error handling logic. For example, lets look at the following mule code: ```xml ``` If you wish to test the subFlow independently, you will need to set an error in the event. The test may look something like this: Set Error in the Event ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/2.3/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/2.3/verify-event-processor) --- product: MUnit version: 3.6 --- # Testing and Mocking Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio ## Expect an Error in your Test During the execution of a flow, components may throw errors which might be expected for the use case being tested. In these cases, you want to specify that your test expects a particular error type or exception. For example, lets look at the following Mule code: ```xml ``` The key is taken from the payload and if the key is `null`, the Object Store connector will throw an error with `OS:INVALID_KEY` error type. The test to validate this case would be something like this: ```xml ``` ## Error Handlers Testing In many cases, errors are handled by the user. They may want to perform some actions when an error is thrown, and decide to propagate the error or continue with the flow’s execution. We can have different tests for each of the following possibilities: ### On Error Continue For example, lets look at the following mule code: ```xml ``` The `OS:INVALID_KEY` error is being handled and the execution continues with a specific payload. Since the error is not propagated, the execution resumes and the event can be verified: ```xml ``` As you can see, in this case you don’t have to expect the `OS:INVALID_KEY` error type. ### On Error Propagate For example, if the user’s code is the following: ```xml ``` The `OS:INVALID_KEY` error is being handled and the error `APP:NULL_KEY` is raised. Since the test will fail with the raised custom error type, the test should expect it: ```xml ``` ## Mock Errors When you don’t want to trigger manually an error on a component (like the examples above), but you only want to make the processor fail with a specific error, you can use the `error` parameter of the mock-when processor. For example, if the user’s code is the following: ```xml ``` and you want to make the `http:request` fail with an `HTTP:CONNECTIVITY` error and also check that the logger was actually executed, the test may look something like this: Mock Error with On Error Continue ```xml ``` If the On Error scope is an `on-error-propagate`, the verifications won’t be executed since the flow will propagate the error and fail, then the `validation` section of the test will be skipped. In this case the error could be caught with a try scope and then the verifications can be performed: Mock Error with On Error Propagate ```xml ``` ## Set an Event with an Error When extracting error handling logic into a separated flow or sub flow, the input event must have an error that can be used in the error handling logic. For example, lets look at the following mule code: ```xml ``` If you wish to test the subFlow independently, you will need to set an error in the event. The test may look something like this: Set Error in the Event ```xml ``` ## See Also - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/3.6/set-event-processor) - [Verify Event Processor](https://docs.mulesoft.com/munit/3.6/verify-event-processor) --- product: MUnit version: 2.3 --- # Testing with Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Assume that you have the following flow that obtains data from an external API and you need to consume it from a test environment when executing your MUnit tests: ```xml ``` To consume data from a QA API endpoint when running your MUnit tests: 1. Extract the HTTP Configuration values into a properties file for each environment where you will execute the validations. Those properties files must go under `src/main/resources`: prod.properties ```xml http.host=dummy.restapiexample.com/api/v1/ http.port=80 ``` qa.properties ```xml http.host=dummy.qax.restapiexample.com/api/v1/ http.port=8081 ``` You can set a properties file for each one of your environments. 2. Use a `configuration-properties` global configuration in your configuration file to load environment properties from the previously created file: ```xml ``` 3. Replace the HTTP configuration with placeholders matching the variables defined in the properties file: ```xml ``` 4. Define an environment variable in the MUnit Maven plugin: ```xml ... qa ... ``` During the execution of the MUnit tests, MUnit loads the properties from the `qa` properties file and connects to your test environment. --- product: MUnit version: 3.6 --- # Testing with Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Assume that you have the following flow that obtains data from an external API and you need to consume it from a test environment when executing your MUnit tests: ```xml ``` To consume data from a QA API endpoint when running your MUnit tests: 1. Extract the HTTP Configuration values into a properties file for each environment where you will execute the validations. Those properties files must go under `src/main/resources`: prod.properties ```xml http.host=dummy.restapiexample.com/api/v1/ http.port=80 ``` qa.properties ```xml http.host=dummy.qax.restapiexample.com/api/v1/ http.port=8081 ``` You can set a properties file for each one of your environments. 2. Use a `configuration-properties` global configuration in your configuration file to load environment properties from the previously created file: ```xml ``` 3. Replace the HTTP configuration with placeholders matching the variables defined in the properties file: ```xml ``` 4. Define an environment variable in the MUnit Maven plugin: ```xml ... qa ... ``` During the execution of the MUnit tests, MUnit loads the properties from the `qa` properties file and connects to your test environment. --- product: MUnit version: 3.7 is-latest-version: true --- # Use Utility Classes in MUnit Tests > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio Use custom Java utility classes located in `src/test/java` in your MUnit tests through DataWeave or the Java Module. Export the class package in your `mule-artifact.json` file to make it available during test execution. ```json { "minMuleVersion": "4.x.x", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["com.example.test"] } } } ``` For example, assume that you want to use in an MUnit test a `MyUtilClass.java` class located in `src/test/java/com/example/`: MyUtilClass ```java package com.example.test; public class Helper { public static long getCurrentMillis() { return System.currentTimeMillis(); } } ``` ## Invoke Your Java Class Using DataWeave To invoke static methods using DataWeave you must add the `java!` prefix to the package name of the class: Use a class in DataWeave ```xml ``` ## Invoke Your Java Class Using Java Module To invoke a custom Java class using Java Module: 1. Ensure that Java Module is in your project: Java Module dependency ```xml org.mule.module mule-java-module ${javaModule.version} mule-plugin test ``` 2. Use any of the Java Module’s operations. For this example, invoke a static method of a class: Use a class with the Java Module ```xml ``` --- product: MUnit version: 2.3 --- # Using Coverage in Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can run a coverage report from Anypoint Studio. The following configurations apply only when you execute your MUnit tests in Studio. They do not apply when running tests from Maven in a CI/CD environment. To run coverage reports from Maven see [Maven Configuration for Coverage](https://docs.mulesoft.com/munit/2.3/coverage-maven-concept). ## Enable Coverage Reports in Anypoint Studio You can see which flows, and which percentage of event processors in those flows the test covers by clicking on the Coverage button: ![MUnit Coverage tab highlighted in the MUnit section](/mulesoft/current/en-us/munit/2.3/_images/using-munit-coverage-in-anypoint-studio.png) The Overall Coverage value represents the percentage of the Mule application event processors that the MUnit test executes. You can click **Generate Report** to get the report that details the flows and event processors in the Mule configuration files that are included in the MUnit test. ![Files included in the report highlighted](/mulesoft/current/en-us/munit/2.3/_images/munit-coverage-report-in-anypoint-studio.png)
ColumnDescription

Resource

Name of the Mule configuration file

Containers

Number of flows inside the Mule configuration file

Weight

Percentage of your application in a configuration file
A percentage of the overall number of event processors in the documentation and the number of event processors in the Mule configuration file

Coverage

Percentage of event processors in the Mule configuration file that the MUnit test executes

Additionally, you can click on each **Resource** to get a more specific and granular report of the Event Processors executed in that resource: ![MUnit Coverage Report with the Granular report highlighted](/mulesoft/current/en-us/munit/2.3/_images/munit-granular-coverage-report-in-anypoint-studio.png)
ColumnDescription

Name

Name of the container

Type

Type of the container

Covered Processors

Processors inside the container that are executed during the MUnit test

Processors

Total amount of processors inside the container

Coverage

Percentage of the event processors inside the container executed in the MUnit test

## Disable Coverage Reports If you choose so, you can disable the coverage calculation from your project run configuration so you test your flow without a coverage report. Right-click **Package Explorer** and choose **Run As** > **Run Configurations**. Select your MUnit run configuration file to access your suite configuration, and deselect the **Run coverage** option in your coverage settings. ![MUnit run and Run coverage highlighted](/mulesoft/current/en-us/munit/2.3/_images/disable-munit-coverage-in-anypoint-studio.png) ## Exclude XML Files from MUnit Coverage Report You can exclude one or more XML files from an MUnit Coverage report when testing your application. For example, you can exclude a third-party XML file that does not comply with your quality standards to improve your final report score. 1. Go to the flow to change. 2. Click **Run** > **Run Configuration**. 3. Click the name of your project. 4. In the **Ignored files** section, click **Add**. ![Add Ignored File window highlighted in the Test tab](/mulesoft/current/en-us/munit/2.3/_images/add-ignored-files.png) 5. Type the name of the XML file to exclude from the Coverage report and click **OK**. 6. Click **Apply** and **Run**. ## See Also - [Coverage](https://docs.mulesoft.com/munit/2.3/munit-coverage-report) - [Maven Configuration for Coverage](https://docs.mulesoft.com/munit/2.3/coverage-maven-concept) --- product: MUnit version: 3.6 --- # Using Coverage in Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio You can run a coverage report from Anypoint Studio. The following configurations apply only when you execute your MUnit tests in Studio. They do not apply when running tests from Maven in a CI/CD environment. To run coverage reports from Maven see [Maven Configuration for Coverage](https://docs.mulesoft.com/munit/3.6/coverage-maven-concept). ## Enable Coverage Reports in Anypoint Studio You can see which flows, and which percentage of event processors in those flows the test covers by clicking on the Coverage button: ![MUnit Coverage tab highlighted in the MUnit section](/mulesoft/current/en-us/munit/3.6/_images/using-munit-coverage-in-anypoint-studio.png) The Overall Coverage value represents the percentage of the Mule application event processors that the MUnit test executes. You can click **Generate Report** to get the report that details the flows and event processors in the Mule configuration files that are included in the MUnit test. ![Files included in the report highlighted](/mulesoft/current/en-us/munit/3.6/_images/munit-coverage-report-in-anypoint-studio.png)
ColumnDescription

Resource

Name of the Mule configuration file

Containers

Number of flows inside the Mule configuration file

Weight

Percentage of your application in a configuration file
A percentage of the overall number of event processors in the documentation and the number of event processors in the Mule configuration file

Coverage

Percentage of event processors in the Mule configuration file that the MUnit test executes

Additionally, you can click on each **Resource** to get a more specific and granular report of the Event Processors executed in that resource: ![MUnit Coverage Report with the Granular report highlighted](/mulesoft/current/en-us/munit/3.6/_images/munit-granular-coverage-report-in-anypoint-studio.png)
ColumnDescription

Name

Name of the container

Type

Type of the container

Covered Processors

Processors inside the container that are executed during the MUnit test

Processors

Total amount of processors inside the container

Coverage

Percentage of the event processors inside the container executed in the MUnit test

## Disable Coverage Reports If you choose so, you can disable the coverage calculation from your project run configuration so you test your flow without a coverage report. Right-click **Package Explorer** and choose **Run As** > **Run Configurations**. Select your MUnit run configuration file to access your suite configuration, and deselect the **Run coverage** option in your coverage settings. ![MUnit run and Run coverage highlighted](/mulesoft/current/en-us/munit/3.6/_images/disable-munit-coverage-in-anypoint-studio.png) ## Exclude XML Files from MUnit Coverage Report You can exclude one or more XML files from an MUnit Coverage report when testing your application. For example, you can exclude a third-party XML file that does not comply with your quality standards to improve your final report score. 1. Go to the flow to change. 2. Click **Run** > **Run Configuration**. 3. Click the name of your project. 4. In the **Ignored files** section, click **Add**. ![Add Ignored File window highlighted in the Test tab](/mulesoft/current/en-us/munit/3.6/_images/add-ignored-files.png) 5. Type the name of the XML file to exclude from the Coverage report and click **OK**. 6. Click **Apply** and **Run**. ## See Also - [Coverage](https://docs.mulesoft.com/munit/3.6/munit-coverage-report) - [Maven Configuration for Coverage](https://docs.mulesoft.com/munit/3.6/coverage-maven-concept) --- product: MUnit version: 2.3 --- # Using Utility Classes From a Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When developing test cases, you might want to use custom Java classes located in `src/test/java`. You can use Java classes through DataWeave or through Java Module. When using custom classes, the package of the class must be exported in the `mule-artifact.json` file: ```json { "minMuleVersion": "4.x.x", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["com.example.test"] } } } ``` For example, assume that you want to use in an MUnit test a `MyUtilClass.java` class located in `src/test/java/com/example/`: MyUtilClass ```java package com.example.test; public class Helper { public static long getCurrentMillis() { return System.currentTimeMillis(); } } ``` ## Invoke Your Java Class Using DataWeave To invoke static methods using DataWeave you must add the `java!` prefix to the package name of the class: Use a class in DataWeave ```xml ``` ## Invoke Your Java Class Using Java Module To invoke a custom Java class using Java Module: 1. Ensure that Java Module is in your project: Java Module dependency ```xml org.mule.module mule-java-module ${javaModule.version} mule-plugin test ``` 2. Use any of the Java Module’s operations. For this example, invoke a static method of a class: Use a class with the Java Module ```xml ``` --- product: MUnit version: 3.6 --- # Using Utility Classes From a Test > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio When developing test cases, you might want to use custom Java classes located in `src/test/java`. You can use Java classes through DataWeave or through Java Module. When using custom classes, the package of the class must be exported in the `mule-artifact.json` file: ```json { "minMuleVersion": "4.x.x", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["com.example.test"] } } } ``` For example, assume that you want to use in an MUnit test a `MyUtilClass.java` class located in `src/test/java/com/example/`: MyUtilClass ```java package com.example.test; public class Helper { public static long getCurrentMillis() { return System.currentTimeMillis(); } } ``` ## Invoke Your Java Class Using DataWeave To invoke static methods using DataWeave you must add the `java!` prefix to the package name of the class: Use a class in DataWeave ```xml ``` ## Invoke Your Java Class Using Java Module To invoke a custom Java class using Java Module: 1. Ensure that Java Module is in your project: Java Module dependency ```xml org.mule.module mule-java-module ${javaModule.version} mule-plugin test ``` 2. Use any of the Java Module’s operations. For this example, invoke a static method of a class: Use a class with the Java Module ```xml ``` --- product: MUnit version: 2.3 keywords: munit, testing, unit testing --- # Verify Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Verify Event processor allows you to verify if a processor was called. For example, you can validate if a specific processor has been called with a particular set of attributes a specific number of times. When defining a verification, you are telling MUnit to fail a test if the verification is not successful. You can define verifications over any processor, even if you haven’t created a mock for it. ```xml ```
Attribute NameDescription

eventProcessor

Describes which event processor you want to mock. The description takes the form {name-space}:{event-processor-name}. It supports regular expressions.

times

(Default = 1.) Defines the verification as successful if the event processor was called N and only N number of times.

atLeast

Defines the verification as successful if the event processor was called a minimum of N number of times.

atMost

Defines the verification as successful if the event processor was called maximum of N number of times.

The attributes `times`, `atLeast`, `atMost`, are mutually exclusive. The `eventProcessor` attribute accepts regular expressions. For example, you can create the same verification as `.*:request` to verify for an event processor named request, disregarding which namespace the event processor belongs to. The regular expression language is the same as Java. ## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/2.3/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/2.3/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/2.3/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/2.3/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/2.3/mock-event-processor) --- product: MUnit version: 3.6 keywords: munit, testing, unit testing --- # Verify Event Processor > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ![logo acb active](/mulesoft/current/en-us/_/img/icons/anypoint-code-builder.svg "Anypoint Code Builder")Anypoint Code Builder ![logo studio active](/mulesoft/current/en-us/_/img/icons/studio.svg "Anypoint Studio")Anypoint Studio The Verify Event processor allows you to verify if a processor was called. For example, you can validate if a specific processor has been called with a particular set of attributes a specific number of times. When defining a verification, you are telling MUnit to fail a test if the verification is not successful. You can define verifications over any processor, even if you haven’t created a mock for it. ```xml ```
Attribute NameDescription

eventProcessor

Describes which event processor you want to mock. The description takes the form {name-space}:{event-processor-name}. It supports regular expressions.

times

(Default = 1.) Defines the verification as successful if the event processor was called N and only N number of times.

atLeast

Defines the verification as successful if the event processor was called a minimum of N number of times.

atMost

Defines the verification as successful if the event processor was called maximum of N number of times.

The attributes `times`, `atLeast`, `atMost`, are mutually exclusive. The `eventProcessor` attribute accepts regular expressions. For example, you can create the same verification as `.*:request` to verify for an event processor named request, disregarding which namespace the event processor belongs to. The regular expression language is the same as Java. ## See Also - [Assert That Event Processor](https://docs.mulesoft.com/munit/3.6/assertion-event-processor) - [Fail Event Processor](https://docs.mulesoft.com/munit/3.6/fail-event-processor) - [Run Custom Event Processor](https://docs.mulesoft.com/munit/3.6/run-custom-event-processor) - [Set Event Processor](https://docs.mulesoft.com/munit/3.6/set-event-processor) - [Mock When Event Processor](https://docs.mulesoft.com/munit/3.6/mock-event-processor)