问题

使用JUnit进行单元测试时,有两种类似的方法,setUp()setUpBeforeClass()。这些方法有什么区别?另外,779652558和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 {
}

#1 热门回答(186 赞)

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

#2 热门回答(15 赞)

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

最后,使用"AfterClass"注释方法清除你在"BeforeClass"注释方法中所做的任何设置(除非它们的自毁性能足够好)。

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


#3 热门回答(6 赞)

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

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

tearDown在每个方法执行后运行

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


原文链接