ios - 我想为按钮和下面的方法编写一个OCMock单元测试。我该怎么写?

标签 ios cocoa-touch ocmock

如何为按钮和下面的方法编写OCMock单元测试

//This method displays the UIAlertView when Call Security button is pressed. 
-(void) displayAlertView
{
     UIAlertView *callAlert = [[UIAlertView alloc] initWithTitle:@"Call Security" message:@"(000)-000-0000" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call", nil];
     [callAlert show];
     if([[callAlert buttonTitleAtIndex:1] isEqualToString:@"Call"])
     {
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://0000000000"]];
     }
}
//This Button calls the above method.
-(IBAction)callSecurityButton 
{
     [self displayAlertView];
}

到目前为止,我已经实现了它,这给了我这个错误:

OCMockObject [UIAlertView]:未调用预期方法:显示:

这是我写的测试用例
-(void)testDisplayAlertView
{
    OCMockObject *UIAlertViewMock = [OCMockObject mockForClass:[UIAlertView class]];
    [[UIAlertViewMock expect] show];
    [self.shuttleHelpViewController displayAlertView];
    [UIAlertViewMock verify];
}

到目前为止,我已经实现了它,这给了我这个错误:

OCMockObject [UIAlertView]:未调用预期方法:显示:

最佳答案

模拟对象和在方法内部创建的对象不相同。应该是这样的:

//This method displays the UIAlertView when Call Security button is pressed. 
-(void)displayAlertView:(UIAlertView *)callAlert
{
    [callAlert show];
    if([[callAlert buttonTitleAtIndex:1] isEqualToString:@"Call"])
    {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://0000000000"]];
    }
}

//This Button calls the above method.
-(IBAction)callSecurityButton 
{
    UIAlertView *callAlert = [[UIAlertView alloc] initWithTitle:@"Call Security" message:@"(000)-000-0000" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call", nil];
    [self displayAlertView:callAlert];
}

并测试方法:
-(void)testDisplayAlertView
{
    OCMockObject *UIAlertViewMock = [OCMockObject mockForClass:[UIAlertView class]];
    [[UIAlertViewMock expect] show];
    [self.shuttleHelpViewController displayAlertView:UIAlertViewMock];
    [UIAlertViewMock verify];
}

关于ios - 我想为按钮和下面的方法编写一个OCMock单元测试。我该怎么写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083755/

相关文章:

ios - 获取所有在后台运行的应用程序的屏幕截图(允许使用私有(private) API)

ios - OCMock 设置模拟类,其属性并获得基本了解

ios - 是否可以使用 OCMock 来模拟类方法和协议(protocol)?

ios - 如何每行显示 3 个单元格 UICollectionView

iOS Cocoa UITableView 旋转后的位置

ios - 如何使用OCMock 3检查单元测试中函数的返回值

ios - 后台的 NSTimer 行为(addTimer :, beginBackgroundTaskWithExpirationHandler :)

无法安装 iOS IPA 文件,因为无法验证其完整性

ios - tzID GMT-8 是否有时区名称

cocoa-touch - 为什么-init是实例方法而+initialize是类方法?