Search code examples
pythonunit-testingmocking

How to patch an attribute in an object


The question is how to patch an attribute of an instance within a with statement. I tried with following example which doesn't work. It prints as in the comment.

from mock import patch, PropertyMock

class Foo(object):
    f = {'a': 1}

new_foo = Foo()

with patch.object(new_foo, 'f', new_callable=PropertyMock) as mock:
    mock.return_value = {'b': 2}
    print new_foo.f
    # <PropertyMock name='f' id='4474801232'>

Solution

  • There's an example in the documentation. You need to provide the class to patch.object, not the instantiated object.

    from mock import patch, PropertyMock
    
    class Foo(object):
        f = {'a': 1}
    
    new_foo = Foo()
    
    with patch.object(Foo, 'f', new_callable=PropertyMock) as mock:
        mock.return_value = {'b': 2}
        print new_foo.f
    
    print new_foo.f
    

    Outputs:

    {'b': 2}
    {'a': 1}