Main Tutorials

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 Author

author image
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

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
go http://gotme.ru
4 years ago

7K XixulpzI44FH5E