A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():
@classmethod
def setUpClass(cls):
...
以及:
setUp()
Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.
Python框架中的
setUp()
和setUpClass()
有什么区别?主要的区别(正如本杰明·霍奇森在回答中指出的那样)是
setUpClass
只调用一次,即在所有测试之前,而setUp
则在每次测试之前立即调用。(注意:这同样适用于其他xUnit测试框架中的等效方法,而不仅仅是Python的unittest
)从
unittest
documentation:以及:
为什么要用一种方法来处理安装程序?
这部分问题尚未得到回答。根据我对Gearon回答的评论,
setUp
方法用于所有测试通用的fixture元素(以避免在每个测试中重复该代码)。我发现这通常是有用的,因为消除重复(通常)可以提高可读性并减少维护负担。setUpClass
方法适用于昂贵的元素,您宁愿只做一次,例如打开数据库连接、打开文件系统上的临时文件、加载共享库进行测试等。在每次测试之前执行这些操作会使测试套件过慢,因此我们只在所有测试之前执行一次。这是测试独立性的一个轻微退化,但在某些情况下是一个必要的优化。可以说,不应该在单元测试中做这样的事情,因为通常可以模拟数据库/文件系统/库/任何东西,而不使用真正的东西。因此,我发现很少需要setUpClass
。然而,当需要测试上述示例(或类似示例)时,它是有用的。当您的类中有多个测试方法时,差异就会显现出来。
setUpClass
和tearDownClass
对整个类运行一次;setUp
和tearDown
在每个测试方法之前和之后运行。例如:
运行此测试时,它会打印:
(当测试通过时,
.
点是unittest
的默认输出)观察setUp
和tearDown
在test1
和test2
前后出现,而setUpClass
和tearDownClass
在整个测试用例的开始和结束时只出现一次。相关问题 更多 >
编程相关推荐