Monthly Archives: March 2016

JUnit categories

When we ask JUnit to run the tests in specific class, all tests are executed in that class. What if want to run specific tests?

That’s when JUnit categories come in to picture. With JUnit categories we can tag tests to specific category and then execute tests from that specific categories.

Maven and Gradle also allows us to configure the JUnit to run tests from specific categories.

Let say you want to run the tests with category SanityTests, then create an interface with name SanityTests.

public interface SanityTests { }

After that create test class as shown in below example. Note how we have tagged a method to be of category – SanityTests

package junit_tests;

import static org.junit.Assert.*;

import junit_categories.SanityTests;
import org.junit.*;
import org.junit.experimental.categories.Category;
/**
* Created by Sagar on 28-03-2016.
*/
public class TestClass {

@BeforeClass
public static void initialize(){
//This method will be called once before all tests are run in this class
//do stuff here which you want to do only once for all test methods
//in this class like setting up environment, allocating resources
System.out.println("Before Class method");
}

@Before
public void initMethod(){
//This method will be called once before each test is run
//In this method, do stuff which you want to do before each test
System.out.println("Before each test");
}

@Category(SanityTests.class)
@Test
public void test1(){
System.out.println("**Running test from sanity**");
assertTrue("Checking simple condition",1==1);
}

@Test
public void test2(){
System.out.println("Running test2");
Assert.assertTrue("Checking other condition",1==2);
}

@After
public void cleanUpMethod(){
//This method will be called once after each test is run
//In this method, do stuff which you want to do after each test
System.out.println("After each test");
}

@AfterClass
public static void cleanUp(){
//This method will be called once after all tests are run in this class
//do stuff here which you want to do only once for all test methods
//in this class like cleaning environment, releasing resources
System.out.println("After Class method");
}
}

After that create a class as shown in below example. Note that we are using @RunWith annotation which tells JUnit that we are trying to execute the tests of specific category.

package junit_tests;

import junit_categories.SanityTests;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Categories.class)
@Categories.IncludeCategory(SanityTests.class)
@Suite.SuiteClasses( {TestClass.class})
public class CategoryTests {
}