在使用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 {
}
发布于 2010-08-05 16:54:12
带@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()
发布于 2010-08-05 17:32:36
可以将"BeforeClass“看作测试用例的静态初始化器--使用它来初始化静态数据--这些数据在测试用例中是不会改变的。你一定要小心那些不是线程安全的静态资源。
最后,使用带"AfterClass“注释的方法清理您在带"BeforeClass”注释的方法中所做的任何设置(除非它们的自毁足够好)。
"Before“和"After”用于单元测试特定的初始化。我通常使用这些方法来初始化/重新初始化我的依赖项的mock。显然,这种初始化不是特定于单元测试的,而是通用于所有单元测试的。
发布于 2010-08-05 16:55:24
setUpBeforeClass在任何方法执行之前运行,紧跟在构造函数之后(只运行一次)
setUp在每个方法执行之前运行
tearDown在每次方法执行后运行
tearDownAfterClass在所有其他方法执行之后运行,是最后一个要执行的方法。(只运行一次解构函数)
https://stackoverflow.com/questions/3413092
复制相似问题