【发布时间】:2020-10-20 14:54:50
【问题描述】:
我正在使用 Python 3.8。我有一个带有成员字段的类...
class AbcServiceBus:
def __init__(self, ...):
...
self._service_bus = AzureServiceBus()
def send_insert_notification(self, record_id):
message_json = {'ids': [record_id]}
self._service_bus.send_topic_message(
namespace_name=self._namespace,
topic_name=self._topic_name,
message_json=message_json
)
return True
我想模拟成员字段的“send_topic_message”方法。我尝试了以下
from unittest import mock
...
sb = AbcServiceBus(device)
with mock.patch('common.azure_service_bus.AzureServiceBus.send_topic_message') as send_topic_message_mock:
sb.send_insert_notification(record_id)
send_topic_message_mock.assert_called_with(
sb._namespace,
sb._topic_name,
{'ids': [record_id]}
)
但这继续调用类的真实方法,而不是我设置的模拟。模拟成员字段方法的正确方法是什么?
【问题讨论】:
-
看起来你没有修补
AzureServiceBuswhere it is used - 你需要修补using_module.AzureServiceBus.send_topic_message。
标签: python-3.x unit-testing mocking pytest python-mock