【发布时间】:2020-09-18 09:12:34
【问题描述】:
在一个测试套件中,我有一些代码组织如下,上下文是一些在退出 with 块时被删除的持久对象:
class Test(TestCase):
def test_action1(self):
with create_context() as context:
context.prepare_context()
context.action1()
self.assertTrue(context.check1())
def test_action2(self):
with create_context() as context:
context.prepare_context()
context.action2()
self.assertTrue(context.check2())
很明显,代码在两个测试中都有一些重复的设置样板,因此我想使用 setUp() 和 tearDown() 方法来分解该样板。
但我不知道如何提取 with_statement。我想出的是这样的:
class Test(TestCase):
def setUp(self):
self.context = create_context()
self.context.prepare_context()
def tearDown(self):
del self.context()
def test_action1(self):
self.context.action1()
self.assertTrue(self.context.check1())
def test_action2(self):
self.context.action2()
self.assertTrue(self.context.check2())
但我相信当测试失败时这并不等同,而且必须在 tearDown() 中明确删除也感觉不对。
将 with_statement 代码更改为 setUp() 和 tearDown() 样式的正确方法是什么?
【问题讨论】:
-
def Test(TestCase):是def还是class? -
@TomWojcik:
class,是伪代码,实际代码要复杂得多。我会解决的。
标签: python python-unittest with-statement