Arrange-Act-Assert (AAA)

A common three-beat shape for readable tests: set up the world, do the one thing, check the result it produced.

given when thenthe three-part test layoutAAA patternarange act assertsetup, do the thing, check the resulthow should I structure a testtriple A test structuregiven-when-then

See it

Live demo coming soon

What it is

Most readable tests fall into three beats. Arrange: build the inputs, fixtures, and fakes the code needs. Act: exercise the one behavior you are testing, which is usually a single call but can be a short sequence when the behavior is a state transition. Assert: check the outcome that proves that behavior. It is a readability pattern, not a law with a line budget. Separate the beats with blank lines and the test reads like a sentence. BDD's Given-When-Then is the same shape wearing customer-facing words, which is why Cucumber and Gherkin feel familiar once you know AAA.

The structure earns its keep as a smell detector. An Act block that wanders into a second unrelated behavior means you have two tests hiding in one, and steps that only exist to reach the interesting moment usually belong up in Arrange. An assertion sitting in the Arrange block means you are testing your setup instead of your code. An Arrange block that runs thirty lines is telling you the thing under test has too many collaborators.

Common misreading: 'one assert per test'. That was never the point, and neither is 'one line of Act'. What you are aiming at is one behavior per test. Three assertions that together describe a single behavior (status, body, and header of one response) are fine, and so are three Act steps that together make up one transition. The other quiet killer is branching: an 'if' or a loop inside a test destroys the shape, because now the test has paths of its own that nobody is testing.

Ask AI for it

Rewrite these tests to follow Arrange-Act-Assert. Keep each test on one behavior: the Act section should hold only the steps needed to reach and trigger that behavior, and everything that merely prepares the world belongs above it in Arrange. Separate the three sections with a blank line. Split any test that exercises a second unrelated behavior into its own test, pull repeated setup into a helper or fixture, remove conditionals and loops from test bodies by using table-driven cases instead, and rename each test to describe the behavior being asserted rather than the method being called.

You might have meant

test caseassertiontest fixturetest driven developmentunit test