unit testing不调用viewDidAppear方法

我正在使用Specta来创build一些testing,但我似乎无法得到这个基本的通过。 该应用程序本身工作正常,但这个testing不会通过。

视图控制器

- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self showLogin]; } - (void)showLogin { [self presentViewController:[ETLoginVC new] animated:NO completion:nil]; NSLog(@"PresentedVC: %@", [self.presentedViewController class]); } 

这个日志: PresentedVC: ETLoginVC

眼镜

 #import "Specs.h" #import "ETLoadingVC.h" #import "ETLoginVC.h" SpecBegin(ETLoadingVCSpec) describe(@"ETLoadingVC", ^{ __block ETLoadingVC *loadingVC; beforeEach(^{ loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:nil]; }); afterEach(^{ loadingVC = nil; }); describe(@"no current user present", ^{ it(@"should have a login view controller as the presented view controller", ^{ expect(loadingVC.presentedViewController).to.beKindOf([ETLoginVC class]); }); }); }); SpecEnd 

这失败了: the actual value is nil/null

我试过电话:

[loadingVC view]

我甚至发起了一个UIWindow和一个appDelegate但我不能得到它的工作。

我的视图控制器都是用代码写的。 没有故事板或笔尖。


UPDATE

现在我已经添加了一个NSString属性,获取将要呈现的类名的更新。 然后我在我的testing中检查这个string。 为了使这个工作,虽然,我不得不改变我beforeEach块如下:

 beforeEach(^{ loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:nil]; [loadingVC viewDidAppear:NO]; }); 

虽然testing通过,我得到以下消息:

 Warning: Attempt to present <ETLoginVC: 0x7fcf34961940> on <ETLoadingVC: 0x7fcf34961280> whose view is not in the window hierarchy! 

我得到这是因为我在当前视图完成出现之前调用viewDidAppear 。 我没有得到的是我怎么可以testing这个更好的方法。

我也不明白为什么loadingVC.presentedViewController仍然等于零,即使这个更新beforeEach块。


更新2

更改beforeEach到下面摆脱了警告消息,现在beforeEach设置正确。

 beforeEach(^{ mockUserDefaults = mock([NSUserDefaults class]); loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:mockUserDefaults]; window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; window.rootViewController = loadingVC; [window makeKeyAndVisible]; [loadingVC viewDidAppear:NO]; }); 

改变beforeEach以下似乎解决了我的问题。

 beforeEach(^{ mockUserDefaults = mock([NSUserDefaults class]); loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:mockUserDefaults]; window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; window.rootViewController = loadingVC; [window makeKeyAndVisible]; [loadingVC viewDidAppear:NO]; }); 

unit testing对testing对象和逻辑更有用。 您可能需要考虑用于模拟实际UI行为的集成testing。 KIF是一个已经使用了很多的框架,build立在XCTest之上: http ://www.raywenderlich.com/61419/ios-ui-testing-with-kif

一切都写在xcode里面,所以你不需要任何额外的设置(除非你想做连续testing)。