Ten Commandments for Unit Testing
- Refactor SUT to limit LOC required to setup a unit test
- Limit a unit test to 10 LOC or less
- Engineer tests so that they fail because of business logic and not setup logic
- Test behaviors and NOT implementation details
- Unit test business logic and NOT integration concerns
- Control test dependencies before they control your tests
- Provide descriptive test names
- Test only one thing per unit test
- Engineer tests so that they’re self-contained and can run in complete isolation
- Investigate static classes when tests no longer run deterministically
Referenced: Testing with F#
5 Replies to “10 Commandments for Unit Testing”
found your blog after your dotnetrocks appearance, some interesting reading. Could you provide an example on point 10? is this F# specific?
Hi Luke. A static class that has state regardless if its access modifiers (i.e. public, private, etc.) will stay in memory throughout the duration of an app’s lifespan. As a result, unit tests must provide an implementation for the teardown stage before exiting the test method. This will enable each unit test to execute without previous tests affecting it via the mutations to the static class’ state.
Hence, the four stages of a test:
Is that a little clearer?
Thanks for the reply, I think that is clear, so you are taking steps to make sure that the unit test is actually testing the unit of work in isolation, without worrying about if it has already run something against that static class.
I would phrase that differently but yes. It’s important for my unit test to run without any preexisting system state that’s outside of the scope of the unit test itself. In other words, my test’s setup will introduce state into the SUT instead of the SUT already having state that my test either is unaware of or has to adapt to.
Hence, tests that are reliant on external state to exist before running typically result in fragile tests that become a nightmare to maintain.
I will agree with your wording (mainly because your wordsmithery is much better), thanks for the clarification.