【发布时间】: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