Chapter 35: Unit Testing
ASP.NET Core developers often use xUnit, Moq, and FluentAssertions. Python's standard path is pytest.
Domain test:
import pytest
from recipevault.domain.recipes import RecipeDraft
def test_recipe_title_is_required():
with pytest.raises(ValueError):
RecipeDraft(title="", instructions="Mix.", servings=2)
Service test:
def test_owner_can_publish_recipe(fake_repo):
service = RecipeService(fake_repo)
recipe = service.publish(recipe_id=1, user_id=42)
assert recipe.is_published
Testing practices:
- Keep domain tests fast and framework-free.
- Use fakes for simple ports.
- Use real database tests for repository behavior.
- Avoid over-mocking SQLAlchemy sessions.
- Name tests as behavior, not implementation.
- Use fixtures for setup, but keep them readable.
Python tests are pleasant when your application logic is not trapped inside route functions.