iOS testing controllers with Cedar

2019-09-12 05:02发布

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);
    });
});

2条回答
Evening l夕情丶
2楼-- · 2019-09-12 05:40

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;
}];
查看更多
我命由我不由天
3楼-- · 2019-09-12 05:48

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.)

查看更多
登录 后发表回答