Editorials

Unit Testing Feedback

Today I’d like to share two quotes I really appreciated in the comments on unit testing. Judeyak writes, “once you write the test, it lives on, manual tests are gone forever once you complete them.” How true that is.

I once wrote a complicated stored procedure that required about 10 hours to complete and debug. It’s more difficult to write and test SQL because it is harder to break apart than procedural code. The interesting thing is that it took me 40 hours to write unit tests, and get them all to pass. That’s a 4 to 1 ratio of effort writing tests compared to effort writing the code. To be fair, the ratio was much smaller as I spent a lot of time refactoring the stored procedure as I added new tests and functionality.

When all the tests and coding were complete, I had a great degree of confidence in the stored procedure and the accuracy it required. If it was that difficult to do, using unit tests, consider how much time it could have taken if I had tested manually. The real proof I found in the value of this process was when we added two new features to the application a few months later. I added the adjustments to the code, and ran all the unit tests. I didn’t have to spend hours in regression testing.

Eilenblogger brings out the Single Responsibility principle, “ which states that a class or module should have only one reason to change.” While this is not a unit testing requirement, it most certainly makes the organization, writing and execution of unit tests much easier to accomplish. I found that learning to write unit tests lead me toward following the Single Responsibility principle more closely.

This principle may also be applied to a method. The more scenarios a method implements, the more complicated it is to test fully. If a method has one variable with 10 options you would need at most 11 tests, one for each option, and a negative test when no option is provided to the method call. If a test has two variables with 10 options each, how many unit tests to you need? At least 100! So, if you can separate the two scenarios into two separate methods for testing, then you can create unit tests on them individually. Then combine them together in your code. You reduced your tests from 100+ to 22.

While Single Responsibility is not something I would put into Unit Testing Requirements, it is certainly something I would encourage as a means of efficiency. Otherwise, we will never get code written because we will be writing thousands of redundant tests.

Cheers,

Ben