Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose order to execute JUnit tests

I wanted to choose the order to execute the JUnit tests. I have 4 classes with several test methods in it, my goal is to execute, for instance, method Y of class A, then method X from class B, and finally method Z from class A.

Would you help please?

like image 261
Miguel Ribeiro Avatar asked Apr 19 '10 17:04

Miguel Ribeiro


3 Answers

In general, you can't specify the order that separate unit tests run in (though you could specify priorities in TestNG and have a different priority for each test). However, unit tests should be able to be run in isolation, so the order of the tests should not matter. This is a bad practice. If you need the tests to be in a specific order, you should be rethinking your design. If you post specifics as to why you need the order, I'm sure we can offer suggestions.

like image 110
Jeff Storey Avatar answered Oct 14 '22 17:10

Jeff Storey


From version 4.11 you can specify execution order using annotations and ordering by method name:

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

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyTest {

    @Test
    public void test1Create() {
        System.out.println("first");
    }

    @Test
    public void test2Update() {
        System.out.println("second");
    }
}

See JUnit 4.11 Release Notes

like image 33
Lorenzo Conserva Avatar answered Oct 14 '22 18:10

Lorenzo Conserva


The JUnit answer to that question is to create one test method like this:

  @Test public void testAll() {
       classA.y();
       classB.x();
       classA.z();
  }

That is obviously an unsatisfying answer in certain cases (where setup and teardown matter), but the JUnit view of unit testing is that if tests are not independant, you are doing something wrong.

If the above doesn't meet your needs, have a look at TestNG.

like image 23
Yishai Avatar answered Oct 14 '22 16:10

Yishai