Does Junit5 give any guarantees regarding execution order of @Nested
classes defined within the same parent? With a trivial example I made, I notice the tests are executed in reverse order of declaration, but this behavior is neither documented (or is it?) nor consistent with how @Test
annotated methods are ordered by default.
It’s also quite annoying, because obviously I’d rather have a non-reverse order, if not a way of configuring it akin to @TestMethodOrder
.
import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; class NestedOrderTest { @Nested class NestedTest1 { @Test void testSuccess1() { System.out.println(1); } } @Nested class NestedTest2 { @Test void testSuccess2() { System.out.println(2); } } @Nested class NestedTest3 { @Test void testSuccess3() { System.out.println(3); } } }
Outputs:
3 2 1
Advertisement
Answer
The @Nested
class ordering feature has been added in Junit 5.8. At this point, the platform gives all the guarantees users may need.
import org.junit.jupiter.api.ClassOrderer; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestClassOrder; @TestClassOrder(ClassOrderer.OrderAnnotation.class) class OrderedNestedTestClassesDemo { @Nested @Order(1) class PrimaryTests { @Test void test1() { } } @Nested @Order(2) class SecondaryTests { @Test void test2() { } } }