SetUp() 和 setUpBefore Class() 之间的区别

在使用 JUnit 进行单元测试时,有两种类似的方法,setUp()setUpBeforeClass()。这些方法之间有什么区别?还有,tearDown()tearDownAfterClass()的区别是什么?

这是签名:

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}


@AfterClass
public static void tearDownAfterClass() throws Exception {
}


@Before
public void setUp() throws Exception {
}


@After
public void tearDown() throws Exception {
}
128676 次浏览

来自 Javadoc:

有时,一些测试需要共享计算开销很大的设置(比如登录到数据库)。虽然这可能会损害测试的独立性,但有时这是必要的优化。用 @BeforeClass注释 public static void no-arg 方法会导致它在类中的任何测试方法之前运行一次。超类的 @BeforeClass方法将在当前类之前运行。

@BeforeClass@AfterClass注释的方法将在测试运行期间精确地运行一次——在整个测试的开始和结束时,在运行其他任何东西之前。事实上,它们甚至在构造测试类之前就已经运行了,这就是为什么它们必须声明为 static

@Before@After方法将在每个测试用例之前和之后运行,因此在测试运行期间可能会多次运行。

假设你的类中有三个测试方法调用的顺序是:

setUpBeforeClass()


(Test class first instance constructed and the following methods called on it)
setUp()
test1()
tearDown()


(Test class second instance constructed and the following methods called on it)
setUp()
test2()
tearDown()


(Test class third instance constructed and the following methods called on it)
setUp()
test3()
tearDown()


tearDownAfterClass()

SetUpBeforeClass 在构造函数之后的任何方法执行之前运行(仅运行一次)

SetUp 在每个方法执行之前运行

TearDown 在每次方法执行后运行

TearDownAfterClass 在所有其他方法执行之后运行,是最后一个执行的方法(只运行一次解构器)

把“ BeforeClass”想象成您的测试用例的静态初始化器——用它来初始化静态数据——这些东西在您的测试用例中不会改变。您一定要小心不是线程安全的静态资源。

最后,使用“ AfterClass”注释方法来清理在“ BeforeClass”注释方法中进行的任何设置(除非它们的自毁性足够好)。

“之前”和“之后”用于单元测试特定的初始化。我通常使用这些方法来初始化/重新初始化依赖项的模拟。显然,此初始化并不特定于单元测试,而是通用于所有单元测试。