如何与Kiwi异步测试代理

Doz*_*Doz 6 unit-testing objective-c ios6 kiwi

H伙计们,我多年来一直试图找到一些关于如何使用Kiwi测试来异步测试委托方法的好例子.

我有一个管理器类,它定义了测试协议,并在委托中返回了pass和fail方法.任何人都可以提供如何执行此操作的示例代码吗?我可以让测试类本身实现调用管理器上的方法吗?

多谢你们

Igo*_*gor 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()];
         });
    });
});
Run Code Online (Sandbox Code Playgroud)

可以在此链接上建立完整示例.


Tim*_*imD 4

您可以通过创建代表委托的模拟对象,然后检查模拟对象是否收到您期望的委托回调来完成我认为您想要实现的目标所以这个过程看起来像:

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

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

  • 将模拟设置为经理类的委托:

[manager setDelegate:delegateMock];

  • 创建一个包含管理器类将返回的数据的对象:

NSString *response = @"foo";

  • 设置最终应使用方法和响应对象调用模拟的断言(在本例中,我期望收到managerRepliedWithResponsefoo

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

  • 调用被测方法:

[manager performMyMethod];

关键是在调用方法之前设置期望,并使用shouldEventually它延迟检查断言并为manager对象提供执行该方法的时间。

您还可以使用 Kiwi wiki 上列出的一系列期望 - https://github.com/allending/Kiwi/wiki/Expectations

我在我的网站上的一篇文章中更详细地写了该过程,尽管它更具体地适合我正在处理的情况。

  • +1 对于非常微妙但非常重要的细节!“关键是在调用方法之前设置期望” (2认同)