Unit Testing Principles
Writing good unit tests is challenging. Over time I’ve accumulated a number of principles about what to do in unit tests, as well as what not to do. This list is incomplete, but I’ll start it now.
- Test every possible code path. This means that for each ‘if’ statement, you’ll have at minimum 2 tests. Also known as code coverage.
- Write your tests first. TDD is a hard mindset to get into, but well worth it.
- If you have doubts about whether your code will do what you intend, you haven’t written enough tests.
- Your tests should never make calls to external resources such as a database, filesystem, etc.
- Every test should be self-sufficient and isolated. Your tests should not rely on other tests, or external factors. Be skeptical of setup/teardown code for a test harness class.
- Don’t test outside of your code. There is no need to write test cases for an assembly you are dependent on.
This list will grow over time, especially if you have suggestions I might add.
Want to start unit testing, but not sure how? Watch our free online webinar “Intro to Unit Testing”.