JUnit – Run test in a particular order

In JUnit, you can use @FixMethodOrder(MethodSorters.NAME_ASCENDING) to run the test methods by method name, in lexicographic order.

P.S Tested with JUnit 4.12

ExecutionOrderTest.java

package com.mkyong;

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

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

//Sorts by method name
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ExecutionOrderTest {

    @Test
    public void testB() {

        assertThat(1 + 1, is(2));

    }

    @Test
    public void test1() {

        assertThat(1 + 1, is(2));

    }

    @Test
    public void testA() {

        assertThat(1 + 1, is(2));

    }

    @Test
    public void test2() {

        assertThat(1 + 1, is(2));

    }

    @Test
    public void testC() {

        assertThat(1 + 1, is(2));

    }

}

Output, the above test methods will run in the following order :

test1
test2
testA
testB
testC
junit-execution-order
Note
JUnit only provides the method name as the execution order, and I think the JUnit team has no plan to develop other features to support the test execution order, because, unit test should run isolated and in ANY execution order.

If you really need the test execution order, try TestNG Dependency Test

References

  1. JUnit MethodSorters JavaDoc
  2. JUnit Test execution order

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
0 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
go http://gotme.ru Recent comment authors
newest oldest most voted
go http://gotme.ru
Guest
go http://gotme.ru

7K XixulpzI44FH5E

trackback
JUnit Tutorial

[…] Unit Test – What is Mocking? and Why?JUnit + Spring integration exampleJUnit – Categories TestJUnit – Assert if a property exists in a classJUnit – Run test in a particular order […]