How to run JUnit tests by category in Maven?

Ran picture Ran · Jun 23, 2010 · Viewed 58k times · Source

Using JUnit 4.8 and the new @Category annotations, is there a way to choose a subset of categories to run with Maven's Surefire plugin?

For example I have:

@Test
public void a() {
}

@Category(SlowTests.class)
@Test
public void b() {
}

And I'd like to run all non-slow tests as in: (note that the -Dtest.categories was made up by me...).

mvn test -Dtest.categories=!SlowTests // run non-slow tests
mvn test -Dtest.categories=SlowTests // run only slow tests
mvn test -Dtest.categories=SlowTests,FastTests // run only slow tests and fast tests
mvn test // run all tests, including non-categorized

So the point is that I don't want to have to create test suites (Maven just picks up all unit tests in the project which is very convenient) and I'd like Maven to be able to pick the tests by category. I think I just made up the -Dtest.categories, so I was wondering if there's a similar facility I can use?

Answer

dmcnelis picture dmcnelis · Feb 7, 2012

Maven has since been updated and can use categories.

An example from the Surefire documentation:

<plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.11</version>
      <configuration>
        <groups>com.mycompany.SlowTests</groups>
      </configuration>
</plugin>

This will run any class with the annotation @Category(com.mycompany.SlowTests.class)