Question

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?

Était-ce utile?

La 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.

Autres conseils

You could also use valueForKey:, but it's not as "clean" since you don't get auto-complete and could break if you rename the property via the refactor tool. But it's another option if you don't want to create the category.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top