For a while I was struggling to write tests/specs for the most complex class in Quizbag.com.
The class’s job was to find and select quiz questions for a quiz based on what question categories they wanted, how difficult they should be and what questions would suit where they’re from. So there was a lot of possible outcomes that needed test coverage.
On several occasions I wrote and rewrote the tests I needed. They worked. But they never felt right.
Be aware of what you’re feeling. If a test doesn’t feel right, stop.
It was taking too much effort, too many lines of code to set up the object I was testing into the required state.
“If its hard to test its a good sign that you need to refactor your code”
This sent me on the right path but I didn’t know the best way to go about refactoring either so I bought a book and found what I needed to sort out that class and write better tests:
- This complex class knew way too much about other class and were violating the Law of Demeter
- I discovered I needed to extract a class or two and in these extracted class I made sure to only pass in the parameters I needed and no more to keep them loosely coupled.
When your tests are right you’ll know it
When I went back to redo those tests again I had one of those aha moments. They were easy to write.