我有一个类层次结构,其中包含一堆我正在尝试测试的包装器。我创建了一个简单的版本,我想在下面尝试做什么,但似乎无法弄清楚我的问题在哪里。
ClassA.py
import ClassB
class ClassA:
key = None
def __init__(self):
print 'Hello World from ClassA!'
def set_key_from_class_d(self):
class_b = ClassB()
class_d = class_b.get_class_d()
self.key = class_d.key
ClassB.py
import ClassC
class ClassB:
class_c = None
def __init__(self):
print 'Hello World from ClassB'
self.class_c = ClassC()
def get_class_d(self):
return self.class_c.get_class_d()
ClassC.py
import ClassD
class classC:
def __init__(self):
print 'Hello World from ClassC!'
def get_class_d(self):
return ClassD()
ClassD.py
class ClassD:
def __init__(self):
print 'Hello World from ClassD!'
self.key = 'my_key'
test_classes.py
import mock
import unittest
from ClassA import ClassA
class TestClasses(unittest.TestCase):
@mock.patch('ClassA.ClassB')
def test_classes(self, mock_class_b):
mock_class_d = mock.MagicMock()
mock_class_d.key = 'test_key_here'
mock_class_b.return_value = mock.MagicMock()
mock_class_b.get_class_d.return_value = mock_class_d
class_a_instance = ClassA()
class_a_instance.set_key_from_class_d()
print 'mock_class_d.key in test is: %s' % mock_class_d.key
self.assertEqual(class_a_instance.key, 'test_key_here')
if __name__ == '__main__':
print 'hello'
unittest.main()
当我运行python test_classes.py
时,我得到以下输出:
> python test_classes.py
hello
Hello World from ClassA!
mock_class_d.key in test is: test_key_here
F
======================================================================
FAIL: test_classes (__main__.TestClasses)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/rybridges/misc_code/test_venv/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "test_classes.py", line 17, in test_classes
self.assertEqual(class_a_instance.key, 'test_key_here')
AssertionError: <MagicMock name='ClassB().get_class_d().key' id='4535940752'> != 'test_key_here'
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
显然,我嘲笑这些东西的方式并不完全正确。我不明白为什么当我在测试中打印mock_class_d.key时它会说出我想要的东西,但是一旦函数被调用它就会在某个地方丢失。我究竟做错了什么? 如果可能的话,更愿意单独使用ClassA - ClassD。
谢谢!