1

要测试一个函数,当第一个参数不是整数类型时,我会引发异常:

def magicWithInteger(integerA):
    if not isinstance(integerA, int):
        raise TypeError("argument should be integer type")

我使用 unittest assertRaises 和 assertEqual,所以我可以检查参数错误的函数是否引发 TypeError 以及 TypeError 是否真的吐出“参数应该是整数类型”

class test(unittest.TestCase):

    def test_magicWithInteger(self):
        self.assertRaises(TypeError, MagicWithInteger, "TEST")
        try:
            MagicWithInteger("TEST")
        except TypeError as error:
            self.assertEqual(str(error), "argument should be integer type")

两次调用该函数看起来有点傻,第一次检查它是否引发异常,第二次检查哪个 TypeError 异常?
经过一番研究,我知道应该可以使用上下文管理器一次性完成这两个测试,但我似乎无法维持生计......

4

1 回答 1

0

您可以使用with self.assertRaises(ExceptionType)上下文管理器来捕获异常。根据assertRaises 手册,您可以在块之后查看异常:如果您使用以下语法with为其命名,它似乎仍在范围内:as <name>

with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)

资料来源:docs.python.org

所以你的代码会变成:

class test(unittest.TestCase):
    def test_magicWithInteger(self):
        with self.assertRaises(TypeError) as cm:
            MagicWithInteger("TEST")
        self.assertEqual(str(cm.exception), "argument should be integer type")

PS:我不知道这一点,但该with声明并未在 Python 中引入新的范围。内部定义的变量与语句本身with在同一范围内。with请参阅https://stackoverflow.com/a/45100308/3216427到此特定点,对于实际创建范围的内容,请参阅https://stackoverflow.com/a/52992404/3216427

于 2021-04-27T12:30:32.893 回答