问题描述
模块A
的顶部包含import B
.但是在测试条件下,我想模拟 B
在A
(模拟A.B
),并完全避免导入B
.
Module A
includes import B
at its top. However under test conditions I'd like to mock B
in A
(mock A.B
) and completely refrain from importing B
.
实际上,不是故意在测试环境中安装了B
.
In fact, B
isn't installed in the test environment on purpose.
A
是被测单元.我必须导入其所有功能的A
. B
是我需要模拟的模块.但是,如果A
所做的第一件事是导入B
,如何在A
中模拟B
并阻止A
导入真实的B
?
A
is the unit under test. I have to import A
with all its functionality. B
is the module I need to mock. But how can I mock B
within A
and stop A
from importing the real B
, if the first thing A
does is import B
?
(未安装B的原因是我使用pypy进行了快速测试,不幸的是B尚未与pypy兼容.)
(The reason B isn't installed is that I use pypy for quick testing and unfortunately B isn't compatible with pypy yet.)
这怎么办?
推荐答案
您可以在导入A
之前将其分配给sys.modules['B']
以获取所需的内容:
You can assign to sys.modules['B']
before importing A
to get what you want:
test.py :
import sys
sys.modules['B'] = __import__('mock_B')
import A
print(A.B.__name__)
A.py :
import B
注意B.py不存在,但是运行test.py
时不会返回错误,并且print(A.B.__name__)
打印mock_B
.您仍然必须创建一个mock_B.py
,在其中模拟B
的实际函数/变量/等.或者,您可以直接分配Mock()
:
Note B.py does not exist, but when running test.py
no error is returned and print(A.B.__name__)
prints mock_B
. You still have to create a mock_B.py
where you mock B
's actual functions/variables/etc. Or you can just assign a Mock()
directly:
test.py :
import sys
sys.modules['B'] = Mock()
import A
这篇关于如何模拟导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!