单元 test.TestCase 中的测试设置和拆解
有时我们希望为每个要运行的测试准备一个上下文。setUp 方法在类中的每个测试之前运行。tearDown 在每次测试结束时运行。这些方法是可选的。请记住,TestCases 通常用于协作多重继承,因此你应该小心在这些方法中始终调用 super,以便调用基类的 setUp 和 tearDown 方法。TestCase 的基本实现提供了空的 setUp 和 tearDown 方法,因此可以在不引发异常的情况下调用它们:
import unittest
class SomeTest(unittest.TestCase):
def setUp(self):
super(SomeTest, self).setUp()
self.mock_data = [1,2,3,4,5]
def test(self):
self.assertEqual(len(self.mock_data), 5)
def tearDown(self):
super(SomeTest, self).tearDown()
self.mock_data = []
if __name__ == '__main__':
unittest.main()
请注意,在 python2.7 +中,还有 addCleanup 方法,它注册在运行测试后要调用的函数。与 tearDown 相反,tearDown 仅在 setUp 成功时被调用,即使在 setUp 中出现未处理的异常,也会调用通过 addCleanup 注册的函数。作为一个具体的例子,经常可以看到这种方法去除在测试运行时注册的各种模拟:
import unittest
import some_module
class SomeOtherTest(unittest.TestCase):
def setUp(self):
super(SomeOtherTest, self).setUp()
# Replace `some_module.method` with a `mock.Mock`
my_patch = mock.patch.object(some_module, 'method')
my_patch.start()
# When the test finishes running, put the original method back.
self.addCleanup(my_patch.stop)
以这种方式注册清理的另一个好处是,它允许程序员将清理代码放在安装代码旁边,并在子类将忘记在 tearDown 中调用 super 时保护你。