Trung BìnhPython iconPython

Mocking với `pytest-mock` — cách dùng thế nào?

Dùng mocker fixture từ pytest-mock để mock functions và verify calls.

python
async def test_register_sends_email(mocker):
    # Mock email service
    mock_send = mocker.patch(
        "app.services.email_service.send",
        new_callable=AsyncMock
    )
    mock_send.return_value = True

    await register_user(email="test@test.com")

    mock_send.assert_called_once_with(
        "test@test.com", "Welcome!"
    )

def test_with_side_effect(mocker):
    mock_api = mocker.patch("app.services.external_api.call")
    mock_api.side_effect = [{"status": "ok"}, ConnectionError()]

    assert call_api() == {"status": "ok"}
    with pytest.raises(ConnectionError):
        call_api()

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python