如果条件在setUp()中,则忽略测试
在Python的unittest库中,有两个函数叫做 setUp
和 tearDown
,它们分别用于在测试之前和之后设置变量和其他东西。
我该如何在 setUp
中根据条件来运行或忽略一个测试呢?
2 个回答
2
与其在setUp
里检查,不如使用skipIf
这个装饰器。
@unittest.skipIf(not os.path.exists("somefile.txt"),
"somefile.txt is missing")
def test_thing_requiring_somefile(self):
...
skipIf
也可以用在类上,这样如果条件不满足,就可以跳过这个类里所有的测试。
@unittest.skipIf(not os.path.exists("somefile.txt"),
"somefile.txt is missing")
class TestStuff(unittest.TestCase):
def setUp(self):
...
def test_scenario_one(self):
...
def test_scenario_two(self):
...
3
你可以在 setUp()
这个函数里写 if cond: self.skipTest('reason')
这行代码。