如何创建扩展,它只对整个大 class 内部有许多嵌套的 classes 运行一次 beforeAll

How to create Extension which runs beforeAll only once for whole big class with many nested classes inside

鉴于我测试的 class 内部有许多嵌套的 classes:

class TestWithManyNested {

    @RegisterExtension
    static MyExtension extension = new MyExtension();

    @Nested
    class Nested1 {

        @Test
        void nested1() {
        }
    }

    @Nested
    class Nested2 {

        @Test
        void nested2() {
        }
    }
}

这是我的简单扩展:

static class MyExtension implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {

        @Override
        public void beforeAll(ExtensionContext extensionContext) throws Exception {
            System.out.println("beforeAll");
        }

        @Override
        public void afterAll(ExtensionContext extensionContext) throws Exception {
            System.out.println("afterAll");
        }
    }

我如何 运行 我的 TestWithManyNestedMyExtension 整个测试 运行 beforeAll 只有一次

如果你只想对最外层class执行class级回调,你可以重写你的扩展如下(检查最外层没有"enclosing class" class).

static class MyExtension implements BeforeAllCallback, AfterAllCallback {

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        Class<?> testClass = extensionContext.getRequiredTestClass();
        if (testClass.getEnclosingClass() == null) {
            System.err.println("beforeAll: " + testClass.getName());
        }
    }

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
        Class<?> testClass = extensionContext.getRequiredTestClass();
        if (testClass.getEnclosingClass() == null) {
            System.err.println("afterAll: " + testClass.getName());
        }
    }
}