pythonpytestpython-unittest.mock

pytest: validating __init__ args with mock


I would like to write a test confirming __init__ values

def test_foo(mocker):
    mock = Mock()
    mocker.patch(
        "Foo.__init__", return_value=mock
    )

    foo = Foo('bar')
    mock.assert_called_with('bar')

But i get the following error TypeError: __init__() should return None, not 'Mock'

I ignore the error via try/except around foo = Foo('bar') but now, pytest says mock was not called

E           AssertionError: expected call not found.
E           Expected: mock('bar')
E           Actual: not call

Any idea how to validate __init__() args?

Thanks

P.S. I also would not like __init__() to actually run hence mock and not spy


Solution

  • You only need to patch the method while not returning anything (even by default a MagicMock would be returned):

    def test_foo(mocker):
        mock = mocker.patch("Foo.__init__", return_value=None)
        foo = Foo("bar")
        mock.assert_called_with("bar")