使用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 {
}
Run Code Online (Sandbox Code Playgroud)
And*_*yle 197
在@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()
Run Code Online (Sandbox Code Playgroud)
mad*_*ani 15
将"BeforeClass"视为测试用例的静态初始化程序 - 将其用于初始化静态数据 - 在测试用例中不会发生变化的事情.您肯定要小心非线程安全的静态资源.
最后,使用"AfterClass"注释方法清除您在"BeforeClass"注释方法中所做的任何设置(除非它们的自毁非常好).
"Before"和"After"用于单元测试特定的初始化.我通常使用这些方法来初始化/重新初始化我的依赖项的模拟.显然,这种初始化不是特定于单元测试,而是通用于所有单元测试.
setUpBeforeClass在构造函数之后的任何方法执行之前运行(仅运行一次)
setUp在每个方法执行之前运行
tearDown在每个方法执行后运行
在所有其他方法执行后运行tearDownAfterClass,是最后一个要执行的方法.(只运行一次解构器)
| 归档时间: |
|
| 查看次数: |
109839 次 |
| 最近记录: |