Tag Archives: category

Unit testing private functions in Xcode 4

I have found myself in the uncomfortable position of declaring private methods in my .h files so that I can run tests on them, and have been looking for ways around this.

I’ve found discussions about handling this in C++ which have me thinking it is bad programming style to need to test private functions: instead, complex private functions should be moved to a new class where they are public. I like the intellectual purity of this approach, but I have to think about how to apply it in my case.

In the meantime, I would like to have two types of unit tests, those on private functions and those on public functions.  Only the public functions define what the class does, of course, but unexpected failure of tests on the private functions can help me quickly find and debug problems.

Fortunately, another Stack Overflow post pointed me to a solution for Objective C.  I declared a new category (“Private”), put the private methods in the classname+Private.h header file, and deleted the classname+Private.m file.  I then import this .h file in classname.m, as well as the unit tests.

[Note the first time I read that post, I misinterpreted it, and created a .h and a .m file for the new category, and tried to implement the private functions in this new .m file.  This approach doesn't solve the original problem at all.]

Using a “Private” category feels like a nice solution, since I could have declared those private functions in a class extension at the top of the classname.m file anyway.  Adding the Private category just allows the unit tests to access them too.

Nonetheless, I’d appreciate any comments on the benefits are of the purer approach of moving complex private functions into a new class…