gpt4 book ai didi

java - 如何将实例传递给实现 BeforeAllCallback 的类

转载 作者:行者123 更新时间:2023-12-01 19:57:27 25 4
gpt4 key购买 nike

我想知道如何将类实例传递到 BeforeAllCallback 中。

测试:

@ExtendWith(MyExtension.class)
public class IntegrationSpec extends DockerComposeAbstraction {

Myobject example = new Myobject("something");

@Test
public void testSomething() {
//Test something
}
}

MyExtension 类:

public class MyExtension implements BeforeAllCallback {

public void beforeAll(ExtensionContext context) throws Exception {
System.out.println(instanceOfMyObject.getSomething);
}
}

我可以使用 junit5 @ExtendWith 注释来做到这一点吗?

最佳答案

首先,如果您希望在 beforeAll 方法中使用 example 对象,则该对象应该是静态字段。

然后你可以使用programatic extension registrationexample 保存为扩展程序中的字段:

public class IntegrationSpec extends DockerComposeAbstraction {

static Myobject example = new Myobject("something");

@RegisterExtension
static MyExtension myExtension = new MyExtension(example);

@Test
public void testSomething() {
//Test something
}
}

以及扩展名:

public class MyExtension implements BeforeAllCallback {

private Myobject example;

public MyExtension(Myobject example) {
this.example = example;
}

public void beforeAll(ExtensionContext context) throws Exception {
System.out.println(example.getSomething());
}
}

关于java - 如何将实例传递给实现 BeforeAllCallback 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com