如何解决的确-断言_with_其中AttributeError作为arg传递
我正在尝试对称为TargetException
的自定义异常进行单元测试。
这是我考试的相关部分:
mock_exception.assert_called_once_with(
id,AttributeError('invalidAttribute',)
)
这是测试失败消息:
File "/usr/local/lib/python2.7/site-packages/mock/mock.py",line 948,in assert_called_once_with
return self.assert_called_with(*args,**kwargs)
File "/usr/local/lib/python2.7/site-packages/mock/mock.py",line 937,in assert_called_with
six.raise_from(AssertionError(_error_message(cause)),cause)
File "/usr/local/lib/python2.7/site-packages/six.py",line 718,in raise_from
raise value
AssertionError: Expected call: TargetException(<testrow.TestRow object at 0x7fa2611e7050>,))
Actual call: TargetException(<testrow.TestRow object at 0x7fa2611e7050>,))
在“预期通话”和“动作通话”中,都存在相同的参数-至少对我来说是这样。
我需要以其他方式传递AttributeError来解决错误吗?
解决方法
问题是您比较了所包含异常的实例。由于在已测试函数中创建的AttributeError
实例与在测试中用于比较的实例不同,因此断言失败。
您可以做的是分别测试调用的参数,以确保它们的类型正确:
@mock.patch('yourmodule.TargetException')
def test_exception(mock_exception):
# call the tested function
...
mock_exception.assert_called_once()
assert len(mock_exception.call_args[0]) == 2 # shall be called with 2 positional args
arg1 = mock_exception.call_args[0][0] # first argument
assert isinstance(arg1,testrow.TestRow) # type of the first arg
... # more tests for arg1
arg2 = mock_exception.call_args[0][1] # second argument
assert isinstance(arg2,AttributeError) # type of the second arg
assert str(arg2) == 'invalidAttribute' # string value of the AttributeError
例如您分别测试类和参数的相关值。使用assert_called_with
仅适用于POD,或者已经知道被调用的实例(例如,是单例还是已知的模拟对象)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。