Update: Apple took this to heart, and improved the unit test template in Xcode 5 and greater.
Xcode 4 has a File Template Library for creating new files. It includes a unit test template called “Objective-C test case class.”
Don’t use it.
Wouldn’t you like your unit test development to go faster? Let me give you a better file template.
Apple’s template puts cruft in your project. Cruft slows you down.
What’s wrong with Apple’s unit test template? Depending on which version of Xcode 4 you’re using, the template can be unnecessarily complicated, due to a distinction between logic tests and application tests that no longer exists.
But the template’s description reveals an ongoing problem: “An Objective-C class containing an OCUnit test case with a header.” A header? What for?
Many people assume that in C-based languages, you always write classes using two files: a header, and an implementation. But while header files often contain the class declaration, that’s not really what header files are for: A header file holds information so it can be shared by more than one file. In other words, it’s not where you put any and all declarations. Hide any declarations you can inside implementation files.
For a test case class, what needs to be included by more than one file? Nothing. OCUnit uses reflection to discover classes that inherit from SenTestCase, and within those classes, methods whose names start with “test”. This is all done dynamically; there’s no need to put the test class declaration in a header file (much less any test method declarations).
By creating a header file when it’s not needed, Apple’s unit test template puts cruft in your project. That cruft will slow down your scanning of the project navigator. To add an instance variable to your test fixture, you’ll have to open another file. When you add a test method, you’ll be tempted to create an unnecessary method declaration. Cruft slows you down.
So let’s cut the cruft. Here’s a better file template for creating test case classes: OCUnit test case. And here’s how I use it:
This reduces the number of files in my project, and lets me code faster.
Download my unit test template and see for yourself.
To go faster still, I use a code snippet to create new test methods. Subscribe by email, and you’ll receive that code snippet and two others that help me write unit tests even more quickly!
Jon is a coach and consultant on iOS Clean Code (Test Driven Development, unit testing, refactoring, design). He’s been practicing TDD since 2001. You can learn more about his background, or see what services he can bring to your organization.