Accessing Private Methods in Unit Tests

Classes often have helper methods that are called by the public methods in the class. In order to keep the public interface clean, these helper methods should not be declared in the header file (.h). Instead, these should be declared in a class extension.

A class extension is a category defined on a class without a name. Sometimes these are referred to as anonymous categories. Methods declared in a class extension must be defined in the implementation (.m) file for the class.

In order to access these private methods declared in the class extension, simply move the class extension into a separate .h file, and include it in both the implementation file as well as the unit test file.

Be sure to name the class extension header file something that makes it clear that it should not be used only for testing; for example, include the word “private” or “fortesting”.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.