When I was trying to mock an async function in unittest with MagicMock, I got this exception:
TypeError: object MagicMock can\'t be used in \'await\' expr
I found this comment very useful when trying to await
a mock object in Python < 3.8. You simply create a child class AsyncMock
that inherits from MagicMock
and overwrites a __call__
method to be a coroutine:
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return super(AsyncMock, self).__call__(*args, **kwargs)
Then, inside your test, do:
@pytest.mark.asyncio
async def test_my_method():
# Test "my_method" coroutine by injecting an async mock
my_mock = AsyncMock()
assert await my_method(my_mock)
you might also want to install pytest-asyncio