Python Mock open调用无参数,assert_called_once_with断言失败如何解决?
Mock open断言失败问题解决方案
错误根因
- 补丁作用域不匹配:你通过
patch('task_4.open')打的补丁仅对task_4模块内部调用的open生效,你当前测试代码中直接调用的是Python内置全局open,没有被Mock覆盖,参数无法被记录,因此返回的实际调用显示为open()。 - Patch参数使用错误:你将实例化后的
mock_open()对象传给了new_callable参数,该参数预期接收可调用的类/函数而非实例,正确用法是将mock_open(无括号)传给new_callable,或是将实例化后的mock_open()传给new参数。
修正方案
方案1:测试当前作用域的open调用
如果要覆盖当前测试代码中的全局open,直接patch内置open即可:
import unittest from unittest.mock import patch, mock_open class TestFileData(unittest.TestCase): def test_save_data(self): m = mock_open() with patch('builtins.open', new=m) as f: with open('test.txt', 'w') as h: h.write('this is text') print(m.mock_calls) m.assert_called_once_with('test.txt', 'w')
方案2:测试task_4模块内部的open调用
如果你的测试目标是验证task_4模块内的逻辑是否正确调用了open,确保你调用的是task_4模块下的open,或是直接调用task_4中触发open调用的目标函数:
import unittest from unittest.mock import patch, mock_open import task_4 class TestFileData(unittest.TestCase): def test_save_data(self): m = mock_open() with patch('task_4.open', new=m) as f: # 示例:调用task_4中会触发open的目标函数即可,无需手动写open逻辑 # task_4.你的目标函数() with task_4.open('test.txt', 'w') as h: h.write('this is text') print(m.mock_calls) m.assert_called_once_with('test.txt', 'w')
内容的提问来源于stack exchange,提问作者method
相关产品推荐
相关产品推荐

