pythonpytestpytest-mock

Trying to understand mocking in python


using pytest - given the following:

class Bar:
    def wtf(self):
        return 1
class Foo:
    def __init__(self, bar):
        self.bar = bar
    def huh(self):
        return self.bar.wtf()


def test_huh():
    bar = Bar()
    foo = Foo(bar)
    assert foo.huh() == 1

def test_huh2(mocker):
    bar = mocker.Mock()
    foo = Foo(bar)
    bar.wtf().return_value = 1
    assert foo.huh() == 1

test_huh does what I expect but I want to test Foo and mock the dependency on Bar.

test_huh2 fails.

it seems the mock does not get called. Can someone explain how this should be done?


Solution

  • On the line:

    bar.wtf().return_value = 1
    

    It sets the return value of the return value. Instead you just want:

    bar.wtf.return_value = 1
    

    It is probably also worth adding into test_huh2 an assertion that your mock was actually invoked as expected:

    bar.wtf.assert_called_once_with()