I have to start with the following:
“when you write any code which you want to share with others (colleagues, public), please, attach the sample how to use it. The best samples are unit tests, or better, specification tests by example.”
In this post I want to share my feelings I’ve got from unit testing approach:
- It affects the design of the subject under test (class, component, etc.)
- It’s because when the tested class is hard to be tested, then it’s hard to use => think about redesign
- If the tested subject has many dependencies, it has many concerns => think about splitting the class into smaller classes with single responsibility
- It proves that the code works correctly
- I spend less time on debugging
- It provides the code readers information how to use it
- I don’t need to spend so much time explaining others how to use it
- It creates a so called “live documentation”
- I can look at the tests and see what’s the subject’s behavior
Overall, the main goal is:
- Follow Arrange/Act/Assert model
- Arrange: written in describe/beforeEach
- Act: written in describe/beforeEach
- Assert: written in describe/it and we follow one it() = one expect
- Keep describe nesting as flat as possible, which means, max 3 levels
These are all high-level doctrines we follow. Keep it simple and stupid (KISS).
The following image shows how it looks when I just collapse all test details and see the behavior description on glance.
One of another goals is that the tests should describe the behavior and the test reader (aka developer) should be able to understand it from the glance, from first view over the test.
There are also other, more testing practices specific, but still very important which I’ll write about in the future:
- Faking the dependencies
- Mock and Stub used for Commands and Queries