Here's a simple case that shows what I want (Python 2.7). (Note: in my actual use case, MyClass
is a class that gets instantiated indirectly within some code I'm testing):
from mock import patch
class MyClass(object):
def __init__(self):
self.prop = 'prop'
def foo(self):
return 'foo'
def bar(self):
return 'bar'
patcher = patch('__main__.MyClass')
MockedClass = patcher.start()
instance = MockedClass.return_value
instance.foo.return_value = 'mocked foo!'
my_instance = MyClass()
assert my_instance.foo() == 'mocked foo!', my_instance.foo()
# These asserts will fail
assert my_instance.bar() == 'bar', my_instance.bar()
assert my_instance.prop == 'prop', my_instance.prop
patcher.stop()
What I'm getting instead:
$ python mock_test.py
Traceback (most recent call last):
File "mock_test.py", line 22, in <module>
assert my_instance.bar() == 'bar', my_instance.bar()
AssertionError: <MagicMock name='MyClass().bar()' id='140162491496976'>
Why is the bar
method now returning a MagicMock
object? How can I patch this class so it stubs only the methods I want and leave everything else alone?
Aucun commentaire:
Enregistrer un commentaire