Take a look at the following test class. I deliberately wrote this poor quality test, so that I could show how easy it is to re-factor it to a better one. I was driven by having seen lots of such poor tests and to be honest I don’t want to see another of its ilk again. I might write a test like this myself, but I would never leave it like this. Its part finished. Its littered with cut and paste, poorly named methods and hard coded values. It’s a bit like a surgeon performing an operation and not sewing up the hole! I would go as far as to say that leaving tests in this state is unprofessional. There is no excuse as most of the lessons of good naming and code re-use have been written down a long time back. More lately in Clean Code by Robert C. Martin. I just don’t understand why people still write rubbish like this! Possibly because they are allowed to get away with it! Note that the test provides 100% coverage of the implementation class, but its not enough to stop there.
Have a read over the class, and then move on to read the steps to re-factor to better patterns. I have several designs here that focus on the setup stage of a test. As your tests get more complex you will find the patterns here support ever increasing complexity. In an Agile project you might move from one system to the next as the requirements ramp up. Then once you see where I am heading, I lay down a challenge.
Test anti-patterns project, contributors wanted!
If you have a Test Anti-Pattern that you would like to showcase. Check out my code from gitHub, add the new example and examples of how to re-factor the code. Blog it to your own blog with a reference to this page, or drop a comment. If we get enough I will setup a page with an index to all the blogs.
The code can be forked out with git from gitHub http://github.com/mhgit/TerribleJavaTestingMadeGood. It should be an easy start. Its a full maven project with a small dependency set and maven site reports already built in for test coverage. Its fully open source with the Apache 2.0 license. Once you have your new example, tell me about it by adding a comment to this page, and following the git forking instructions for making a git pull available.
Continue reading →