gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:09:26 25 4
gpt4 key购买 nike

我已经安装了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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com