簡體   English   中英

如何在異步單元測試中模擬方法?

[英]How to mock a method within an async unit test?

我有一個名為 database.py 的 class 和一個名為 generate_token() 的 function。 我想模擬它並返回一個固定值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"

它實際上比我想象的要簡單得多, 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM