【问题标题】:Python Mock Function and Import MockPython Mock 函数和导入 Mock
【发布时间】:2017-10-24 14:01:36
【问题描述】:

在我的测试文件中,我想模拟一个包含在模块中的辅助函数。我能够“成功”(即没有编译或运行时错误,因为所有内容都已正确链接)模拟该函数,但该模拟不会渗透到我正在测试的类。

我已经研究过依赖注入,但我不确定如何注入我的模块,该模块目前只有一个模拟函数。最终我计划模拟几乎所有的功能;我只想让基线先工作。

这是我目前所拥有的

class FooTestCase(unittest.TestCase):

    @mock.patch('modules.MyHelperModule.helper_function')
    def test_simple(self, mock_hf):

        my_obj = MyObj()

        # internally, this class imports HelperModule 
        # and the method calls helper_function with 1
        my_obj.do_something()

        mock_hf.helper_function.assert_called_with(1)

        return

assert 命令失败并报告从未调用过该方法。我假设 mock 永远不会通过 my_obj。

我知道我可以在 MyObj 的 init 方法中创建一个标志,例如 testing=False 并相应地导入模块,但我如何才能导入仅在测试文件中模拟的模块?这是我现在正在考虑的方法,但我愿意接受其他能得到相同结果的实现。

针对丹尼尔·罗斯曼的评论,

在 MyOBJ 中,我有以下行

from modules.HelperModule import helper_function

但是,我得到了错误

ImportError: No module named modules

我的补丁线现在看起来像

@mock.patch('MyObj.modules.HelperModule.helper_function')

我们总是感谢任何帮助;谢谢!

【问题讨论】:

  • 阅读:Where to patch
  • 继续我自己的研究,我刚刚来到同一篇文章!谢谢你。你知道比文档更详细的版本吗?

标签: python python-2.7 unit-testing dependency-injection mocking


【解决方案1】:

我想问题是 mock_hf 不是你想要修补的。 尝试:

from unittest.mock import patch
class FooTestCase(unittest.TestCase):


def test_simple(self):
    with patch('modules.MyHelperModule.helper_function') as mock_hf:
        my_obj = MyObj()
        my_obj.do_something()
        mock_hf.assert_called_with(1)

【讨论】:

    【解决方案2】:

    正如 Daniel Roseman 对我的原始帖子的评论中提到的,问题在于我在哪里打补丁。

    我应该修补 MyObj.helper_function。此外,我在 init.py 中有一个 from MyObj import MyObj。这导致我只能在测试中引用 MyObj 类,但我需要覆盖整个文件的 helper_function。我不得不删除那条线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      相关资源
      最近更新 更多