I'm trying to mock a function which is being called within an API call in a FastAPI project. But the mock doesn't work. I've prepared a sample API to demonstrate the issue. conftest.py @pytest.fixture(scope="function") def get_client(): client = TestClient(app) yield client utils.py def sample_function() -> str: return "Hello, World!" api.py from src.utils import sample_function @router.get( "/test-api", status_code=status.HTTP_200_OK, ) def sample_api() -> JSONResponse: return JSONResponse( status_code=status.HTTP_200_OK, content=sample_function(), ) tests.py from src.api import sample_api @patch("src.path.to.api.sample_function") def test_sample_api( mock_sample_function, get_client, ): mock_sample_function.return_value = "Bye World!" response = get_client.get( "/test-api", ) assert json.loads(response.body) == "Bye World!" @patch("src.path.to.api.sample_function") def test_sample_api_function( mock_sample_function, ): mock_sample_function.return_value = "Bye World!" response = sample_api() assert json.loads(response.body) == "Bye World!" In this sample if I try test_sample_api_function mocking works well, but if I try the test which actually test the api call test_sample_api, it can't mock the sample_function method. Why is this happening and what am I missing here? Continue reading...