我正在使用Specta创建一些测试,但我似乎无法通过这个基本的测试。该应用程序本身工作正常,但此测试不会通过。
的ViewController
- (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
,但我无法让它发挥作用。
我的视图控制器都是用代码编写的。没有故事板或笔尖。
更新
现在我已经添加了一个NSString
属性,该属性会使用即将显示的类名进行更新。然后我在测试中检查这个字符串。为了实现这一点,我必须将beforeEach
块更改为以下内容:
beforeEach(^{
loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:nil];
[loadingVC viewDidAppear:NO];
});
虽然测试通过,但我收到以下消息:
Warning: Attempt to present <ETLoginVC: 0x7fcf34961940> on <ETLoadingVC: 0x7fcf34961280> whose view is not in the window hierarchy!
我知道这是因为我在当前视图完成之前调用viewDidAppear
。我不能得到的是如何以更好的方式测试它。
即使使用此更新的loadingVC.presentedViewController
阻止,我也不明白为什么beforeEach
仍然等于零。
更新2
将beforeEach
更改为以下内容消除了警告消息,现在presentedViewController
已正确设置。
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];
});
答案 0 :(得分:4)
将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];
});
答案 1 :(得分:-1)
单元测试对于测试对象和逻辑更有用。您可能希望查看集成测试,该测试用于模拟实际的UI行为。 KIF是一个经常使用的框架,它建立在XCTest之上:http://www.raywenderlich.com/61419/ios-ui-testing-with-kif
所有内容都写在xcode中,因此您不需要任何额外的设置(除非您想进行连续测试)。