我想修补通过__import__
函数导入的类,但不起作用。
class Bar():
def __init__(self, class_name)
obj = getattr(__import__(class_name, fromlist=[class_name]), class_name)()
class TestBoard(unittest.TestCase):
@patch('MyClass', autospec=True)
def test_serial_construction(self, class_mock):
Bar('MyClass')
该类没有被模拟,但是当我用真实的对象构造替换__import__
时,它确实起作用:
class Bar():
def __init__(self, class_name)
obj = MyClass()
如何使它与__import__
一起使用?
答案 0 :(得分:1)
将行分隔为单独的set_object
方法,然后可以轻松地对该方法进行修补,以将其替换为其他方法
def set_object(self):
self.obj = getattr(__import__(class_name, fromlist=[class_name]), class_name)()
new_method = lambda self: self.obj = 'I didnt import this'
with patch('myclass.set_object', new_method):