我正在学习python
我想知道是否有一种机制可以将对象(在我的情况下为假对象)“注入”到要测试的类中,而无需在构造函数/设置器中显式添加对象。
## source file
class MyBusinessClass():
def __init__(self):
self.__engine = RepperEngine()
def doSomething(self):
## bla bla ...
success
## test file
## fake I'd like to inkject
class MyBusinessClassFake():
def __init__(self):
pass
def myPrint(self) :
print ("Hello from Mock !!!!")
class Test(unittest.TestCase):
## is there an automatic mechanism to inject MyBusinessClassFake
## into MyBusinessClass without costructor/setter?
def test_XXXXX_whenYYYYYY(self):
unit = MyBusinessClass()
unit.doSomething()
self.assertTrue(.....)
在我的测试中,我想“注入”对象“引擎”而不将其传递给构造函数。我尝试了很少的选择(例如:@patch ...)而没有成功。
Python不需要IOC。这是一种Python方法。
class MyBusinessClass(object):
def __init__(self, engine=None):
self._engine = engine or RepperEngine()
# Note: _engine doesn't exist until constructor is called.
def doSomething(self):
## bla bla ...
success
class Test(unittest.TestCase):
def test_XXXXX_whenYYYYYY(self):
mock_engine = mock.create_autospec(RepperEngine)
unit = MyBusinessClass(mock_engine)
unit.doSomething()
self.assertTrue(.....)
您也可以将类存根以绕开构造函数
class MyBusinessClassFake(MyBusinessClass):
def __init__(self): # we bypass super's init here
self._engine = None
然后在您的设置中
def setUp(self):
self.helper = MyBusinessClassFake()
现在,您可以在测试中使用上下文管理器。
def test_XXXXX_whenYYYYYY(self):
with mock.patch.object(self.helper, '_engine', autospec=True) as mock_eng:
...
如果要使用构造函数不加注入,则可以将其添加为类属性。
class MyBusinessClass():
_engine = None
def __init__(self):
self._engine = RepperEngine()
现在存根绕过__init__
:
class MyBusinessClassFake(MyBusinessClass):
def __init__(self):
pass
现在,您只需分配值即可:
unit = MyBusinessClassFake()
unit._engine = mock.create_autospec(RepperEngine)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句