Python Mock没有断言调用 [英] Python Mock not asserting calls
本文介绍了Python Mock没有断言调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用模拟库在连接到外部资源并发送命令的程序中修补类.
I'm using the mock library to patch a class in a program that connects to a external resource and sends a dictioanry.
这种结构有点像...
The structure goes a litle like this...
code.py
def make_connection():
connection = OriginalClass(host, port)
connection.connect()
connection.send(param)
connection.close()
test.py
@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
code.make_connection()
mocked_conn.assert_called_with(host, port)
mocked_conn.connect.assert_called_once()
mocked_conn.send.assert_called_with(param)
第一个assert_Called_with可以正常工作,但是对模拟类的方法的调用 不及格.我试过使用patch.object作为装饰器也没有运气.
The first assert_called_with works perfectly, but the calls to method of the mocked class don't pass. I have tried using patch.object as a decorator also with no luck.
推荐答案
在第一次调用的返回值上调用connect()
和send()
方法.相应地调整测试:
The connect()
and send()
methods are called on the return value of the first call; adjust your test accordingly:
mocked_conn.return_value.connect.assert_called_once()
mocked_conn.return_value.send.assert_called_with(param)
我通常首先存储对实例"的引用:
I usually store a reference to the 'instance' first:
@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
code.make_connection()
mocked_conn.assert_called_with(host, port)
mocked_instance = mocked_conn.return_value
mocked_instance.connect.assert_called_once()
mocked_instance.send.assert_called_with(param)
这篇关于Python Mock没有断言调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文