javaunit-testingjunit5

JUnit 5: Specify execution order for nested tests


Is it possible to execute several nested tests in between of some other tests with a fixed execution order?

E.g.

@TestInstance(Lifecycle.PER_CLASS)
@TestMethodOrder(OrderAnnotation.class)
class MyTest {

    private State state = State.ZERO;

    @Test
    @Order(1)
    public void step1() throws IOException {
        state = State.ONE;
    }

    @Order(2)  // sth like this, however this annotation isn't allowed here
    @Nested
    class WhileInStateOne {

        @Test
        public void step2a {
            Assumptions.assumeTrue(state == State.ONE);

            // test something
        }

        @Test
        public void step2b {
            Assumptions.assumeTrue(state == State.ONE);

            // test something else
        }

    }

    @Test
    @Order(3)
    public void step3() throws IOException {
        state = State.THREE;
    }

}

I know, that unit tests should in general be stateless, however in this case I can save a lot of execution time if I can reuse the state in a fixed order.


Solution

  • Tests in nested classes are always executed after tests in the enclosing class. That cannot be changed.

    Methods in the same class can be ordered as follows:

    @TestMethodOrder(MethodOrderer.OrderAnnotation.class) 
    public class TestCode { 
      
        @Test
        @Order(1) 
        public void primaryTest() 
        {  
        } 
          
        @Test
        @Order(2) 
        public void secondaryTest() 
        { 
        } 
    } 
    

    Nested inner test classes can be ordered as follows:

     @TestClassOrder(ClassOrderer.OrderAnnotation.class)
     class OrderedNestedTests {
    
         @Nested
         @Order(1)
         class PrimaryTests {
              // @Test methods ...
         }
    
         @Nested
         @Order(2)
         class SecondaryTests {
            // @Test methods ...
         }
    

    }