import unittest.mock.async_mock as AsyncMock async def my_coroutine(): return 42 async def my_async_function(): result = await my_coroutine() return result * 2 async def test_my_async_function(): coro_mock = AsyncMock() coro_mock.return_value = 10 result = await my_async_function() assert result == 20
import unittest.mock.async_mock as AsyncMock class MyClass: async def my_method(self): return 42 async def test_my_method(): my_mock = AsyncMock() my_mock.return_value = 10 my_obj = MyClass() result = await my_obj.my_method() assert result == 10In this example, we define a class `MyClass` with an async method `my_method()`. The method returns the value `42`. In the test function `test_my_method()`, we create an instance of `AsyncMock` called `my_mock` that we use to mock the `my_method()` method. We set the return value of the mock to `10`, and then call `my_method()` on an instance of the `MyClass` object called `my_obj`. We assert that the result is equal to `10`, which is the expected output. The `unittest.mock` package is a part of the Python Standard Library and does not require any additional installation.