Categories allows you to group tests together so we can run different categories of test in different test suites. For example, we can separate slow test from fast ones. We can include or exclude categories with specified annotations. To assign a test case or a method to one of those categories the @Category annotation is provided. I tried to show how to use categories based on official Junit release notes.

First we have to define our categories. FastTests and SlowTests.

FastTests.java
public interface FastTests { /* category marker */ }

SlowTests.java
public interface SlowTests { /* category marker */ }

A category can be either class or an interface. In below code we marked method b() of class A with @category annotation. Thus, we indicate that method b() belongs to category of SlowTests. In this way, we marked not only the whole class, we marked the test method individually.

A.java:

In below code class B is annotated with @Category annotation. Thus, this test class’s all test methods are included in this category. We see that a test class or a test method can be included more than one category.

B.java:

In below code you can see that our test suite name is SlowTestFirstSuite. Categories is also a kind of test suite. @IncludeCategory annotation indicates which categories will be included in execution. For below example, we included SlowTest category and it will be executed. Thus, test method b() of class A, method c() of class B will be executed.

SlowTestFirstSuite.java

In below code we annotated @ExcludeCategory that indicates which categories will be excluded from the execution. For below code sample, test method b() of class A will be executed but method a() of class A and method c() of class B will not run because they are excluded from the execution by @ExcluedeCategory annotation. Test method a() of class A will not be executed for both cases because it is not in any category.

Summary

  • You learned how to use and the meanings of JUnit categories.