2015-01-04 180 views
1

我正在關注Graham Lee所着的「測試驅動的iOS開發」一書,並且遇到了本節沒有很好解釋的部分。這個想法不是在didFinishLaunchingWithOptions中實例化UIWindow,而是使用IBOutlet並將其掛接到UIWindow xib文件。我無法工作,也找不到任何互聯網上的例子。如何單元測試didFinishLaunchingWithOptions?

-(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?非常感謝

回答

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的副作用。你想要一個單元測試有一個已知的開始狀態,並且在整個測試中重用正在運行的應用程序通常是一件壞事。