setUp()和setUpBeforeClass()之间的区别

时间:2010-08-05 08:51:02

标签: java junit

使用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 {
}

4 个答案:

答案 0 :(得分:194)

@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()

答案 1 :(得分:15)

将“BeforeClass”视为测试用例的静态初始化程序 - 使用它来初始化静态数据 - 在测试用例中不会发生变化的事情。您肯定要小心非线程安全的静态资源。

最后,使用“AfterClass”注释方法来清理你在“BeforeClass”注释方法中所做的任何设置(除非它们的自毁非常好)。

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

答案 2 :(得分:7)

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

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

每次执行方法后都会运行tearDown

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

答案 3 :(得分:4)

来自the Javadoc

  

有时,多个测试需要共享计算成本高昂的设置(例如登录数据库)。虽然这会损害测试的独立性,但有时这是必要的优化。使用public static void注释@BeforeClass无参数方法会导致它在类中的任何测试方法之前运行一次。超类的@BeforeClass方法将在当前类之前运行。