【问题标题】:How to mock a class method in the test which tests another class method? [duplicate]如何在测试另一个类方法的测试中模拟一个类方法? [复制]
【发布时间】:2022-02-06 14:40:02
【问题描述】:

我有以下课程,我正在 method2 上写一个测试。

y.py

class C:
    @classmethod
    async def method1(cls):  # to be mocked
        pass

    @classmethod
    async def method2(cls):  # to be tested
        await cls.method1()

我有以下

from asyncio import Future
from unittest.mock import Mock
import pytest
from y import C

@pytest.mark.asyncio
async def test_method2():
    C.method1 = Mock(return_value=Future())
    await C.method2()
    C.method1.assert_called_once()

但是,在运行python -m pytest test.py时会挂起?

【问题讨论】:

    标签: python pytest python-unittest


    【解决方案1】:

    您正在这里测试异步功能。因此,您应该使用 AsyncMock。使用 async_mock 您可以使用 awaited_onced 而不是调用一次。你的代码看起来像

    from unittest.mock import AsyncMock
    @pytest.mark.asyncio
    async def test_method2():
        C.method1 = AsyncMock()
        await C.method2()
        C.method1.assert_awaited_once() 
    

    【讨论】:

      猜你喜欢
      • 2022-06-19
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多