python - Python unittest补丁模拟实体类
问题描述
我有一个类,我想在我的单元测试中修补。
class OriginalClass():
def method_a():
# do something
def method_b():
# do another thing
现在我创建了另一个类来修补它,所以修补它的代码就像
class MockClass(OriginalClass):
def method_a():
# This will override the original method and return custom response for testing.
patcher = patch('OriginalClass', new=MockClass)
mock_instance = patcher.start()
这完全符合我的要求,我可以返回单元测试所需的任何响应。
现在这个问题是当我想验证在单元测试中使用正确的参数调用方法时。我试过了
mock_instance.method_a.assert_called_once()
但它因错误而失败AttributeError: 'function' object has no attribute 'assert_called_once'
。
如何在这里测试方法调用?
解决方案
我认为wraps
在这里有用:
from unittest.mock import patch
class Person:
name = "Bob"
def age(self):
return 35
class Double(Person):
def age(self):
return 5
with patch('__main__.Person', wraps=Double()) as mock:
print(mock.name) # mocks data
print(mock.age()) # runs real methods, but still spies their calls
mock.age.assert_not_called()
输出:
<MagicMock name='Person.name' id='139815250247536'>
5
...
raise AssertionError(msg)
AssertionError: Expected 'age' to not have been called. Called 1 times.
Calls: [call()].
推荐阅读
- python - 如何在 matplotlib 中显示“摆动”堆叠图的宽度值
- c - 打印 10 的幂 - C 中的 Printf
- javascript - 同步加载谷歌字体
- sql - 如何使用游标将数据插入到 Oracle 中具有包含 XML 类型数据的单列的新表中?
- laravel - Laravel Json 响应未按预期工作
- jenkins - 如何从 Jenkins 管道作业中的凭据参数获取密码
- openstack - openstack如何解决0个dhcp代理活动
- python - 多个输入文件作为 biopython AlignIO 的单个文件输出
- mysql - 按部分(MySQL)从数据库中选择对象的最佳方法是什么?
- python - 用户警告:Pandas 不允许通过新属性名称创建列 -