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:

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

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

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

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

I would expect that 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