Python 补丁:调用 class 中的嵌套方法不起作用

Python patch: calling nested method in class doesn't work

这是我的以下模板代码:

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')

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

为了您的测试,只修补 _get_data,而不是整个 class。

@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')