junit5 - @BeforeAll 是否需要实例化对象?

问题描述 投票:0回答:3

创建实例变量和在@BeforeAll注解标记的方法中创建成员变量有区别吗?

Public class Example1Test{

Lift testClass = null;

@BeforeAll
public void init() {
    testClass = new Lift();
}

@Test
...
}

VS

Public class Example2Test{
Lift testClass = new testClass;

@Test
...
}
java unit-testing junit junit5
3个回答
0
投票

@BoforeAll 用于确保被注解的方法应该在当前类中的所有@ParameterizedTest、@Test、@RepeatedTest 和@TestFactory 方法之前执行。因此,如果您希望此方法在任何其他方法之前运行,那么您必须对此进行注释。


0
投票

如果同时定义和初始化的对象(如代码片段中的 Lift 类)具有状态,最好在

@BeforeEach
中初始化它。每次测试之前都会清除对象的上下文。这使得您的测试彼此独立。


0
投票

抱歉,我不清楚第二个例子。 你的意思是

提升 testClass = new TestClass(); // 多态性,括号

或者:

Lift testClass = new Lift();

© www.soinside.com 2019 - 2024. All rights reserved.