假设我有一个如下所示的方法:
def my_function(arg1, arg2):
if arg1:
raise RuntimeError('error message A')
else:
raise RuntimeError('error message B')
使用 python 的内置 unittets 库,有什么方法可以判断引发了哪个 RuntimeError
?我一直在做:
import unittest
from myfile import my_function
class MyTestCase(unittest.TestCase):
def test_my_function(self):
self.assertRaises(RuntimeError, my_function, arg1, arg2)
但这只是断言遇到了 RuntimeError
。我想知道遇到了哪个 RuntimeError
。检查实际的错误消息是我认为可以完成的唯一方法,但我似乎找不到任何也尝试断言错误消息的断言方法
最佳答案
单元测试用户:
在这种情况下,最好使用assertRaisesRegex .
Like
assertRaises()
but also tests that regex matches on the string representation of the raised exception. regex may be a regular expression object or a string containing a regular expression suitable for use byre.search()
.
所以,你可以使用:
self.assertRaisesRegex(RuntimeError, "^error message A$", my_function, arg1, arg2)
pytest 用户:
安装我的插件 pytest-raisin .然后你可以使用匹配的异常实例断言:
with pytest.raises(RuntimeError("error message A")):
my_function(arg1, arg2)
关于python - 使用 python unittest,我如何断言报告的错误给出了特定消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085998/