要测试一个函数,当第一个参数不是整数类型时,我会引发异常:
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 异常?
经过一番研究,我知道应该可以使用上下文管理器一次性完成这两个测试,但我似乎无法维持生计......