Ivan Peng
Ivan Peng

Reputation: 609

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

This is my following template code:

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

However, this throws an error on the assert. When I change it to:

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

it works just fine. Can someone please tell me what I'm doing wrong?

Upvotes: 2

Views: 833

Answers (1)

falsetru
falsetru

Reputation: 369064

For your test, patch _get_data only, not the whole 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')

or

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

or

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

Upvotes: 4

Related Questions