单元测试Storyboard viewDidLoad未调用

时间:2015-03-03 03:01:10

标签: ios objective-c unit-testing uiviewcontroller storyboard

所以有一些关于如何加载包含用于单元测试的笔尖的Storyboard的文章,它看起来像这样

MyViewController vc;

- (void)setUp
{
    [super setUp];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self.vc = [storyboard instantiateViewControllerWithIdentifier:@"main"];
    [self.vc performSelectorOnMainThread:@selector(loadView) withObject:nil waitUntilDone:YES];
}

然而,当我这样做时,类的viewDidLoad方法永远不会被调用,我必须像这样手动执行

- (void)setUp
{
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MediaSelectionSuite" bundle:[NSBundle mainBundle]];
    SUT = [storyboard instantiateViewControllerWithIdentifier:@"Gallery"];
    [SUT performSelectorOnMainThread:NSSelectorFromString(@"loadView") withObject:nil waitUntilDone:YES];
    [SUT viewDidLoad];
}

正如你所看到的那样,我必须为要调用的控制器的[SUT viewDidLoad];添加viewDidLoad ...它可以工作,我不应该太担心,因为它是套件测试,但我有疑虑,因为你很少需要手动调用它,不应该instantiateViewControllerWithIdentifier:或选择调用loadView确保调用viewDidLoad

更新

经过一些实验后,似乎只有UIViewController被设置为您的故事板初始UIViewController的{​​{1}}方法才会调用viewDidLoad方法instantiateViewControllerWithIdentifier: }

1 个答案:

答案 0 :(得分:1)

我最近遇到了和你一样的情况并找到了我的解决方案。你是正确的viewDidLoad()不会自动调用。实际上,您可以调用视图控制器的view属性来触发viewDidLoad()。有关详情,请查看View Controller TDD