Sebastian S
Sebastian S

Reputation: 4712

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.

Upvotes: 9

Views: 4776

Answers (2)

Sam Brannen
Sam Brannen

Reputation: 31197

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 ...
     }

}

Upvotes: 14

humperei
humperei

Reputation: 31

You can now use @TestClassOrder(ClassOrderer.OrderAnnotation.class) on your main class.

Upvotes: 1

Related Questions