2012-11-28 32 views
6

H guys, 我一直在努力寻找一些关于如何使用Kiwi测试异步测试委托方法的好例子。如何使用Kiwi异步测试代理

我有一个管理员类,它定义了用于测试的协议,并在委托中返回了一个通过和失败的方法。任何人都可以提供如何做到这一点的示例代码?我可以让测试类本身实现调用管理器上的方法吗?

谢谢你们

回答

4

你可以做什么,我想你试图通过创建为代表矗立在一个模拟对象,然后检查模拟对象收到您所期望的委托回调来实现。所以这个过程会是这样的:

  • 创建符合委托协议的模拟对象:

id delegateMock = [KWMock mockForProtocol:@protocol(YourProtocol)];

  • 设置模拟为经理级的代表:

[manager setDelegate:delegateMock];

  • 创建包含将通过您的经理类返回的数据对象:

NSString *response = @"foo";

  • 设定的说法,模拟应最终与方法和响应对象调用(在这种情况下,我期待收到managerRepliedWithResponsefoo

[[[delegateMock shouldEventually] receive] managerRepliedWithResponse:response];

  • 呼叫测试方法:

[manager performMyMethod];

的关键是设定预期之前调用该方法,并使用shouldEventually,其延迟断言被检查并给出manager对象时间执行该方法。

有一系列正在对猕猴桃维基上市的期望,你也可以使用 - https://github.com/allending/Kiwi/wiki/Expectations

我写的过程长达in more detail in a post on my site,尽管它更专门针对行动我处理情况。

+2

+1来建立的非常微妙,但非常重要的细节! “关键是在你调用方法之前设定期望” – Bach

+0

现在已经是一年多了,我正在为同样的事情而苦苦挣扎。它在expectFutureValue/without之前/之后根本不起作用。我可以让这个等待请求完成的唯一方法是通过具有真正的价值来检查某个地方。 – Hugo

6

可以例如,在做这样

SPEC_BEGIN(IFStackOverflowRequestSpec) 

describe(@"IFStackOverflowRequestSpec",^
{ 
    context(@"question request",^
    { 
     __block IFViewController *controller = nil; 

     beforeEach(^ 
     { 
      controller = [IFViewController mock]; 
     }); 

     it(@"should conform StackOverflowRequestDelegate protocol",^
     { 
      [[controller should] conformToProtocol:@protocol(StackOverflowRequestDelegate)]; 
     }); 

     it(@"should recieve receivedJSON",^
     { 
      NSString *questionsUrlString = @"http://api.stackoverflow.com/1.1/search?tagged=iphone&pagesize=20"; 

      IFStackOverflowRequest *request = [[IFStackOverflowRequest alloc] initWithDelegate:controller urlString:questionsUrlString]; 
      [[request fetchQestions] start]; 
      [[[controller shouldEventuallyBeforeTimingOutAfter(3)] receive] receivedJSON:any()]; 
     }); 

     it(@"should recieve fetchFailedWithError",^
     { 
      NSString *fakeUrl = @"asda"; 
      IFStackOverflowRequest *request = [[IFStackOverflowRequest alloc] initWithDelegate:controller urlString:fakeUrl]; 
      [[request fetchQestions] start]; 
      [[[controller shouldEventuallyBeforeTimingOutAfter(1)] receive] fetchFailedWithError:any()]; 
     }); 
    }); 
}); 

完整的示例可以this link.