"Clean code always looks like it was written by someone who cares."
— Robert C. Martin (Uncle Bob)

Arrange-Act-Assert

✅ One-liner Summary

Structure your unit tests using the Arrange-Act-Assert (AAA) pattern to make them more readable and maintainable.

💡 Short Explanation

The AAA pattern divides test methods into three distinct sections:

  • Arrange: Set up the test data and conditions
  • Act: Execute the code being tested
  • Assert: Verify the results This structure makes tests easier to understand, maintain, and debug.

🚫 Bad Example

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);
}

✅ Good Example

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);
}

💬 Real-World Insight

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.

📊 Best Practices

  1. Use comments to clearly separate the three sections
  2. Keep the Arrange section focused on test setup
  3. Have only one Act statement per test
  4. Group related assertions together
  5. Consider using helper methods for common Arrange patterns

🧠 Key Takeaways

  • AAA pattern improves test readability and maintainability
  • Makes it easier to identify where test failures occur
  • Helps new team members understand test structure quickly
  • Reduces cognitive load when reviewing test code
  • Enables better test documentation through clear structure