Unit testing keyWindow using OCUnit throws an error

194 views Asked by At

I want to test my app delegate make window as key window after launch. So I write the following tests.

- (void)setUp
{
    window = [[UIWindow alloc] init];
    appDelegate = [[FGAppDelegate alloc] init];
    appDelegate.window = window;
    appDidFinishLaunchingReturn = [appDelegate application: nil didFinishLaunchingWithOptions:nil];
}

- (void)tearDown
{
    window = nil;
    appDelegate = nil;
}
- (void)testWindowIsKeyAfterApplicationLaunch
{
    STAssertTrue(window.keyWindow, @"App delegate's window should be key.");
}

In my app delegate the method applicaton:didFinishLaunchingWithOptions:

  ...
  self.window.rootViewController = self.tabBarController;
  [self.window makeKeyAndVisible];
  return YES;
}

The test failed and told me window.keyWindow should be true. Is there anything wrong? How can I fix the test?

1

There are 1 answers

2
Jon Reid On

I imagine this is a similar problem to my question iOS unit test: How to set/update/examine firstResponder? The actual activating of the key window is probably something that happens in the main run loop. To give it a chance to run, try calling this in your test:

- (void)runForShortTime
{
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];
}