How to write good unit tests - Part II: Follow the given-when-then pattern
© Image by Margarethe Pfründer-Sonn↗
Given - When - Then
In my former post, I’ve written about the naming of tests and structuring the test class.
Given - When - Then
is the way to structure the body of your test method.
For the given - when - then
schema I’ve been inspired by spock framework↗.
But I believe, it is helpful to structure tests like this regardless of the testing framework or programming language you use:
Given:
Prepare the preconditions that are necessary for the test to succeed (from a business point of view).
When:
Call the implementation code (usually one line of code).
Then:
Assert/verify that the implementation did the right thing (try to only have one line of code).
How to start
Usually: On a new test, you start coding the when
part: You just call the implementation method under test.
Later, as the implementation code evolves, then the then
part will occur, and the given
part will grow gradually.
Other Names
In the clean code cheat sheet (page 4)↗, this pattern is called “Arrange - Act - Assert”.
But I prefer the words given - when - then
because they are more widespread (cucumber, spock framework↗, and others ).
My next post is about the details of the “given” block.
Any comments or suggestions? Leave an issue or a pull request!