的确-断言_with_其中AttributeError作为arg传递

如何解决的确-断言_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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?