0

I commonly instantiate a Mock object during unit tests. I am sick of:

  1. Having to type from unittest.mock import Mock
  2. And then instantiate a Mock object via mock = Mock()

I am wondering, does pytest, unittest.mock, pytest-mock, etc. have a built in way of passing in a Mock object?

Here is what my current workflow looks like:

from unittest.mock import Mock


def test_something() -> None:
    mock = Mock()
    mock.func()
    mock.func.assert_called_once()

Research

I know with pytest-mock, I can at least get around the import via the mocker fixture.

def test_something(mocker) -> None:
    mock = mocker.Mock()
    mock.func()
    mock.func.assert_called_once()

I am hoping to just be able to do something like this:

def test_something(mock) -> None:
    mock.func()
    mock.func.assert_called_once()
Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

1 Answers1

1

If you're using pytest just make a fixture.

@pytest.fixture(scope="function")
def my_cool_mock():
    mocked = Mock()
    yield mocked

def test_something(my_cool_mock) -> None:
    my_cool_mock.func()
    my_cool_mock.func.assert_called_once()

Otherwise, just use pytest-mock.

gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • Yeah, I had also thought of this. I was hoping for something that didn't require custom fixturing on my end at all. I was hoping it would just be built-in. – Intrastellar Explorer Sep 24 '20 at 22:56