I need to write test cases for the module
to_be_tested.py
from module_x import X
_x = X() # creating X instance in test environment will raise error
#.....
In the test case,
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):
...
However, this will not prevent the import from creating the instance. Is it a way to workaround it and write the test cases for the module? Or is it a way to refactory to_be_tested to be testable?
Maybe write in to_be_tested.py, just _x = None if detected test environment?
to_be_tested.pyis under your control, modify it not to create an instance at import time but to delay that until first use. Ifto_be_tested.pyis out of your control, see the solution here: Mocking a module import in pytest_x = None / def get_x(): global _x / if _x == None: _x = X() / return _x. Then other functions access_xusing the function. Is this a good way?