Unit Test Tip: No Conditional Logic in a Test Case
I thought I’d share my response to this e-mail from a colleague:
I find myself having huge arguments with someone at work about how to write unit tests. In particular, things like having ifs and loops in tests. I am wondering if you could send me resources about the format of writing unit tests.
The definitive resource is xUnit Test Patterns: Refactoring Test Code by Gerard Meszaros. I’ve often used the book to influence people: if you don’t agree right now I will club you with this book that I’m holding. Kidding.
Most of the book is online. In the part of the book that describes test smells, Meszaros calls out Conditional Test Logic as a code test smell. There is a section of the Result Verification chapter that describes how to Avoid Conditional Test Logic.
I prefer to write test code that is straight line code: no conditional logic whatsoever. I suggest you adopt this guideline and see how it works for you. I would be interested in seeing any of your tests where you felt that conditional logic was needed.