Monday, 12 September 2016

Junit Test Suits and Test Execution Order


When you have large number test classes and you want to combine then and manage them the you can create a Test Suit. Execution of test case means execution of all test classes inside the Suite as per specified order.

The following example gives outline of Suit class. It contains 3 test classes FirstTestClass and SecondTestClass. You can add as many test classes as you want.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
                FirstTestClass.class,
                SecondTestClass.class,
                ThirdTestClass.class })

public class AllTests {

}   

Test Execution Order within Class - Junit Assumes that the test cases written inside class and independent and can be executed randomly.  But in case if you have to define the flow of Junit test cases within a class then there is annotations @FixMethodOrder which you can use. Consider below example with Class MyTests with Test Cases BTest(), ATest() and CTest() and we can define the order of execution as per method name ascending order alphabetically.

In following example the order of execution will be  -
1. ATest()
2. BTest()
3. CTest()



@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTests {

@Test
public void BTest()
{
}

@Test
public void ATest()
{
}

@Test
public void CTest()
{
}

}

0 comments:

Post a Comment