Course outline · 0% complete

0/29 lessons0%

Course overview →

Arrange, Act, Assert

lesson 2-1 · ~9 min · 4/29

Quiz

Warm-up. In lesson 1-2 you refactored count_vowels from a loop into a one-line generator expression. What proved the refactor was safe?

The three-part shape of every test

Almost every good test has the same skeleton, called arrange, act, assert (AAA):

  1. Arrange: set up the input data and any objects you need
  2. Act: call the one function or method under test, once
  3. Assert: check the result against what you expected

Why enforce a shape? Because tests are documentation. A teammate (or you, in six months) should be able to open any test and answer three questions instantly: what was the situation, what did we do, what should have happened. When those three phases blur together, a failing test becomes a puzzle instead of a message.

Arrangeset the stageActone callAssertcheck the resultevery test tells the same three-beat story
Arrange, act, assert: the fixed skeleton that makes any test readable at a glance.

Code exercise · python

Run this AAA-shaped test of cart_total. The comments mark the three phases, and there is exactly one act line.

Code exercise · python

Your turn. Write an AAA test for apply_discount named test_apply_discount_takes_percent_off: arrange a price of 80.0 and a percent of 25, act by calling apply_discount, assert the result is 60.0. Then call the test and print: PASS test_apply_discount_takes_percent_off

Code exercise · python

One more AAA rep. Write test_word_count_ignores_extra_spaces: arrange the text "hello world" (three spaces), act by calling word_count once, assert the count is 2. Then call the test and print: PASS test_word_count_ignores_extra_spaces