cleansharp.NET
"Clean code always looks like it was written by someone who cares."— Robert C. Martin (Uncle Bob)
Structure your unit tests using the Arrange-Act-Assert (AAA) pattern to make them more readable and maintainable.
The AAA pattern divides test methods into three distinct sections:
This test mixes setup, execution, and verification, making it hard to understand:
[Fact]
public void CalculateTotal_WithDiscount_ReturnsCorrectAmount()
{
var cart = new ShoppingCart();
cart.AddItem(new Item("Book", 20.0m));
cart.AddItem(new Item("Pen", 5.0m));
cart.ApplyDiscount(0.1m);
var total = cart.CalculateTotal();
Assert.Equal(22.5m, total);
Assert.True(cart.HasDiscount);
}
The same test using AAA pattern is much clearer:
[Fact]
public void CalculateTotal_WithDiscount_ReturnsCorrectAmount()
{
// Arrange
var cart = new ShoppingCart();
cart.AddItem(new Item("Book", 20.0m));
cart.AddItem(new Item("Pen", 5.0m));
cart.ApplyDiscount(0.1m);
// Act
var total = cart.CalculateTotal();
// Assert
Assert.Equal(22.5m, total);
Assert.True(cart.HasDiscount);
}
The AAA pattern is particularly valuable in team environments where multiple developers work on the same test suite.
When a test fails, the clear separation makes it immediately obvious whether the issue is in the setup, the action being tested, or the expectations.