ios – 测试是否在视图控制器方法中调用performSegueWithIdentifier

前端之家收集整理的这篇文章主要介绍了ios – 测试是否在视图控制器方法中调用performSegueWithIdentifier前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在浏览一个应用程序并添加单元测试.该应用程序使用故事板编写,并支持iOS 6.1及更高版本.

我已经能够毫无问题地测试所有常用的返回方法.但是我目前难以接受我想要执行的某项测试:

基本上我有一个方法,让我们称之为doLogin:

  1. - (IBAction)doLogin:(UIButton *)sender {
  2.  
  3. // Some logic here
  4.  
  5. if ( //certain criteria to meet) {
  6. variable = x; // important variable set here
  7. [self performSegueWithIdentifier:@"memorableWord" sender:sender];
  8. } else {
  9. // handler error here
  10. }

所以我想测试是否调用segue并设置变量,或者加载MemorableWord视图控制器并且其中的变量是正确的.在doLogin方法中设置的变量将传递到prepareForSegue方法中的memorableWord segues’目标视图控制器.

我有OCMock设置和工作,我也使用XCTest作为我的单元测试框架.有没有人能够进行单元测试以涵盖这种情况?

对于这个领域的信息来说,Google和SO似乎相当简陋.很多关于简单基本测试的例子与iOS测试中更复杂的现实无关.

解决方法

你走在正确的轨道上,你的测试要检查:

>点击登录按钮时,将使用loginButton作为发件人调用doLogin
>如果某些条件为YES,请调用performSegue

因此,您实际上应该从登录按钮触发完整流程以执行Sese:

  1. - (void)testLogin {
  2. LoginViewController *loginViewController = ...;
  3. id loginMock = [OCMockObject partialMockForObject:loginViewController];
  4.  
  5. //here the expect call has the advantage of swallowing performSegueWithIdentifier,you can use forwardToRealObject to get it to go all the way through if necessary
  6. [[loginMock expect] performSegueWithIdentifier:@"memorableWord" sender:loginViewController.loginButton];
  7.  
  8. //you also expect this action to be called
  9. [[loginMock expect] doLogin:loginViewController.loginButton];
  10.  
  11. //mocking out the criteria to get through the if statement can happen on the partial mock as well
  12. BOOL doSegue = YES;
  13. [[[loginMock expect] andReturnValue:OCMOCK_VALUE(doSegue)] criteria];
  14.  
  15. [loginViewController.loginButton sendActionsForControlEvents:UIControlEventTouchUpInside];
  16.  
  17. [loginMock verify]; [loginMock stopMocking];
  18. }

您需要为“条件”实现一个属性,以便有一个可以使用’expect’模拟的getter.

重要的是要意识到“期望”只会模拟1次调用getter,后续调用将失败并显示调用意外方法…”.您可以使用’stub’来模拟所有调用,但这意味着它将始终返回相同的值.

猜你在找的iOS相关文章