Ever had a tiny bug in your C# code crash your entire test suite? š© Letās break down why that happensāand how your testing style (London vs. Classical) changes your debugging experience.
Inspired by āUnit Testing: Principles, Practices, and Patternsā by Vladimir Khorikov, hereās a relatable C# example to highlight the difference!
š The Scenario: A Simple Shopping Cart System
Imagine an e-commerce setup with:
-
Cart
ā Manages items, calculates totals -
OrderProcessor
ā Handles orders (depends onCart
) -
PaymentService
ā Processes payments (depends on OrderProcessor)
Now suppose you accidentally break the Cart
class. How does each testing style react?
1ļøā£ London-Style Tests (Isolated with Mocks)
In London-style testing, dependencies are mocked, so only tests for the broken component (Cart
) fail.
// London-style test for OrderProcessor (using Moq)
[Fact]
public void OrderProcessor_CreatesInvoice_ReturnsCorrectTotal()
{
var mockCart = new Mock<ICart>();
mockCart.Setup(c => c.GetTotal()).Returns(100); // Mocked Cart
var processor = new OrderProcessor(mockCart.Object);
var result = processor.CreateInvoice();
Assert.Equal(100, result); // ā
Passesāeven if the REAL Cart is broken!
}
ā
Pros: Fast, focused tests. Easy to pinpoint failures (e.g., Cart only).
ā Cons: Can give false confidenceāmisses integration bugs.
In classical testing, real dependencies are used. So if Cart
is broken, tests for OrderProcessor
and even PaymentService
start failing too.
// Classical test for OrderProcessor
[Fact]
public void OrderProcessor_CreatesInvoice_ReturnsCorrectTotal()
{
var cart = new Cart(); // Real Cart instance
cart.AddItem("Book", 50);
var processor = new OrderProcessor(cart);
var result = processor.CreateInvoice();
Assert.Equal(50, result); // ā FAILS if Cart.GetTotal() is broken!
}
ā
Pros: Detects integration issues early.
ā Cons: One bug can trigger a failure avalanche š
š§ Why This Matters
London-style tests are precise and fastābut can miss real-world breakages.
Classical tests offer stronger guaranteesābut debugging them can feel like āwhack-a-mole.ā šØ
š Khorikovās Insight
- Classical tests align better with the Test Pyramid, emphasizing integration and reducing over-reliance on mocks.
- A failure avalanche often points to mission-critical code. If breaking
Cart
causes 50 failures? Thatās a signalāitās important!
ā Silver Linings
- Run tests frequently: If things break, youāll know you broke it š
- Volume of failure = Importance: Failures are feedback, not frustration
š¬ Final Thought
Which testing style do you lean toward?
š *London *ā for precision and speed?
š *Classical *ā for real-world system feedback?
Letās discuss belowāand if you havenāt read Khorikovās book yet, seriously, itās a game-changer. šÆ
Top comments (0)