临时禁用单个Python单元测试

195 投票
8 回答
106039 浏览
提问于 2025-04-15 18:02

在使用Python的unittest模块时,怎么能暂时禁用某些单元测试呢?

8 个回答

21

只需要在测试上方加上 @unittest.SkipTest 这个标记就可以了。

27

你可以使用装饰器来禁用测试。装饰器可以包裹一个函数,从而阻止googletest或Python单元测试去运行这个测试案例。

def disabled(f):
    def _decorator():
        print f.__name__ + ' has been disabled'
    return _decorator

@disabled
def testFoo():
    '''Foo test case'''
    print 'this is foo test case'

testFoo()

输出:

testFoo has been disabled
351

你可以使用 unittest.skip 这个装饰器来禁用单个测试方法或测试类。

@unittest.skip("reason for skipping")
def test_foo():
    print('This is foo test case.')


@unittest.skip  # no reason needed
def test_bar():
    print('This is bar test case.')

想了解其他选项,可以查看 跳过测试和预期失败 的文档。

撰写回答