如何模拟导入 [英] How to mock an import

查看:51
本文介绍了如何模拟导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模块A的顶部包含import B.但是在测试条件下,我想模拟 BA(模拟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

这篇关于如何模拟导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆