Development, Implementation & Testing
Date Published
Moving into Phase 3 & 4: Development, Implementation & Testing, modern software engineering intertwines writing code with continuous automated verification. Rather than treating testing as a final phase before release, high-performing engineering teams adopt Test-Driven Development (TDD) and clean coding practices to build confidence, reduce defect rates, and keep the codebase easy to refactor.
Core Pillars of Implementation & TDD
-
The Red–Green–Refactor Cycle:
- Red: Write a small unit test that defines a specific desired behavior before writing the production code. Verify that the test fails (confirming the test is actually testing something and fails for the right reason).
- Green: Write the minimal amount of production code necessary to make the test pass.
- Refactor: Clean up the code, improve variable naming, eliminate duplication, and enhance modularity while keeping the test suite passing.
-
The Test Pyramid:
- Unit Tests (~70%): Fast, low-cost tests that verify individual functions, methods, or classes in complete isolation. They form the broad foundation of your test suite.
- Integration Tests (~20%): Validate interactions between multiple modules or against lightweight test environments (such as in-memory databases).
- End-to-End (E2E) & UI Tests (~10%): Run full user scenarios across complete production-like environments. Because they are slower and brittle, they sit at the narrow apex of the pyramid.
-
Isolating External Dependencies (Test Doubles):
- Mocks: Objects that record calls and parameters to verify behavior (e.g., asserting that
send_email()was called once). - Fakes: Simplified, working implementations used to verify state (e.g., an
InMemoryRepositoryusing a Python dictionary).
- Mocks: Objects that record calls and parameters to verify behavior (e.g., asserting that
Practical Example: The TDD Cycle in Action
Let's demonstrate TDD using pytest to implement discount validation on our Order model.
Step 1: Write a Failing Test (Red)
We define the test for a new feature—applying a discount percentage—before implementing the method on Order:
1# tests/test_order.py2from decimal import Decimal3import pytest4from domain import Order, Product5 6def test_apply_valid_discount_reduces_total():7 # Arrange8 order = Order(order_id="ord_1", customer_id="cust_1")9 product = Product(id="p1", name="Keyboard", price=Decimal("100.00"), stock_quantity=10)10 order.add_item(product=product, quantity=1)11 12 # Act: Apply 10% discount13 order.apply_discount(Decimal("0.10"))14 15 # Assert: Total with 8% tax should be (100 * 0.9) * 1.08 = 97.2016 assert order.calculate_total() == Decimal("97.20")17 18def test_apply_invalid_discount_raises_error():19 order = Order(order_id="ord_1", customer_id="cust_1")20 21 with pytest.raises(ValueError, match="Discount must be between 0 and 100%"):22 order.apply_discount(Decimal("1.50"))
Running pytest fails immediately because apply_discount does not exist yet.
Step 2: Implement Minimal Code (Green)
We add the simplest implementation to satisfy the test requirements:
1# domain.py2@dataclass3class Order:4 order_id: str5 customer_id: str6 items: List[OrderItem] = field(default_factory=list)7 discount_rate: Decimal = Decimal("0.00") # Added state8 9 def apply_discount(self, rate: Decimal) -> None:10 if rate < Decimal("0.00") or rate > Decimal("1.00"):11 raise ValueError("Discount must be between 0 and 100%")12 self.discount_rate = rate13 14 def calculate_total(self, tax_rate: Decimal = Decimal("0.08")) -> Decimal:15 subtotal = sum((item.subtotal for item in self.items), Decimal("0.00"))16 discounted_subtotal = subtotal * (Decimal("1.00") - self.discount_rate)17 return discounted_subtotal * (Decimal("1.00") + tax_rate)
Running pytest now passes!
Step 3: Refactor Safely (Refactor)
Because we have an automated safety net, we can clean up mathematical formulas or extract helper methods with full confidence that we haven't introduced regressions.
Why Automated Testing & Continuous Feedback Matter
- Rapid Feedback Loop: Running tests locally or during git pre-commit hooks gives immediate feedback while cognitive context is fresh.
- Legacy Code Prevention: Un-tested code quickly turns into intimidating legacy code. Automated test coverage makes future refactoring safe and predictable.
- Self-Testing Builds in CI: Merging code into main repositories triggers automated build pipelines that run unit, style, and coverage checks instantly.
