我设置了一个带有几个测试的类,而不是使用@Before我希望有一个在所有测试之前只执行一次的设置方法.Junit 4.8有可能吗?
Ale*_*exR 198
虽然我同意@assylias认为使用@BeforeClass是一种经典的解决方案,但并不总是方便.注释的方法@BeforeClass必须是静态的.对于需要测试用例的一些测试来说非常不方便.例如,基于Spring的测试@Autowired用于处理spring上下文中定义的服务.
在这种情况下,我个人使用setUp()带@Before注释的常规方法注释并管理我的自定义static标志:
private static boolean setUpIsDone = false;
.....
public void setUp() {
if (setUpIsDone) {
return;
}
// do the setup
setUpIsDone = true;
}
Run Code Online (Sandbox Code Playgroud)
ass*_*ias 85
您可以使用的BeforeClass注释:
@BeforeClass
public static void setUpClass() {
//executed only once, before the first test
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ian 27
JUnit 5现在有一个@BeforeAll注释:
表示应在当前类或类层次结构中的所有@Test方法之前执行带注释的方法; 类似于JUnit 4的@BeforeClass.这些方法必须是静态的.
JUnit 5的生命周期注释似乎终于搞定了!您可以猜测哪些注释无需查看(例如@BeforeEach @AfterAll)
当setUp()在测试类的超类中时,接受的答案可以修改如下:
public abstract class AbstractTestBase {
private static Class<? extends AbstractTestBase> testClass;
.....
public void setUp() {
if (this.getClass().equals(testClass)) {
return;
}
// do the setup - once per concrete test class
.....
testClass = this.getClass();
}
}
Run Code Online (Sandbox Code Playgroud)
这应该适用于单个非静态setUp()方法,但是我不能在tearDown()不偏离复杂反射的世界的情况下产生等价物......赏金指向任何可以做到的人!
JUnit 5 @BeforeAll 可以是非静态的,前提是测试类的生命周期是每个类,即用 a 注释测试类,@TestInstance(Lifecycle.PER_CLASS)然后就可以开始了