0

我有一个使用 Promise (PMKPromise) 的方法,我想使用 Kiwi 库进行单元测试。

我的方法如下所示:

- (void)fetchData {
[PMKPromise new:^(PMKPromiseFulfiller fulfill, PMKPromiseRejecter reject) {
    // make the request
}].then(^(NSDictionary *data){
    // code that I'd like to test
});
}

我想捕获并执行承诺完成块(称为“then”),并且我设法做到了(使用模拟的承诺):

// capture the promise completion block
__block void (^capturedBlock)(NSDictionary *);

[thePromise stub:@selector(then) withBlock:^id(NSArray *params) {
    return ^(id block){
        capturedBlock = block;
        return nil;
    };
}];

[myObj fetchData];

// execute the block
capturedBlock(@{});

我现在想做的是将这个丑陋的代码隐藏在一个类别中,以便将来在单元测试承诺时可以轻松使用。

我想将块“双指针”作为方法参数传递。

这可能是实现:

@interface NSObject (PMKPromiseTest)

- (void)captureThenBlock:(void (^ *)(NSDictionary *))capturedBlock;

@end

@implementation NSObject (PMKPromiseTest)

- (void)captureThenBlock:(void (^ *)(NSDictionary *))capturedBlock {

    [self stub:@selector(then) withBlock:^id(NSArray *params) {
        return ^(id block){
            *capturedBlock = block;
            return nil;
        };
    }];
}

@end

这就是我将如何使用它:

// capture the promise completion block:
void (^capturedBlock)(NSDictionary *);
[thePromise captureThenBlock:&capturedBlock];

[myObj fetchData];

// execute it
capturedBlock(@{});  // Exception! captureBlock is nil

不幸的是,这段代码不起作用。踏入时,确实捕获了该块。但是一旦出来,在执行捕获的块的那一刻,它就为零。

4

0 回答 0