lecture 9 of 130 completed

Arrange, Act, Assert

One pattern shapes almost every test ever written. Once you see it, unfamiliar test code becomes readable.

Read enough test code and you notice every good test has the same three parts, in the same order. The pattern has a name, and interviewers ask for it directly: Arrange, Act, Assert. Sometimes called AAA, sometimes Given-When-Then.

Arrange. Get the world into the state you need. Log in, open the page, create the contact you are about to delete.

Act. Do the one thing the test is about. Click delete.

Assert. Check the result. The row is gone, and the count dropped by one.

Written out, a test reads like this:

// Arrange: a contact exists and we are on the contacts page
login();
createContact('Dana Fox');
openContactsPage();

// Act: delete it
clickDeleteFor('Dana Fox');

// Assert: it is really gone
expectRowMissing('Dana Fox');
expectContactCount(3);

You do not need those comments in real code. The shape should be visible without them.

Three rules follow from the pattern, and each one prevents a specific problem.

One Act per test. If your test clicks delete, then edits another contact, then changes a setting, it is three tests wearing one name. When it fails, you cannot tell which part broke, and the failure message will not say. Split it.

Name the test after the assertion, not the steps. deletes a contact is weak. removing a contact drops it from the list and the count tells the next person what broke without opening the file. You will read failure names far more often than you write them.

Arrange with code, not with clicks, whenever you can. If a test needs a logged-in user, logging in through the form takes seconds and can fail for reasons that have nothing to do with what you are testing. A delete test that fails because login was slow is a lie: it reports a delete bug that does not exist. Later you will learn to set the session directly and skip the form.

That last point has a bigger version worth stating now. The arrange step should never be the thing you are testing. If the setup breaks, the test fails, and the failure blames the wrong feature. Keep the fragile, interesting behaviour in the Act, and make the Arrange as boring and reliable as you can.

Remember this: set the scene, do one thing, prove it happened.