Python补丁:在类中调用嵌套方法并不起作用

时间:2015-02-16 14:00:24

标签: python class unit-testing methods mocking

这是我的以下模板代码:

import mock
import unittest
class ClassToPatch(object):
    def __init__(self, *args):
        pass
    def some_func(self):
        data = self._get_data()
        return data

    def _get_data(self):
        return 'class_data'

class TestCase(unittest.TestCase):
    @mock.patch('__main__.ClassToPatch', autospec = True)
    def test_1(self, mock1):
        #mock1.data = "mocked data"
        m = mock.Mock()
        m._get_data.return_value = 'mocked data'
        mock1.return_value = m
        u = ClassToPatch()
        self.assertEqual(u.some_func(), 'mocked data')

unittest.main()

但是,这会在断言上抛出错误。当我将其更改为:

self.assertEqual(u._get_data(), 'mocked data')

它运作得很好。有人可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:3)

对于您的测试,仅修补_get_data,而不是全班。

@mock.patch.object(ClassToPatch, '_get_data')
def test_1(self, mock):
    mock.return_value = 'mocked data'
    u = ClassToPatch()
    self.assertEqual(u.some_func(), 'mocked data')

@mock.patch.object(ClassToPatch, '_get_data', lambda self: 'mocked data')
def test_1(self):
    u = ClassToPatch()
    self.assertEqual(u.some_func(), 'mocked data')

@mock.patch('__main__.ClassToPatch._get_data', return_value='mocked data')
def test_1(self, mock1):
    u = ClassToPatch()
    self.assertEqual(u.some_func(), 'mocked data')