0

我尝试在下面的代码中修补 calc 类。在测试代​​码中,我希望使用“MockCalc”而不是“Calc”创建每个“客户端”。但是,这不会发生,并且测试返回 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()
4

1 回答 1

0

解决方法

替换test_mock_play.Calc__main__.Calc。但不建议这样做。

推荐方式

分成test_mock_play.py两个文件: - 测试代码test_mock_play.py。- 实现代码:calc.py.

calc从 test_mock_play导入。替换对Calc/Client的引用calc.Calc/ calc.Client

补丁calc.Calc而不是test_mock_play.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()
于 2013-08-08T08:37:50.140 回答