White Box Testing
Test your code
   Home      JUnit4-Categories
 

JUnit4 Test Categories

Junit 4.8 introduced categories concept to categorize your test and execute  them selectively
 
From a given set of test classes, runs only the classes and methods that are annotated with either the category given with the @IncludeCategory annotation, or a subtype of that category. Note that, for now, annotating suites with @Category has no effect. Categories must be annotated on the direct method or class.
 
JUnit categories can be defined as classes or interfaces. Since categories work like marker It is better to define them as interface. Categories also support subtyping. In example IntegrationTests are subtype of FunctionalTests
 

public interface UnitTests {}

public interface FuntionalTests {}

interface IntegrationTests extends FuntionalTests{}

 
 
 
Particular test within a test class can be marked in a category by @Category annotation. See below example
 

package CategoryTest;

import static org.junit.Assert.fail;

import org.junit.Test;

import org.junit.experimental.categories.Category;

public class TestClass1 {

        @Test

        public void test1() {

          fail();

        }

 

        @Category(UnitTests.class)

        @Test

        public void test2() {

        }

       

        @Category(FuntionalTests.class)

        @Test

        public void test3() {

        }

       

        @Category(IntegrationTests.class)

        @Test

        public void test4() {

        }

      }

 
 
 
Particular test class can be marked in a category by @Category annotation. See below example
 
 
package CategoryTest;

import org.junit.Test;

import org.junit.experimental.categories.Category;

 

@Category({UnitTests.class, IntegrationTests.class})

public class TestClass2 {

  @Test

  public void test5() {

  }

}
 
 
 
 
Test category can be run by Categories runner classes with TestSuites. We can include and exclude particular category by @IncludeCategory and @ExcludeCategory annotations. See the behavior of below examples execution run
 

@RunWith(Categories.class)

@IncludeCategory(UnitTests.class)

@SuiteClasses( { TestClass1.class, TestClass2.class })

public class CategoryTest {

      //Execute test2 test5  

}

 

@RunWith(Categories.class)

@IncludeCategory(FuntionalTests.class)

@SuiteClasses( { TestClass1.class, TestClass2.class })

public class CategoryTest {

      //Execute test3 test4 test5

}

 

@RunWith(Categories.class)

@IncludeCategory(FuntionalTests.class)

@ExcludeCategory(IntegrationTests.class)

@SuiteClasses( { TestClass1.class, TestClass2.class })

public class CategoryTest {

      //Execute test3 only

}