-1

假设我有一个文件a.py名为

import mod1
mod1.a()

def b():
   print("hi")

现在,如果我想嘲笑乐趣,b()那么unittest.py同时在顶部有 import 语句

from a import b

在导入mod1.a()时将被调用。我如何模拟导入时发生的调用。

4

1 回答 1

2

考虑从模块顶层删除代码,将其移动到受保护的块中

if __name__ == '__main__':
    mod1.a()
    ... # the rest of your top level code

这样,受保护的代码不会在导入时执行,只有在直接运行时才会执行。

如果您仍然需要那里的电话并想模拟它,那很简单。有了这样的文件,

# mod.py

import mod1
mod1.a()

def b():
   print("hi")


# mod1.py

def a():
    print('Running a!')

# test_1.py
# Note: do not call unittest.py to a file.
# That is the name of a module from the Python stdlib,
# you actually need to use it and things will not work,
# because Python tries to load your file not the library you need.

from unittest.mock import patch

with patch('mod1.a') as mock_a:
    ... # configure mock_a here if there is a need, for example
        # to set a fake a call result
    import mod
    ... # the rest of your testing code. Use `mock_a` if you want to
        # inspect `a` calls.

外面的 withmod1.a不再被嘲笑。还有其他方法可以开始和停止模拟,您应该查看文档。在学习模拟之前,请确保您充分了解单元测试的工作原理以及如何组织测试。

于 2019-12-18T15:11:56.227 回答