Python unittest 测试用例捕获错误失败

标签 python unit-testing python-3.x

所以我有狗课:

class Dog:

def __init__(self, res):
    self._res = res


def error(self):
    raise IndexError

和单元测试:

class TestDog(unittest.TestCase):

def setUp(self):
    self.dog = Dog([1,2])

def testError(self):
    self.assertRaises(IndexError, self.dog.error())

为什么测试用例 testError 失败? self.dog.error() 应该会导致 IndexError 被引发,并且我相信 assertRaises 的格式正确。

感谢任何帮助,谢谢。

最佳答案

当 Python 运行 self.assertRaises(IndexError, self.dog.error()) 行时,它必须先计算 self.assertRaises 方法的参数将它们传递给它,因此它调用 self.dog.error() ,从而引发错误。这就是所有功能的工作原理。 self.assertRaises 的存在并不能阻止错误的发生。您应该调用 self.assertRaises(IndexError, self.dog.error) ,其中第二个参数现在是实际的函数/方法对象 self.dog.error ,而不需要还没打电话呢。 self.assertRaises 会为您调用它,并封装在 try/except 中,以便它可以正确执行测试。

或者:

with self.assertRaises(IndexError):
    self.dog.error()

关于Python unittest 测试用例捕获错误失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40604829/

相关文章:

python - 如何为 python 中的列中的每个唯一值创建一个虚拟对象

database - python 3 : Connect to Remote Postgres Database with SSL

Python:使用 'Null' 作为 mysql.connector 的端口参数

python - Django 2.0 与关键字参数 uidb64 的 NoReverseMatch

python - 使用 python 和 boto 的亚马逊 FPS 的最小示例?

reactjs - 如何使用 React 测试库编写测试来检查悬停是否更改了组件样式?

node.js - 尝试从 Jest 单元测试连接到 mongo 时超时

python-3.x - 是否有 python 3 命令来清除输出控制台?

python - Azure Flask Web 应用程序中的 Postgres

.net - 如何允许程序集(单元测试)访问另一个程序集的内部属性?