问题
I am using Specta to create some tests but I don't seem to be able to get this basic one to pass. The app itself works fine but this test won't pass.
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]);
}
This logs: PresentedVC: ETLoginVC
Specs
#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
This fails with: the actual value is nil/null
I've tried calling:
[loadingVC view]
I've even initiated a UIWindow
and an appDelegate
but I just can't get it working.
My view controller is all written in code. No storyboards or nibs.
UPDATE
For now i've added an NSString
property that gets updated with the class name that is about to be presented. I then check this string in my test. To get this working though, I had to change my beforeEach
block to the following:
beforeEach(^{
loadingVC = [[ETLoadingVC alloc] initWithUserDefaults:nil];
[loadingVC viewDidAppear:NO];
});
Although the test passes, I get the following message:
Warning: Attempt to present <ETLoginVC: 0x7fcf34961940> on <ETLoadingVC: 0x7fcf34961280> whose view is not in the window hierarchy!
I get that this is because i'm calling viewDidAppear
before the current view has finished appearing. What I don't get is how I can test this a better way.
I also don't understand why loadingVC.presentedViewController
still equals nil even with this updated beforeEach
block.
UPDATE 2
Changing the beforeEach
to the below got rid of the warning message and now the presentedViewController
is set correctly.
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:
Changing the beforeEach
to the following seemed to solve my problem.
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];
});
来源:https://stackoverflow.com/questions/26608530/unit-tests-dont-call-viewdidappear-method