Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Sebastian S Avatar asked Apr 02 '19 13:04

Sebastian S


People also ask

How do you write JUnit test cases for nested methods?

All nested test classes must be annotated with the @Nested annotation. The depth of the test class hierarchy is not limited in any way. A nested test class can contain test methods, one @BeforeEach method, and one @AfterEach method. By default, we cannot add the @BeforeAll and @AfterAll methods to a nested test class.

Does JUnit 5 run tests in parallel?

Once parallel test execution property is enabled, the JUnit Jupiter engine will execute tests in parallel according to the provided configuration with declared synchronization mechanisms.

What is the order of execution of annotation in JUnit?

JUnit execution sequence Execution sequence with the same annotation is in order of appearance in the file. Methods annotated with @BeforeClass and @AfterClass – those public static void methods which do some setup/teardown just once before and after all tests have started/passed.


1 Answers

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

Ordering of test methods only applies to methods within a single test class.

like image 200
Sam Brannen Avatar answered Oct 01 '22 23:10

Sam Brannen