Skip to main content

Levels of Abstraction in Testing

Sam Selikoff’s Levels of abstraction in testing does a nice job demonstrating how to make unit tests easier to read by abstracting the low level setup steps at the beginning of each test into a well-named function.

After that change, the everything in the tests reads at a single level of abstraction (namely, how would a user interact with this component?) rather than alternating between what the computer is doing and what the user is doing. The result is easier to understand.

Basically, you just want to act as if you’re sitting next to the person who is using the system you’re testing…just imagine how you’d explain to them what behaviour you’re testing and then write your tests using similar words.

I think this advice would apply just as well to non-test code. If you notice a code block mixes levels of abstraction, try extracting the lower level bits so the resulting code reads as a continuous train of thought from a single point of view.

For more, check out Sam’s complete video.