使用XCTest测试PresentedViewController

时间:2014-02-10 09:02:13

标签: ios iphone ios7 xctest

我有方法,我想测试:

- (void)sendMailToContact:(Contact *)conact
{
    self.contact = conact;

    if ([self isSendingAvaiable]) {

        MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        mailViewController.mailComposeDelegate = self;
        [mailViewController setToRecipients:@[self.contact.email]];

        [self.parentViewController presentViewController:mailViewController animated:YES completion:nil];
    }
}

测试......

- (void)testSendMailToContact_itShouldShowMFMailComposeViewController
{
    UIViewController *mockViewController = [[UIViewController alloc] init];
    [mockViewController viewDidLoad];

    MailComposer *mockMailComposer = [MailComposer sharedComposerWithController:mockViewController];

    [mockMailComposer sendMailToContact:[self mockContact]];

    XCTAssertTrue([mockViewController.presentedViewController isKindOfClass:[MFMailComposeViewController class]], @"");
}

但它无法正常工作。我应该将MFMailComposeViewController作为presentViewController,但我有null。我不知道该怎么办。请帮忙!

5 个答案:

答案 0 :(得分:5)

问题是mockViewController不在UIWindow层次结构中。尝试:

[UIApplication sharedApplication].keyWindow.rootViewController = mockViewController;

然后你也可以摆脱viewDidLoad电话。

答案 1 :(得分:2)

Here's the Swift 4 solution:

let vc = UIViewController()
UIApplication.shared.keyWindow?.rootViewController = vc

In your test…

XCTAssert(vc.presentedViewController is MyCustomViewController)

答案 2 :(得分:0)

您的测试用例包含一些问题。 您正在MFMailComposeViewController展示MailComposer。因此,您应拨打presentedViewController上的mockMailComposer而不是mockViewController

将其更改为:

- (void)testSendMailToContact_itShouldShowMFMailComposeViewController
{
    MailComposer *mockMailComposer = [MailComposer sharedComposerWithController:mockViewController];

    [mockMailComposer sendMailToContact:[self mockContact]];

    XCTAssertTrue([mockMailComposer.presentedViewController isKindOfClass:[MFMailComposeViewController class]], @"");
}

答案 3 :(得分:0)

看起来您的测试需要2个部分(或2个单独的测试)。第一部分应确保isSendingAvaiableNO并测试mockViewController.presentedViewControllernil。第二部分应确保isSendingAvaiableYES并测试mockViewController.presentedViewController是否为适当的类。

当测试失败时,重要的是确定错误是在于正在测试的代码还是在测试本身。

问题可能是isSendingAvaiableNO

答案 4 :(得分:0)

在测试之前将根ViewController实例添加到UIWindow,无需如上所述使用UIApplication.shared.keyWindow?.rootViewController

let window = UIWindow()
window.rootViewController = yourRootViewController
window.makeKeyAndVisible()


XCTAssert(yourRootViewController.presentedViewController is YourModalViewController)