Search code examples
objective-cunit-testingobjective-c-category

Exposing private properties with categories


I want to expose a view controller's private properties so that I can test them. One way to do that is by creating a category on the class just for testing and use a category method to get the value out.

// Class I want to test -- implementation
#import "SomeViewController.h"

@interface SomeViewController ()
@property (strong, nonatomic)UIActionSheet *sheet;
@end

// Category's header
#import "SomeViewController.h"

@interface SomeViewController (Test)
-(UIActionSheet *)getSheetValue;
@end

// Category's implementation
#import "SomeViewController+Test.h"

@implementation SomeViewController (Test)
-(UIActionSheet *)getSheetValue{
    return self.sheet;    // references private property
}
@end

Is there a better way to do this? I was thinking maybe I could just create a public sheet property on the category that referenced the private property's value but can't find any good documentation on how to go about it. What's the best practice for testing private properties without relying on ivars?


Solution

  • Privately the methods you need already exist, the category just needs to make them visible to the test:

    @interface SomeViewController (Test)
    
    - (UIActionSheet *) sheet;
    
    @end
    

    you don't need to implement that method, but now you can use it. You will only have issues if you make a method visible but which doesn't actually exist at runtime.