【问题标题】:How to mock a method within an async unit test?如何在异步单元测试中模拟方法?
【发布时间】:2021-02-04 00:17:00
【问题描述】:

我有一个名为 database.py 的类和一个名为 generate_token() 的函数。 我想模拟它并返回一个固定值321。这样我就可以看到方法被调用并返回了返回值。

我该如何模拟呢?这是我尝试过的。

@pytest.mark.asyncio
async def test_successful_register_returns_device_token(monkeypatch):
    async def mock_generate_token():
        return "321"

    m = AsyncMock(mock_generate_token)
    m.return_value = "321"
    async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
        monkeypatch.setattr(database, "generate_token", m)
        response = await ac.post(
            "/register/",
            headers={},
            json={},
        )
        assert response.status_code == 201
        assert "device_token" in response.json()
        assert response.json()["device_token"] == "321"

【问题讨论】:

  • 你能提供一个minimal reproducible example吗?代码不包含任何错误,但是看不到错误,很难说是哪里出了问题。

标签: python pytest fastapi python-3.9


【解决方案1】:

它实际上比我想象的要简单得多,来自from unittest.mock import patch 的普通@patch 就足够了。它识别异步方法并自动注入 AsyncMock。

@pytest.mark.asyncio
@patch("service.auth_service.AuthService.generate_token")
async def test_successful_register_returns_device_token(self, mock_token):
        mock_token.return_value = "321"
        async with AsyncClient(app=app, base_url="http://testserver") as ac:
            response = await ac.post(
                "/register/",
                headers={},
                json={},
            )
            assert response.status_code == 201
            assert "device_token" in response.json()
            assert response.json()["device_token"] == "321"

【讨论】:

    猜你喜欢
    • 2014-01-18
    • 2016-01-26
    • 1970-01-01
    • 2020-12-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多