Junit - 运行一次设置方法 [英] Junit - run set up method once
问题描述
我设置了一个包含几个测试的类,而不是使用 @Before
我想要一个在所有测试之前只执行一次的设置方法.Junit 4.8 可以实现吗?
I set up a class with a couple of tests and rather than using @Before
I would like to have a setup method that executes only once before all tests. Is that possible with Junit 4.8?
推荐答案
尽管我同意 @assylias 的观点,即使用 @BeforeClass
是一种经典的解决方案,但它并不总是很方便.用 @BeforeClass
注释的方法必须是静态的.对于一些需要测试用例实例的测试来说非常不方便.例如,基于 Spring 的测试使用 @Autowired
来处理在 spring 上下文中定义的服务.
Although I agree with @assylias that using @BeforeClass
is a classic solution it is not always convenient. The method annotated with @BeforeClass
must be static. It is very inconvenient for some tests that need instance of test case. For example Spring based tests that use @Autowired
to work with services defined in spring context.
在这种情况下,我个人使用带有 @Before
注释的常规 setUp()
方法并管理我的自定义 static
(!) boolean
标志:
In this case I personally use regular setUp()
method annotated with @Before
annotation and manage my custom static
(!) boolean
flag:
private static boolean setUpIsDone = false;
.....
@Before
public void setUp() {
if (setUpIsDone) {
return;
}
// do the setup
setUpIsDone = true;
}
这篇关于Junit - 运行一次设置方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!