iOS testing controllers with Cedar

纵饮孤独 提交于 2019-12-13 04:10:13

问题


I'm trying to test a controller(s) with Cedar but can't really understand why it's not working. The controller never gets shown, viewDidLoad or viewDidAppear are never called. Is this something Cedar wasn't meant to do or just my mistake?

describe(@"MyController", ^{
    __block UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
    __block UINavigationController *root = (UINavigationController *)[[[[UIApplication sharedApplication] delegate]window ]rootViewController];
    __block MyViewController *model = [storyboard instantiateViewControllerWithIdentifier:@"MyController"];

    [root pushViewController:model animated:YES];

    it(@"should test something", ^{
        expect(model.content).to(be_truthy);
    });
});

回答1:


Unit tests run synchronously. Anything that is — or can be — animated won't work in a normal unit test, because the test will be done before the change takes place.

It looks like you're trying to test the state of your view controller when it is shown. In that case, what we do is not push it, but load it:

[model loadViewIfNeeded];

This will load up the view from the story board, then invoke its -viewDidLoad. You should then be able to test its state.

I don't use Cedar, but I do have an OCUnit-based screencast of test-driven development of a view controller: How to Do UIViewController TDD

("model" is a very confusing name for a controller, by the way.)




回答2:


I usually test my view controllers in isolation with a setup like:

beforeEach(^{
            window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            subject = [storyboard instantiateViewControllerWithIdentifier:@"ViewControllerName"];
            window.rootViewController = subject;
            [window makeKeyAndVisible];
            subject.view should_not be_nil;
}];


来源:https://stackoverflow.com/questions/14466407/ios-testing-controllers-with-cedar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!