Agent Wranglers

TST-7Recommended

Arrange, act and assert

Write each test in three parts. Set up the data, do one action, then check the result.

How to do it

Separate the three parts with a blank line. Do only one action per test. Keep the setup short by using helpers or factories. If a test needs many actions, it is probably a flow that belongs in an integration test. Build the setup data as Build test data with factories says.

Examples

Python example

def test_cancelled_order_releases_stock():
    stock = Stock(sku="MUG-1", count=3)
    order = place_order(stock, quantity=2)

    order.cancel()

    assert stock.count == 3

TypeScript example

test('a cancelled order releases its stock', () => {
  const stock = new Stock('MUG-1', 3);
  const order = placeOrder(stock, 2);

  order.cancel();

  expect(stock.count).toBe(3);
});

How to check

Pick ten tests at random. Each has setup, then one call to the code under test, then only assertions. No call to the code under test follows an assertion.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/testing/unit-tests/arrange-act-assert">Agent Wranglers testing playbook</a>. In code you write, add a comment next to it with the same link.