python - 如何在保持自定义返回值的同时在模拟类上调用 assert_call_with?
问题描述
假设我想测试一个类B
并检查它的成员函数foo
是否正确实例化并调用了一个类A
并调用了bar
它的方法。当我模拟A
执行此操作时,如何检查它是否被正确调用,同时确保该方法仍按预期返回其参数B
?
这是我的尝试:
class B():
def __init__(self):
pass
def foo(self, arg):
a = A()
res = a.bar(arg)
print(f'foo called with {arg} and returned {res}')
assert res == arg
return res
class A():
def bar(self, arg):
return arg
import unittest
import unittest.mock
class MockA:
@unittest.mock.create_autospec
def bar(self, arg):
return arg
@unittest.mock.patch("__main__.A", new=MockA)
class MyTestCase(unittest.TestCase):
def test_case_1(self):
x = B().foo(1)
A.bar.assert_called_with(1)
def test_case_2(self):
x = B().foo(2)
A.bar.assert_called_with(2)
def test_case_3(self):
x = B().foo(3)
A.bar.assert_called_with(3)
MyTestCase().test_case_1()
这会因断言错误而失败,因为res
is <MagicMock name='mock()' id='140545715265664'>
。为什么autospec
装饰器MockA.bar
会以这种方式忽略返回值?
解决方案
推荐阅读
- sql-server - 使用存储过程连接到 SQL Server 后,我在“ExecuteNonQuery”上收到错误,为什么?
- c# - 我需要将小数或货币转换为 int
- python - Python - Selenium 无法处理警报
- arrays - Mongoose $push 用一个元素的新数组替换整个数组
- imagemagick - 使用 ImageMagick 比较像素移动但相似的图像
- objective-c - CGImageCreateWithImageInRect
- javascript - 动画结束后添加一个小反弹
- python - 在 Django 中,给定一个模型实例,我如何确定 ForeignKey 字段是否已完全水合?
- node.js - 如何使用 Azure Bot Channels Registration + Botbuilder SDK 捕获 Facebook messing_optins?
- postgresql - 如何在 postgreSQL 的新集群中添加数据库?