您如何测试Python函数引起异常?

如何编写仅在函数未引起预期异常的状况下失败的单元测试? less


#1楼

看一下unittest模块的assertRaises方法。 函数


#2楼

使用unittest模块中的TestCase.assertRaises (或TestCase.failUnlessRaises ),例如: 单元测试

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)

#3楼

您的代码应遵循如下模式(这是一个unittest模块样式测试): 测试

def test_afunction_throws_exception(self):
    try:
        afunction()
    except ExpectedException:
        pass
    except Exception:
       self.fail('unexpected exception raised')
    else:
       self.fail('ExpectedException not raised')

在Python <2.7上,此构造对于检查预期异常中的特定值颇有用。 unittest函数assertRaises仅检查是否引起了异常。 spa


#4楼

我上一个答案中的代码能够简化为: 命令行

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction)

若是函数接受参数,则将它们传递给assertRaises,以下所示: code

def test_afunction_throws_exception(self):
    self.assertRaises(ExpectedException, afunction, arg1, arg2)

#5楼

我几乎在全部地方都使用doctest [1],由于我喜欢同时记录和测试函数的事实。 ip

看一下这段代码: 文档

def throw_up(something, gowrong=False):
    """
    >>> throw_up('Fish n Chips')
    Traceback (most recent call last):
    ...
    Exception: Fish n Chips

    >>> throw_up('Fish n Chips', gowrong=True)
    'I feel fine!'
    """
    if gowrong:
        return "I feel fine!"
    raise Exception(something)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

若是将此示例放在模块中并从命令行运行它,则将评估并检查两个测试用例。 get

[1] Python文档:23.2 doctest-测试交互式Python示例

相关文章
相关标签/搜索