Unit testing private method - objective C

Geek picture Geek · Aug 21, 2013 · Viewed 14.2k times · Source

I use GHUnit. I want to unit test private methods and don't know how to test them. I found a lot of answers on why to or why not to test private methods. But did not find on how to test them.

I would not like to discuss whether I should test privates or not but will focus on how to test it.

Can anybody give me an example of how to test private method?

Answer

Abizern picture Abizern · Aug 21, 2013

Methods in Objective-C are not really private. The error message you are getting is that the compiler can't verify that the method you are calling exists as it is not declared in the public interface.

The way to get around this is to expose the private methods in a class category, which tells the compiler that the methods exist.

So add something like this to the top of your test case file:

@interface SUTClass (Testing)

- (void)somePrivateMethodInYourClass;

@end

SUTClass is the actual name of the class you are writing tests for.

This will make your private method visible, and you can test it without the compiler warnings.