Execution order in junit

JUnit does not run the tests in the order they are written in a test class. So there is no guarantee of which tests will run in which order. But sometimes it is important to run the tests in typical order. JUnit 4.12+ provides annotation called as @FixMethodOrder. We can pass one parameter to this annotation called as MethodSorters.NAME_ASCENDING With this annotation parameter, tests are always run in ascending order of names of test methods. For example, in below test class, tests will always be run in below order.
 
abcTest()
pqrTest()
xyzTest()

Without @FixMethodOrder(MethodSorters.NAME_ASCENDING), there is no guarantee of order in which tests are executed.
 
package ordered_tests;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

/**
 * Created by Sagar on 30-04-2016.
 */

    @FixMethodOrder(MethodSorters.NAME_ASCENDING)
    public class OrderedTests {

        @Test
        public void abcTest() {
            System.out.println("ABC");
        }

        @Test
        public void pqrTest() {
            System.out.println("PQR");
        }

        @Test
        public void xyzTest() {
            System.out.println("XYZ");
        }

    }

Here is the output of above test.
 
ABC
PQR
XYZ    

Web development and Automation testing

solutions delivered!!