iphone - 如何对异步 API 进行单元测试?

标签 iphone unit-testing asynchronous google-toolbox-for-mac

我已经安装了Google Toolbox for Mac进入 Xcode 并按照说明设置单元测试发现 here .

一切都很好,我可以在所有对象上测试我的同步方法,效果非常好。然而,我实际上想通过调用委托(delegate)上的方法来测试大多数复杂的 API 异步返回结果 - 例如,对文件下载和更新系统的调用将立即返回,然后在文件下载完成时运行 -fileDownloadDidComplete: 方法.

我如何将其作为单元测试进行测试?

看来我想要 testDownload 函数,或者至少是测试框架“等待” fileDownloadDidComplete: 方法运行。

编辑:我现在已切换到使用 XCode 内置 XCTest 系统,并发现 TVRSMonitor Github 上提供了一种非常简单的方法来使用信号量等待异步操作完成。

例如:

- (void)testLogin {
  TRVSMonitor *monitor = [TRVSMonitor monitor];
  __block NSString *theToken;

  [[Server instance] loginWithUsername:@"foo" password:@"bar"
                               success:^(NSString *token) {
                                   theToken = token;
                                   [monitor signal];
                               }

                               failure:^(NSError *error) {
                                   [monitor signal];
                               }];

  [monitor wait];

  XCTAssert(theToken, @"Getting token");
}

最佳答案

我遇到了同样的问题,并找到了适合我的不同解决方案。

我使用“老派”方法通过使用信号量将异步操作转变为同步流,如下所示:

// create the object that will perform an async operation
MyConnection *conn = [MyConnection new];
STAssertNotNil (conn, @"MyConnection init failed");

// create the semaphore and lock it once before we start
// the async operation
NSConditionLock *tl = [NSConditionLock new];
self.theLock = tl;
[tl release];    

// start the async operation
self.testState = 0;
[conn doItAsyncWithDelegate:self];

// now lock the semaphore - which will block this thread until
// [self.theLock unlockWithCondition:1] gets invoked
[self.theLock lockWhenCondition:1];

// make sure the async callback did in fact happen by
// checking whether it modified a variable
STAssertTrue (self.testState != 0, @"delegate did not get called");

// we're done
[self.theLock release]; self.theLock = nil;
[conn release];

确保调用

[self.theLock unlockWithCondition:1];

然后在代表中。

关于iphone - 如何对异步 API 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2162213/

相关文章:

iphone - 使用 Oauth 从 iPhone 应用程序发送推文

unit-testing - Rust 测试甚至无法运行

ios - 从 URL Swift 异步下载和上传数据

python - 如何将 tweepy api 调用转换为异步

iphone DatePickerView - PickerView - 模态视图还是弹出窗口?什么是最好的?

iphone - 控制背景音乐播放

iphone - 操纵 nsmutabledata

perl - 这是测试 Perl 代码的好方法吗?

python - 单元测试数据应该简化还是现实?

javascript - 返回服务对本地存储的 Angular 数据的 promise