我有方法,我想测试:
- (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。我不知道该怎么办。请帮忙!
答案 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个单独的测试)。第一部分应确保isSendingAvaiable
为NO
并测试mockViewController.presentedViewController
为nil
。第二部分应确保isSendingAvaiable
为YES
并测试mockViewController.presentedViewController
是否为适当的类。
当测试失败时,重要的是确定错误是在于正在测试的代码还是在测试本身。
问题可能是isSendingAvaiable
是NO
。
答案 4 :(得分:0)
在测试之前将根ViewController实例添加到UIWindow,无需如上所述使用UIApplication.shared.keyWindow?.rootViewController
。
let window = UIWindow()
window.rootViewController = yourRootViewController
window.makeKeyAndVisible()
XCTAssert(yourRootViewController.presentedViewController is YourModalViewController)