Explain Codes LogoExplain Codes Logo

Run a single test method with maven

java
maven
testng
integration-tests
Nikita BarsukovbyNikita Barsukov·Jan 12, 2025
TLDR

Want to cooly run a specific test method with Maven? Boom. We have -Dtest=ClassName#methodName.

Example:

mvn -Dtest=MyClass#myMethod test

And, boom! Maven springs into action, your test method is under execution with the # selector.

Wildcards: The * magic

Forgotten the full name of that awfully long method? Maven's got your back! Leverage the * wildcard to match methods when life throws you a curveball.

R.Lee. Ermey's orders for all tests beginning with check:

mvn -Dtest=DataIntegrityTests#check* test

This way, our trusty pal Maven whisks all matching methods into the execution room. Hooray for teamwork! 👏

Multi-module projects? No problem!

In the labyrinth of multi-module projects, it makes a difference to run tests belonging to a specific module. Maven lets you do this with -pl and the module name.

mvn -pl my-module -Dtest=MyClass#myMethod test

Pass the correct module, or else Maven yells at you for not finding the test. 🗺️

Integration tests? Maven cares.

Working with integration tests? Maven adapts. The syntax gets a little facelift to accommodate Maven Failsafe, using -Dit.test instead of -Dtest.

Embrace the integration test life with:

mvn -pl my-module -Dit.test=MyIntegrationTest#methodToRun integration-test

Maven Surefire versions

The Maven Surefire version can be a game-changer. Some versions, like 2.7.3, allow multiple methods. If single tests give you the heebie-jeebies, downgrading to 2.11 might be your cup of tea.

With TestNG, run by group

Rolling with TestNG and neatly grouped test methods? Kudos to you! Now, make them run with this:

mvn -Dgroups=myGroup test

Maven and TestNG: adversaries or best buddies? Discuss. 🍵

Extra tips? Yes, please!

  • Watch the syntax like a hawk. Typos in class/method names spell trouble.
  • Patterns can save the day. Use them like your secret weapon in test execution.
  • Each module might need a unique Maven setting. Adapt and overcome!
  • Your test framework (JUnit or TestNG) must meet your testing conquests.

For slaying multiple methods in one swipe:

mvn -Dtest=MyClass#testOne+testTwo test

Look at you, multitasker!