我想知道如何将一个类实例传递到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注释吗?

最佳答案

首先,如果要在example方法中使用它,则beforeAll对象应该是一个静态字段。

然后,您可以使用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/

10-12 05:12