Daniel Zapata wrote an interesting post about using dynamic ports when testing your Mule 3 application. Since then, subsequent releases of Mule included support for JUnit 4 which meant improved flexibility in terms of dynamic ports.
Before JUnit 4, an annoying problem with dynamic ports was that you were limited to property placeholder names having the following pattern: ‘port’ + n where n is an integer. For example:
Using JUnit 4, this problem is solved by leveraging the Rule annotation and the DynamicPort class. We’ll see how this is done. Let’s create a simple Mule config for testing dynamic ports out:
Notice the property placeholder “${foo}” in the port attribute. The next step is to create a test case for the config. The test case must extend org.mule.tck.junit4.FunctionalTestCase for this to work:
The port variable declaration is what we’re interested in. @Rule instructs JUnit to execute code in the DynamicPort object before running the test. The code will:
- Find an unused port,
- Search the Mule config for a placeholder with the name ‘foo’, and then
- Replace the placeholder with the unused port number.