はじめに
iOSのユニットテストを行う際、テストターゲットアプリを指定した方が便利です。ただ、プロダクトコードのAppDelegateには大概色々のもの(UI、プッシュ、行動解析ライブラリの初期化やら。。。)がごちゃごちゃ乗っていてユニットテストの阻害要因になりやすいす。
解決策
ユニットテスト用のAppDelegateを作って、ユニットテストを実行する際はそれにすげ替えましょう!
実際のコード
こんな感じになります。なお、TestableAppDelegateはテストターゲットのみに含めます。
main.m
int main(int argc, char * argv[])
{
@autoreleasepool {
Class appDelegateClass = NSClassFromString(@"TestableAppDelegate");
if (!appDelegateClass) {
appDelegateClass = [AppDelegate class];
}
return UIApplicationMain(argc, argv, nil, NSStringFromClass(appDelegateClass));
}
}
テスト用のAppDelegateはこんな感じですっからかんにします。
TestableAppDelegate.m
@implementation TestableAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = [UIViewController new];
[self.window makeKeyAndVisible];
[UIView setAnimationsEnabled:NO];
return YES;
}
@end