The Computing Series

How It Works

Unit test for pure logic:

function testDiscountApplied():
    order = buildTestOrder(items=[{sku: "A", price: 100, qty: 1}])
    discountCode = DiscountCode(percentage=10, minOrderValue=50)

    result = calculateDiscount(order, discountCode)

    assert result.discountAmount == 10
    assert result.finalTotal == 90

function testDiscountNotAppliedBelowMinimum():
    order = buildTestOrder(items=[{sku: "A", price: 40, qty: 1}])
    discountCode = DiscountCode(percentage=10, minOrderValue=50)

    result = calculateDiscount(order, discountCode)

    assert result.discountAmount == 0
    assert result.finalTotal == 40

No infrastructure. These run in under one millisecond.

Integration test for database interaction:

function testOrderRepositorySave():
    db = createTestDatabase()  # spins up a test DB or uses a transaction that rolls back
    repo = PostgresOrderRepository(db)
    order = Order.create(testCart, testCustomer)

    repo.save(order)

    storedOrder = db.queryOne("SELECT * FROM orders WHERE id = ?", order.id)
    assert storedOrder.status == "pending"
    assert storedOrder.total == order.totalPrice()
    assert storedOrder.customer_id == testCustomer.id

    db.rollback()  # clean up

Consumer-driven contract test:

# Consumer (warehouse service) defines what it expects from orders service:
contract OrdersServiceContract:
    interaction GetOrder:
        request:
            method: GET
            path: /orders/123
        response:
            status: 200
            body:
                id: String
                status: String (one of: "pending", "confirmed", "shipped")
                items: List<{sku: String, quantity: Integer, unitPrice: Money}>
                total: Money

# Orders service runs this contract as a test:
function testGetOrderMatchesContract():
    order = createTestOrder(id="123")
    response = testClient.get("/orders/123")

    assert response.status == 200
    assert response.body.id == "123"
    assert response.body.status in ["pending", "confirmed", "shipped"]
    assert isValidMoney(response.body.total)

When the orders service team changes the response schema, they run the contract tests from all consuming services. If any fail, they must either preserve backward compatibility or coordinate a versioned update.

Read in the book →