I'm trying to test a class and mock one of its methods, but I can't seem to replace the behavior of one of the instance methods with my mocked behavior. My code is organized like so:
--src
----module
------__init__.py
------my_class.py
--tst
----__init__.py
----test_my_class.py
my_class.py
contains the following
class MyClass:
def __init__(self):
pass
def do_something(self):
return 'Real Output'
My test file test_my_class.py
contains the following.
from unittest.mock import patch
from src.module.my_class import MyClass
def test_my_class():
my_class = MyClass()
assert my_class.do_something() == 'Real Output'
@patch('src.module.my_class.MyClass')
def test_mock_my_class(mock_my_class):
mock_my_class.return_value.do_something.return_value = 'Mocked Output'
my_class = MyClass()
assert my_class.do_something() == 'Mocked Output'
The first test works just fine (no mocking involved so far). The second test, however, gives me the following assertion error. I expect the do_something()
method to be mocked and to return "Mocked Output", and for the assert statement to evaluate to true. Where am I going wrong here?
AssertionError: assert <bound method MyClass.do_something of <src.module.my_class.MyClass object at 0x1057133c8>> == 'Mocked Output'
E + where <bound method MyClass.do_something of <src.module.my_class.MyClass object at 0x1057133c8>> = <src.module.my_class.MyClass object at 0x1057133c8>.do_something
PS. I've consulted the following resources without success:
- Python mock class instance variable
- Mocking Methods on an Instance Variable in Python
- Python mock: wrap instance method
- How to supply a mock class method for python unit test?
- https://medium.com/python-pandemonium/python-mocking-you-are-a-tricksy-beast-6c4a1f8d19b2
That last link looked especially helpful at first, because I'm following one of the examples almost verbatim, but it still doesn't work.
@mock.patch("simple.SimpleClass")
def mock_simple_class(mock_class):
mock_class.return_value.explode.return_value = "BOO!"
inst = simple.SimpleClass()
result = inst.explode()
print(result)