Python – Mocking object and return values of methods via patch

  mocking, python, python-unittest

I have a problem mocking the return value of an object’s methods using the patch decorator of unittest.mock in Python. A minimal example is this:

dummy_objects.py:

class DummyObject:
    def foo(self, int):
        return f"foo-{int}-"
    def bar(self, int):
        return f"bar-{int}-"

test_dummy.py:

import unittest
from unittest.mock import patch, Mock
import dummy_objects as do

dummy_patch = Mock(spec=do.DummyObject)
dummy_patch.foo.return_value = "9999"

@patch("dummy_objects.DummyObject", new=dummy_patch)
class TestCaseOne(unittest.TestCase):
    def test_patching_foo(self):
        tmp = do.DummyObject()
        self.assertEqual(tmp.foo(), "9999")

I would expect that tmp.foo() returns "9999" due to the patch-decorator. However, I get a new MagicMock as the output shows:

Ran 1 test in 0.006s

FAILED (failures=1)


9999 != <Mock name='mock().foo()' id='2087245816552'>

Expected :<Mock name='mock().foo()' id='2087245816552'>
Actual   :9999

Does anyone know what I am doing wrong here?

Source: Python Questions

LEAVE A COMMENT