Skip to content

Anatomy of a test

BraveJero edited this page Oct 4, 2021 · 4 revisions

In the simplest terms, a test is meant to look at the result of a particular behavior, and make sure that result aligns with what you would expect.

The four steps of a test (AAAC)

You can think of a test as being broken down into four steps:

AAAC

  1. Arrange: is where the testing conditions are set.

  2. Act: is the state-changing action that kicks off the behavior we want to test.

  3. Assert: is where the resulting output is contrasted with the expected one.

  4. Cleanup: is where the test picks up after itself, so that further tests aren't affected by it.

Tests must be deterministic

Non-deterministic tests have two problems, firstly they are useless, secondly they are useless. Jokes aside, a good test code must always yield the same result from the same code.

Writing clean test code

As with writing code in general, coming up with good and clean test code takes great care. Here are some of the best recommendations you can follow to write better test code:

  • Test code is as important as production code.

  • Test one condition per test. This helps you to keep your tests short and easy to debug.

  • The four steps of a test (AAAC) are good mnemonics to keep your tests well-structured.

  • Readability matters. Try to find a balance between DRY and DAMP code.

The basics of unit testing

A unit test is a piece of code that invokes a unit of work and checks one specific end result of that unit of work. If the assumptions on the end result turn out to be wrong, the unit test has failed. A unit test’s scope can span as little as a method or as much as multiple classes. — The Art of Agile Development by James Shore and Shane Warden

Unit Test diagram

References

Clone this wiki locally