我有一个测试如下:
import mock
# other test code, test suite class declaration here
@mock.patch("other_file.another_method")
@mock.patch("other_file.open", new=mock.mock_open(read=["First line", "Second line"])
def test_file_open_and_read(self, mock_open_method, mock_another_method):
self.assertTrue(True) # Various assertions.
我收到以下错误:
TypeError: test_file_open_and_read() takes exactly 3 arguments (2 given)
我正在尝试指定我想要其他文件的 __builtin__.open
用 mock.mock_open
模拟的方法而不是 mock.MagicMock
这是 patch
的默认行为装饰器。我该怎么做?
最佳答案
应该使用 new_callable
而不是 new
。也就是说,
@mock.patch("other_file.open", new_callable=mock.mock_open)
def test_file_open_and_read(self, mock_open_method):
# assert on the number of times open().write was called.
self.assertEqual(mock_open_method().write.call_count,
num_write_was_called)
请注意,我们将函数句柄 mock.mock_open
传递给 new_callable
,而不是结果对象。这允许我们执行 mock_open_method().write
以访问 write
函数,就像 mock_open
文档中的示例所示。
关于python - 如何将 mock_open 与 Python UnitTest 装饰器一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265706/