I'm trying to understand the difference in approaches for mocking. For example, I have a class that I can't initialize because it depends on another service.
class SomeClass:
def __init__(self, some_service):
self.some_service = some_service
async def some_method(self, x, y):
return x + y
And I have a function that uses this class
async def some_function(some_class: SomeClass, a, b):
return a * b + await some_class.some_method(a, b)
I want to test the function some_function.
@pytest.mark.asyncio
async def test_some_function_with_create_autospec():
autospec_mock = create_autospec(SomeClass)
autospec_mock.some_method = AsyncMock(return_value=10)
result = await some_function(autospec_mock, 2, 3)
assert result == 16
autospec_mock.some_method.assert_awaited_once_with(2, 3)
But I can do everything the same using MagicMock
@pytest.mark.asyncio
async def test_some_function_with_magic_mock():
autospec_mock = MagicMock(spec=SomeClass)
autospec_mock.some_method = AsyncMock(return_value=10)
result = await some_function(autospec_mock, 2, 3)
assert result == 16
autospec_mock.some_method.assert_awaited_once_with(2, 3)
what is the difference and which should I use?
I read the documentation but still don't understand