Although I've successfully used google test and mock successfully for C++, I'm getting nowhere when it comes to using mocking in Python.
I'm trying to mock a small class in my code so that I can ensure the response from a particular function. I want to mock the whole class since the constructor does things that involve dependencies that I'd like to avoid. This seems like a fairly typical and mundane use case for mocking.
However, when I call the function on the mock, what I get is a MagicMock
object, not the result I wanted. Taking a very simple example:
class MyClass: def value(self): return 10
If I want to mock the MyClass
class and change the value
function so that it returns a different value, I believed that I could do this as follows:
with patch('__main__.MyClass') as MockMyClass: b = MyClass()
If I then attempt to set the value
function to something different, it doesn't work the way I expect and calling the function on the mock seems to return a MagicMock object instead:
>>> with patch('__main__.MyClass') as MockMyClass:... MockMyClass.value = lambda : 22... b = MyClass()... print(b.value())<MagicMock name='MyClass().value()' id='140661276636400'>
I've been through so many references and examples and I still don't get what I'm doing wrong. Feel so clueless - can anyone help me?