如何单元测试didFinishLaunchingWithOptions?

时间:2015-01-04 16:39:42

标签: ios unit-testing uiwindow

我正在关注这本书"测试驱动的iOS开发"格雷厄姆·李(Graham Lee)发现了这一部分并没有得到很好的解释。我们的想法不是在UIWindow中实例化didFinishLaunchingWithOptions,而是使用IBOutlet并将其挂钩到UIWindow xib文件。我无法正常工作,无法在互联网上找到任何示例。

-(void)testWindowHasRootNavigationControllerAfterApplicationLaunch
{
    XCTAssertEqualObjects(window.rootViewController, navigationController, @"App delegate's navigation controller should be the root VC");
}

@implementation iTagNewsAppDelegateTests
{
    UIWindow *window;
    UINavigationController *navigationController;
    AppDelegate *appDelegate;
}

- (void)setUp {
    window = [UIWindow new];
    navigationController = [UINavigationController new];
    appDelegate = [AppDelegate new];
    appDelegate.window = window;
    appDelegate.navigationController = navigationController;
}

代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
BrowseOverflowViewController *firstViewController =
[[BrowseOverflowViewController alloc] initWithNibName: nil bundle: nil];
    TopicTableDataSource *dataSource = [[TopicTableDataSource alloc]
        init];
    [dataSource setTopics: [self topics]];
    firstViewController.dataSource = dataSource;
    self.navigationController.viewControllers =
        [NSArray arrayWithObject: firstViewController];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

@interface BrowseOverflowAppDelegate : NSObject <UIApplicationDelegate> 
@property (nonatomic, retain) IBOutlet UIWindow *window;  
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end

他的完整项目在GitHub. 是否有任何教程如何定义自定义UIWindow?非常感谢

1 个答案:

答案 0 :(得分:0)

我还没看过那本书,但发现我能够测试我的AppDelegate的完整实例。使其适应您的代码:

- (void) setUp {
    //Could also use [[UIApplication sharedApplication] delegate] but I'm worried state may persist
    iTagNewsAppDelegate* appDelegate = [[iTagNewsAppDelegate alloc] init]
    [appDelegate application:[UIApplication sharedApplication] didFinishLaunchingWithOptions:nil]; //Couldn't find a better option than sharedApplication here, fine if application param isn't used?
    //the rest of your setup here
}

这适用于我的项目,但我不确定使用sharedApplication的副作用。您希望单元测试具有已知的开始状态,并且在整个测试过程中重复使用正在运行的应用程序通常是一件坏事。