
Unit Tests & Test-Driven Development (TDD)
In this week’s blog, I’m going to continue covering Robert C. Martin’s Clean Code, Chapter 9, Unit Tests. This is going to be a brief summary on
Three Laws of TDD
1. You may not write production code until you have written a failing unit test.
2. You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
3. You may not write more production code than is sufficient to pass the currently failing test.
Martin indicates that it’s important for our tests to stay clean and cover almost all of our production code. Having dirty tests is just as invaluable as having zero tests. It’s important to make changes to the tests when making changes to the codebase. Test code is just as important as production code. Unit tests keep our code maintainable, flexible, and reusable (Martin, 124). The tests allow you to write code without fear of a possible bug. When you don’t have tests, every change has the potential to become a bug. Test Code should be immensely readable.
There are some great patterns to follow when creating good unit tests. Such as Build—Operate—Check, Arrange—Assert—Act, etc.
Martin also states that there is a general guideline for having one Assert per test. And it is exactly that, a guideline rather than a hard-set rule. If anything, try to keep the test cases down to one concept.
F.I.R.S.T.
Clean tests should follow these rules too
- Fast — They should run quickly. This is so that they can be run frequently while writing new production code.
- Independent — It’s not a good idea for unit tests to depend on each other. If one or more tests were to fail due to an issue with production code, then we would quickly create an issue being that we don’t know where in the cycle our bug was created.
- Repeatable — We want to be able to repeat our tests in any environment, whether in QA, production, even with or without the internet. Anywhere.
- Self-Validating — They need to either pass or fail.
- Timely — We want to strive to build them in a timely fashion. And ideally, right before we create the code that will make them pass.
In summation, there are numerous tips to be used to write appropriate and meaningful tests. Remember the key is that we really want this to be beneficial for our future selves. For a better understanding check out Clean Code, by Robert C. Martin.