1 min read

Revisiting Dynamic Ports in Mule 3

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:

  1. Find an unused port,
  2. Search the Mule config for a placeholder with the name ‘foo’, and then
  3. Replace the placeholder with the unused port number.
The newly assigned port no. is retrieved using the getNumber() method of the DynamicPort class. The complete example can be found on GitHub.

comments powered by Disqus