问题描述
测试代码如下:
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailComposeController = [[MFMailComposeViewController alloc] init];
[mailComposeController setSubject:nil];
[mailComposeController setToRecipients:@[Text_Email_Me_Email]];
[mailComposeController setMailComposeDelegate:self];
[self.frontViewController presentViewController:mailComposeController
animated:YES
completion:nil];
}
这是测试代码:
id mailComposerMock = [OCMockObject mockForClass:[MFMailComposeViewController class]];
[[[mailComposerMock stub] andReturnValue:@YES] canSendMail];
[[[mailComposerMock stub] andReturn:mailComposerMock] alloc];
(void)[[[mailComposerMock stub] andReturn:mailComposerMock] init];
[[[mailComposerMock expect] andReturn:nil] setMailComposeDelegate:self.contactItemManager];
[[[mailComposerMock expect] andReturn:nil] setToRecipients:@[@"email@email.com"]];
[[[mailComposerMock expect] andReturn:nil] setSubject:nil];
[[[mailComposerMock expect] andReturn:self.frontViewController] presentingViewController];
[self.contactItemManager handleSelectionOfContentItemWithTitle:Text_Contact_Me_Email_Me];
[mailComposerMock verify];
错误状态:
[theTestingClass testEmailMe] failed: OCMockObject[MFMailComposeViewController]: unexpected method invoked: setSubject:nil
正如你所看到的,我已经在调用 setSubject.
And as you can see, I am calling setSubject already.
推荐答案
我还没有确定发生这种情况的确切原因,但是如果你构建了一些依赖注入,你可以绕过它:
I haven't determined exactly why this is happening, but you can get around it if you build in some dependency injection:
- (void)handleSelectionOfContentItemWithTitle:(NSString *)title mailComposeViewController:(MFMailComposeViewController *)mailComposeViewController;
此外,避免在 void 方法中返回 nil
.
Additionally, avoid returning nil
in void methods.
[[mailComposerMock expect] setSubject:nil];
如果您要将模拟对象传递给可以将 compose 控制器作为参数的方法,那么您的测试应该可以工作.
If you were to pass your mock object into a method that could take the compose controller as an argument, your test should work.
或者,您可以模拟自定义工厂方法:
Alternatively you could mock a custom factory method:
+ (MFMailComposeViewController*)mailComposeViewController
{
return [[MFMailComposeViewController alloc] init];
}
不是一个很好的答案,但希望是一个有用的解决方法.我避免亲自嘲笑 alloc
和 init
.
Not quite an answer, but hopefully a helpful workaround. I avoid mocking alloc
and init
personally.
这篇关于OCMock - 意外的方法虽然预期被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!