无法使用 unittest 修补由被测试的 class 实例化的 class
Unable to patch class instantiated by the tested class using unittest
我正在尝试修补由 class 实例化的 class 我正在尝试测试,但它不起作用。我已经阅读了各种文档,但仍然没有发现我做错了什么。这是代码片段:
在tests/Test.py
中:
from module.ClassToTest import ClassToTest
class Test(object):
@mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
def setUp(self, my_class_mock):
self.instance = my_class_mock.return_value
self.instance.my_method.return_value = "def"
self.class_to_test = ClassToTest()
def test(self):
val = self.class_to_test.instance.my_method() #Returns 'abc' instead of 'def'
self.assertEqual(val, 'def')
在module/ClassToPatch.py
中:
class ClassToPatch(object):
def __init__(self):
pass
def my_method(self):
return "abc"
在module/ClassToTest.py
中:
from module.ClassToPatch import ClassToPatch
class ClassToTest(object):
def __init__:
# Still instantiates the concrete class instead of the mock
self.instance = ClassToPatch()
我知道在这种情况下我可以很容易地注入依赖项,但这只是一个例子。此外,我们对每个文件策略使用一个 class,文件命名为 class,因此导入命名很奇怪。
正如 norbert 提到的那样,解决方法是将模拟行从
@mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
到
@mock.patch('module.ClassToTest.ClassToPatch', autospec = False)
The patch() decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends.
您正在测试 ClassToTest
模块,而不是 ClassToPatch
模块。
我正在尝试修补由 class 实例化的 class 我正在尝试测试,但它不起作用。我已经阅读了各种文档,但仍然没有发现我做错了什么。这是代码片段:
在tests/Test.py
中:
from module.ClassToTest import ClassToTest
class Test(object):
@mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
def setUp(self, my_class_mock):
self.instance = my_class_mock.return_value
self.instance.my_method.return_value = "def"
self.class_to_test = ClassToTest()
def test(self):
val = self.class_to_test.instance.my_method() #Returns 'abc' instead of 'def'
self.assertEqual(val, 'def')
在module/ClassToPatch.py
中:
class ClassToPatch(object):
def __init__(self):
pass
def my_method(self):
return "abc"
在module/ClassToTest.py
中:
from module.ClassToPatch import ClassToPatch
class ClassToTest(object):
def __init__:
# Still instantiates the concrete class instead of the mock
self.instance = ClassToPatch()
我知道在这种情况下我可以很容易地注入依赖项,但这只是一个例子。此外,我们对每个文件策略使用一个 class,文件命名为 class,因此导入命名很奇怪。
正如 norbert 提到的那样,解决方法是将模拟行从
@mock.patch('module.ClassToPatch.ClassToPatch', autospec = False)
到
@mock.patch('module.ClassToTest.ClassToPatch', autospec = False)
The patch() decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends.
您正在测试 ClassToTest
模块,而不是 ClassToPatch
模块。