Explain the AAA pattern (Arrange, Act, Assert)

4 minbeginnertestingunit-testingbest-practices

Quick Answer

The AAA pattern structures a test into three clear phases: Arrange (set up objects, inputs, and dependencies), Act (invoke the method under test), and Assert (verify the outcome). This separation keeps tests readable and consistent and makes the intent obvious. Each test should ideally exercise a single behavior with one logical assertion.

Detailed Answer

The AAA pattern is a common structure for organizing unit tests, making them clear and consistent:

1. Arrange: Set up the test conditions

  • Initialize objects
  • Configure dependencies
  • Set up test data and expected values

2. Act: Execute the code under test

  • Call the method or function being tested
  • Trigger the behavior you want to verify

3. Assert: Verify the results

  • Check that the actual outcome matches expectations
  • Verify state changes, return values, or method calls

Example:

[Fact]
public void Withdraw_WithSufficientFunds_DecreasesBalance()
{
    // Arrange
    var account = new BankAccount(initialBalance: 100);
    var withdrawAmount = 30;
    
    // Act
    account.Withdraw(withdrawAmount);
    
    // Assert
    Assert.Equal(70, account.Balance);
}