Levels of abstraction in testing 🔖
Updated 1 year ago
This is a nice video from Sam Selikoff 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 tests read at one level of abstraction (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.
Source: Levels of abstraction in testing by Sam Selikoff