[英]How to create Extension which runs beforeAll only once for whole big class with many nested classes inside
Given my tested class with many nested classes inside: 给定我的测试类,其中包含许多嵌套类:
class TestWithManyNested {
@RegisterExtension
static MyExtension extension = new MyExtension();
@Nested
class Nested1 {
@Test
void nested1() {
}
}
@Nested
class Nested2 {
@Test
void nested2() {
}
}
}
Here is my simple extension: 这是我的简单扩展名:
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");
}
}
How can I run my TestWithManyNested
with MyExtension
which just run beforeAll
only once for whole test 我怎样才能运行我TestWithManyNested
与MyExtension
刚刚运行beforeAll
对整个测试只有一次
If you only want the class-level callbacks to execute for the outermost class, you can rewrite your extension as follows (checking that there is no "enclosing class" for the outermost 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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.