13

XCTest waitForExpectationsWithTimeout:handler: 的文档指出

只有一个 -waitForExpectationsWithTimeout:handler: 可以在任何给定时间处于活动状态,但可以将多个离散序列 {期望 -> 等待} 链接在一起。

但是,我不知道如何实现这一点,也找不到任何示例。我正在研究一个类,首先需要找到所有可用的串行端口,选择正确的端口,然后连接到连接到该端口的设备。所以,我至少有两个期望,XCTestExpectation *expectationAllAvailablePorts 和 *expectationConnectedToDevice。我将如何链接这两个?

4

5 回答 5

7

我做了以下,它的工作原理。

expectation = [self expectationWithDescription:@"Testing Async Method Works!"];

[AsynClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
    [expectation fulfil];
    // whatever
}];

[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
    if (error) {
        XCTFail(@"Expectation Failed with error: %@", error);
    }
    NSLog(@"expectation wait until handler finished ");
}];

// do it again

expectation = [self expectationWithDescription:@"Testing Async Method Works!"];

[CallBackClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
    [expectation fulfil];
    // whatever
}];

[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
    if (error) {
        XCTFail(@"Expectation Failed with error: %@", error);
    }
    NSLog(@"expectation wait until handler finished ");
}];
于 2015-05-03T05:17:20.503 回答
3

迅速

let expectation1 = //your definition
let expectation2 = //your definition

let result = XCTWaiter().wait(for: [expectation1, expectation2], timeout: 10, enforceOrder: true)

if result == .completed {
    //all expectations completed in order
} 
于 2017-11-30T17:23:44.140 回答
2

将我的期望分配给一个弱变量对我有用。

于 2015-12-07T12:26:21.197 回答
0

在扩展 XCTestCase 的类中,您可以wait(for:timeout:)像这样使用:

let expectation1 = self.expectation(description: "expectation 1")
let expectation2 = self.expectation(description: "expectation 2")
let expectation3 = self.expectation(description: "expectation 3")
let expectation4 = self.expectation(description: "expectation 4")

// ...
// Do some asyc stuff, call expectation.fulfill() on each of the above expectations.
// ...

wait(for:[expectation1,expectation2,expectation3,expectation4], timeout: 8)

于 2020-08-08T19:11:38.727 回答
0

这似乎在 Swift 3.0 中也适用于我。

let spyDelegate = SpyDelegate()
var asyncExpectation = expectation(description: "firstExpectation")
spyDelegate.asyncExpectation = asyncExpectation
let testee = MyClassToTest(delegate: spyDelegate)
testee.myFunction() //asyncExpectation.fulfill() happens here, implemented in SpyDelegate

waitForExpectations(timeout: 30.0) { (error: Error?) in
    if let error = error {
        XCTFail("error: \(error)")
    }
}

asyncExpectation = expectation(description: "secoundExpectation")
spyDelegate.asyncExpectation = asyncExpectation
testee.delegate = spyDelegate
testee.myOtherFunction() //asyncExpectation.fulfill() happens here, implemented in SpyDelegate

waitForExpectations(timeout: 30.0) { (error: Error?) in
    if let error = error {
        XCTFail("error: \(error)")
    }
}
于 2017-04-05T14:43:45.747 回答