pythonpytestpython-unittest.mock

Verifying constructor calling another constructor


I want to verify Foo() calls Bar() without actually calling Bar(). And then I want to verify that obj is assigned with whatever Bar() returns.

I tried the following:

class Bar:
    def __init__(self, a):
        print(a)

class Foo:
    def __init__(self):
        self.obj = Bar(1)

###

import pytest
from unittest.mock import Mock, patch
from mod import Foo, Bar

@pytest.fixture # With stdlib
def mock_bar():
    with patch('mod.Bar') as mock:
        yield mock

def test_foo(mock_bar):
    result = Foo()
    mock_bar.assert_called_once_with(1)
    assert result.obj == mock_bar

But it would fail and say that:

E       AssertionError: assert <MagicMock na...='5265642864'> == <MagicMock na...='5265421696'>
E         Full diff:
E         - <MagicMock name='Bar' id='5265421696'>
E         ?                                 ^ ^^
E         + <MagicMock name='Bar()' id='5265642864'>
E         ?                     ++          +  ^ ^

Solution

  • This line:

    assert result.obj == mock_bar
    

    Should be:

    assert result.obj == mock_bar.return_value
    

    It is the result of calling Bar which gets assigned in self.obj = Bar(1), not Bar itself.