python - 如何将 mock_open 与 Python UnitTest 装饰器一起使用?

标签 python unit-testing mocking python-unittest python-mock

我有一个测试如下:

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__.openmock.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/

相关文章:

python - matplotlib,在图例标签上包含多个已定义变量

unit-testing - 将集合内容与 ScalaTest 进行比较

Python 单元测试模拟

c# - 更改字段值的 MOQ Mock void 方法

python - Django 模型不会保存

python - 无法在朴素贝叶斯中训练模型

python - 使用 pymc3 绘制 Gamma 分布拟合图

angularjs - Angular 自动模拟 Controller /服务依赖项

unit-testing - 如何对 Angular2 中的复选框进行单元测试

c# - 如何使用 Moq 模拟使属性在设置时抛出异常?