如何对 didFinishLaunchingWithOptions 进行单元测试?

Posted

技术标签:

【中文标题】如何对 didFinishLaunchingWithOptions 进行单元测试?【英文标题】:How to unit test didFinishLaunchingWithOptions? 【发布时间】:2015-01-04 16:39:41 【问题描述】:

我正在关注 Graham Lee 的“Test-Driven ios Development”一书,并且遇到了根本没有很好解释的这一部分。这个想法不是在didFinishLaunchingWithOptions 中实例化UIWindow,而是使用 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】:

我没有读过那本书,但发现我能够测试我的 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 的副作用。您希望单元测试具有已知的开始状态,并且在整个测试过程中重用正在运行的应用程序通常是一件坏事。

【讨论】:

以上是关于如何对 didFinishLaunchingWithOptions 进行单元测试?的主要内容,如果未能解决你的问题,请参考以下文章

iOS:在应用程序委托中加载应用程序后选择一个选项卡

推送通知进入时调用的方法序列

如何对List 进行排序

如何对Dictionary的值进行排序

如何对Dictionary的值进行排序

如何对DataTable中的数据进行筛选