Test Error Cases
Exit

Test Error Cases

Write tests that verify your API returns the correct errors for invalid requests

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why test errors

Your API already handles errors — requesting a nonexistent expense returns a 404, and sending invalid data returns a 422. But without tests, you have no way to know these error responses stay consistent as you change the code.

Error tests are especially valuable because they catch regressions. If you accidentally remove a validation rule or change an error message, the test fails immediately.

What to test

You will write three error tests:

  • GET a nonexistent expense: should return 404
  • POST with a negative amount: should return 422 (Pydantic validation rejects it)
  • DELETE a nonexistent expense: should return 404

Each test sends a request that should fail and asserts the correct status code. The pattern is simpler than success tests because you do not need to check response body details — the status code is the important signal.

Instructions

Add tests for error cases.

  1. Define a function called test_get_nonexistent. Call client.get("/expenses/999999") and assert that response.status_code equals 404.
  2. Define a function called test_create_invalid. Call client.post("/expenses", json={"description": "Test", "amount": -5, "category": "food"}) and assert that response.status_code equals 422.
  3. Define a function called test_delete_nonexistent. Call client.delete("/expenses/999999") and assert that response.status_code equals 404.