1

如何为按钮和下面的方法编写 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]:未调用预期方法:显示:

4

1 回答 1

3

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

//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];
}
于 2013-08-07T09:25:16.550 回答