我尝试在下面的代码中修补calc类。 在测试代码中,我想用'MockCalc'而不是'Calc'创建每个'Client'。 然而,这不会发生,测试返回12而不是7。 Calc不会被MockCalc取代。
注意:'test_mock_play'是包含此代码的python模块(文件)的名称。
注意:我不想使用装饰
import mock
import sys
import unittest
SEVEN = 7
class Calc:
def __init__(self):
print self.__class__
def add(self,a,b):
return a + b
class MockCalc:
def __init__(self):
print self.__class__
def add(self,a,b):
return SEVEN
class Client:
def __init__(self):
self.calc = Calc()
def add(self,a,b):
return self.calc.add(a,b)
class TestIt(unittest.TestCase):
def setUp(self):
self.mock_calc = mock.patch('test_mock_play.Calc',create=True, new=MockCalc)
self.mock_calc.start()
def tearDown(self):
self.mock_calc.stop()
def test_patch_class(self):
'''Mocking the Calc and replace it with MockCalc.'''
print " \npatch class "
# client should be created with 'MockCalc'
client = Client()
# result should be 7
result = client.add(4,8)
print "1)" + str(result)
self.assertEqual(result,SEVEN)
if __name__ == "__main__":
unittest.main()
答案 0 :(得分:0)
将test_mock_play.Calc
替换为__main__.Calc
。但不建议这样做。
将test_mock_play.py
拆分为两个文件:
- 测试代码test_mock_play.py
。
- 实施代码:calc.py
。
从test_mock_play导入calc
。将对Calc
/ Client
的引用替换为calc.Calc
/ calc.Client
。
补丁calc.Calc
而不是test_mock_play.Calc
。
<强> calc.py 强>
class Calc:
def __init__(self):
print self.__class__
def add(self,a,b):
return a + b
class Client:
def __init__(self):
self.calc = Calc()
def add(self,a,b):
return self.calc.add(a,b)
<强> test_mock_play.py 强>
import unittest
import mock
import calc
SEVEN = 7
class MockCalc:
def __init__(self):
print self.__class__
def add(self,a,b):
return SEVEN
class TestIt(unittest.TestCase):
def setUp(self):
self.mock_calc = mock.patch('calc.Calc',create=True, new=MockCalc)
self.mock_calc.start()
def tearDown(self):
self.mock_calc.stop()
def test_patch_class(self):
'''Mocking the Calc and replace it with MockCalc.'''
print " \npatch class "
# client should be created with 'MockCalc'
client = calc.Client()
# result should be 7
result = client.add(4,8)
print "1)" + str(result)
self.assertEqual(result,SEVEN)
if __name__ == "__main__":
unittest.main()