Writing Great Unit Tests
Unit testing was one of the types of testing that I had played a little bit before. Therefore, when I found this blog entry about Writing Great Unit Tests: Best and Worst Practices, I decided to choose it to understand more about unit testing and check if all the unit tests that I wrote in the past were good or bad. Below was the URL of the blog entry:
http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
In this blog, Steve Sanderson discussed about unit test and the tips to write great unit tests. He mentioned that it was overwhelmingly easy to write bad unit tests that add very little value to a project while inflating the cost of code changes astronomically. In his opinion, unit testing was not an effective way to find bugs or detect regressions. Unit testing was more about designing software components. He also compared good unit tests with bad unit tests, and provided some tips to write great unit tests.
Steve explained the reason he thought that unit testing was not an effective way to detect bugs or regressions. I agreed with him that only proving component X and Y both worked independently did not prove that they were compatible with one another or configured correctly. Therefore, bugs still might occur when the application was run. This absolutely reduced the effectiveness of bugs detection. Before reading this blog entry, I never realized that unit testing was not that suitable to find bugs like that. Furthermore, Steve provided a table to identify which type of test we should use for different purposes like finding bugs, detecting regressions, or designing software components.
Steve also gave some tips about writing good unit tests. In my opinion, some of them were very basic, but Steve still included them. I thought that was because he saw a lot of bad unit tests had those mistakes. He recommended not to make unnecessary assertions because unit tests were a design specification of how a certain behavior should work. Including multiple assertions only increased the frequency of pointless failures. Moreover, the unit tests’ names should be clear and consistent. Personally, I liked the way he used to name the example unit test. It helped you quickly identify the subject, the scenario, and the result of the unit test. This way of naming was more descriptive than the way I always used. I would apply it the next time I wrote tests.
From the blog CS@Worcester – Learn More Everyday by ziyuan1582 and used with permission of the author. All other rights reserved by the author.