如何为按钮和下面的方法编写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]:未调用预期方法:show:
这是我写的测试案例
-(void)testDisplayAlertView
{
OCMockObject *UIAlertViewMock = [OCMockObject mockForClass:[UIAlertView class]];
[[UIAlertViewMock expect] show];
[self.shuttleHelpViewController displayAlertView];
[UIAlertViewMock verify];
}
到目前为止,我已经实现了这个,它给了我这个错误:
OCMockObject [UIAlertView]:未调用预期方法:show:
答案 0 :(得分: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];
}