Frage

In multiple classes, I'm using [NSApp delegate] to get my main AppDelegate from where I'm accessing some properties. This is working as expected, but when I Unit Test the code that uses this, this delegate is nil.

How can I handle this in my test? Is it possible to write a mock or something?

War es hilfreich?

Lösung

Create a separate singleton class, that can be used to store global properties, and leave App Delegate to do its delegation role and nothing more:

AppProperties.h:

@interface AppProperties : NSObject

@property (strong, nonatomic) NSString *prop1;
@property (strong, nonatomic) NSNumber *prop2;
@property (strong, nonatomic) NSMutableArray *prop3;

+ (AppProperties *)sharedInstance;

@end

AppProperties.m:

@implementation AppProperties

@synthesize prop1, prop2, prop3;

+ (AppProperties *)sharedInstance {
    static AppProperties *instance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        instance = [[AppProperties alloc] init];
    });
    return instance;
}

@end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top