2

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?

2
  • Because mock1 is completely unrelated to u? Commented Feb 16, 2015 at 14:02
  • I realize now that I was a little verbose in declaring mock to set to return_value for mock1, when I could have just consolidated the two... Commented Feb 16, 2015 at 19:05

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.