: 在多模块项目中仅运行单个测试

有没有办法提供一些命令行参数,以便跳过除某个模块上的一个测试之外的所有测试?因此,每次需要运行另一个测试时,我都不需要更改 pom.xml?

例如,我希望在 TeamCity 上创建生成配置,并提供命令行参数以在某些模块中仅运行单个测试。下次我将需要更改它并运行另一个测试,以此类推。

也许这不是 CI 的用途,但仍然是。

70866 次浏览

I assume you've read the docs about running a single test under surefire? What they don't tell you is how to do that in a sub-module:

mvn test -Dtest=testname -pl subproject

Where subproject is the project containing that test. From the mvn man page:

-pl,--projects arg Comma-delimited list of specified reactor projects to build instead of all projects. A project can be specified by [groupId]:artifactId or by its relative path.

In case the module to be tested depends on other projects, solution works by changing commands as:

mvn test -DfailIfNoTests=false -Dtest=testname -pl subproject

Other answers I see are not fully complete, for projects that depend on other sub-modules to be built. One option is to run mvn install to have the required jars to be installed into ~/.m2/..., but that option is not very "clean".

Following command will build the sub-modules, and run only the test class that is specified. This is to be run at parent module level. Also, no need to specify sub-module name.

mvn test -DfailIfNoTests=false -Dtest={test_class_name} -am

As an aside, this can also be mvn clean test -Dfa...... I have a habit of always running clean when running tests.

References..
-am will make all the other sub-modules.
-DfailIfNoTests=false does not fail the entire process since we are not intending to run tests in other modules.
-pl option is not needed since -am is already building everything

FWIW, if you have a multi-module project, you can run all tests with this command at parent directory.

mvn test -pl subproject

And the subproject's name can be found by running the following command, usually in the form of group-id:artifact-id.

mvn help:active-profiles