Hone

Lessons · Python · arrange, act, assert

Arrange, act, assert

Set up the inputs, call the one thing being tested, check the result. Three short steps in that order, so a test can be read at a glance.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A test is read most often when it fails, by someone in a hurry. If the given, the done and the expected are three separate lines, that person knows in seconds what the code was supposed to do.

How to think about it

Ask: what do I need before the call (arrange)? What is the single call (act)? What must be true after (assert)? If the act is two calls, it is two tests.

Worked example

def apply_discount(prices, pct):
The code under test.
    return [round(p * (1 - pct / 100), 2) for p in prices]
def test_ten_percent_off():
    prices = [10.0, 20.0]
Arrange: the inputs.
    result = apply_discount(prices, 10)
Act: the one call.
    assert result == [9.0, 18.0]
Assert: what must be true.
test_ten_percent_off(); print('ok')
ok

Your turn

Fill in the act step.

def test_no_discount_leaves_prices():
    prices = [5.0]
    result = 
    assert result == [5.0]

The trap

Asserting on several calls in one test. When it fails you get one red line and five suspects.

Practise arrange, act, assert on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.