Java – Grouping JUnit tests

javajunitunit testing

Is there any way to group tests in JUnit, so that I can run only some groups?

Or is it possible to annotate some tests and then globally disable them?

I'm using JUnit 4, I can't use TestNG.

edit: @RunWith and @SuiteClasses works great. But is it possible to annotate like this only some tests in test class? Or do I have to annotate whole test class?

Best Answer

Do you want to group tests inside a test class or do you want to group test classes? I am going to assume the latter.

It depends on how you are running your tests. If you run them by Maven, it is possible to specify exactly what tests you want to include. See the Maven surefire documentation for this.

More generally, though, what I do is that I have a tree of test suites. A test suite in JUnit 4 looks something like:

 @RunWith(Suite.class)
 @SuiteClasses({SomeUnitTest1.class, SomeUnitTest2.class})
 public class UnitTestsSuite {
 }

So, maybe I have a FunctionTestsSuite and a UnitTestsSuite, and then an AllTestsSuite which includes the other two. If you run them in Eclipse you get a very nice hierarchical view.

The problem with this approach is that it's kind of tedious if you want to slice tests in more than one different way. But it's still possible (you can for example have one set of suites that slice based on module, then another slicing on the type of test).