如何使用unittest断言?

时间:2019-04-08 17:36:43

标签: python testing assert python-unittest

假设我具有此功能:

def to_upper(var):
    assert type(var) is str, 'The input for to_upper should be a string'
    return var.upper()

还有一个用于使用unittest进行单元测试的文件:

class Test(unittest.TestCase):

    def test_1(self):
        -- Code here --


if __name__ == '__main__':
    unittest.main()

如何测试如果我调用to_upper(9)会引发断言错误?

2 个答案:

答案 0 :(得分:0)

您可以使用assertRaises(AssertionError)声明一个断言:

def test_1(self):
    with self.assertRaises(AssertionError):
        to_upper(9)

答案 1 :(得分:0)

断言用于调试。如果存在一些前提条件足以通过单元测试进行验证,请对其进行显式检查,并在失败的情况下酌情提出ValueErrorTypeError

在这种情况下,您实际上并不关心varstr;您只需要它具有upper方法即可。

def to_upper(var):
    try:
        return var.upper()
    except AttributeError:
        raise TypeError("Argument has no method 'upper'")
相关问题