Junit - 运行设置方法一次 [英] Junit - run set up method once

查看:109
本文介绍了Junit - 运行设置方法一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个带有几个测试的类,而不是使用 @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()方法/ code>注释和管理我的自定义布尔标志:

In this case I personally use regular setUp() method annotated with @Before annotation and manage my custom boolean flag:

private static boolean setUpIsDone = false;
.....
public void setUp() {
    if (setUpIsDone) {
        return;
    }
    // do the setup
    setUpIsDone = true;
}

这篇关于Junit - 运行设置方法一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆