重要细节:有库导入,但是库没有安装,所以平时运行会返回
ModuleNotFoundError: No module named 'somemodule'
。
我们必须以某种方式模拟它,假设我们无法添加新文件或编辑
tested.py
文件
# tested.py
from somemodule import somelogger
class MyClass(object):
def __init__(self):
self.logger = somelogger()
def do_smth(self, message):
self.logger.log(message)
由于模块
somemodule
不存在,像@patch这样的常用解决方案不适合。
我需要模拟
somemodule
somelogger's
方法 log
使其执行简单的打印:
#tests.py
from tested import MyClass
def test_logging():
obj = MyClass()
obj.do_smth('some_message')
在控制台中:
some_message
我认为做到这一点的方法是使用此处描述的
unittest.mock.patch
方法:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch
在您的tests.py 文件中,创建一个模拟日志方法来执行打印。
# tests.py
from tested import MyClass
from unittest.mock import patch
def mocked_log(log_msg):
print(log_msg)
@patch('tested.somelogger.log')
def test_logging(mock_logger)
mock_logger.return_value = mocked_log
obj = MyClass()
obj.do_smth('some message')