代码之家  ›  专栏  ›  技术社区  ›  Houman

如何在异步单元测试中模拟方法?

  •  0
  • Houman  · 技术社区  · 3 年前

    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"
    
    0 回复  |  直到 3 年前
        1
  •  0
  •   Houman    3 年前

    它实际上比我想象的要简单得多,一个来自 from unittest.mock import patch

    @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"
    
    推荐文章