【发布时间】:2020-10-02 22:00:29
【问题描述】:
我需要为模块编写测试用例
to_be_tested.py
from module_x import X
_x = X() # creating X instance in test environment will raise error
#.....
在测试用例中,
from unittest import TestCase, mock
class Test1(TestCase):
@mock.patch('...to_be_tested._x')
@mock.patch('...to_be_tested.X.func1')
def test_1(self, mock_func1, mock_x):
...
但是,这不会阻止import 创建实例。这是一种解决方法并为模块编写测试用例吗?或者它是一种将to_be_tested 重构为可测试的方法?
如果检测到测试环境,也许写to_be_tested.py,只写_x = None?
【问题讨论】:
-
如果
to_be_tested.py在您的控制之下,修改它不要在导入时创建实例,而是将其延迟到第一次使用。如果您无法控制to_be_tested.py,请在此处查看解决方案:Mocking a module import in pytest -
是的,我现在可以完全控制源代码。我将把变量封装在一个函数中:
_x = None / def get_x(): global _x / if _x == None: _x = X() / return _x。然后其他函数使用该函数访问_x。这是个好方法吗?
标签: python unit-testing mocking