如果条件在setUp()中,则忽略测试

2 投票
2 回答
1821 浏览
提问于 2025-04-18 07:00

在Python的unittest库中,有两个函数叫做 setUptearDown,它们分别用于在测试之前和之后设置变量和其他东西。

我该如何在 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') 这行代码。

撰写回答