在Xcode UI测试的测试用例中延迟/等待

时间:2015-07-02 10:55:50

标签: ios9 xcode-ui-testing xcode7-beta2 xctwaiter

我正在尝试使用Xcode 7 beta 2中提供的新UI测试来编写测试用例。该应用程序有一个登录屏幕,用于调用服务器进行登录。与此相关的延迟是因为它是异步操作。

在继续进一步的步骤之前,有没有办法在XCTestCase中引起延迟或等待机制?

没有适当的文档,我浏览了类的Header文件。无法找到与此相关的任何内容。

有任何想法/建议吗?

13 个答案:

答案 0 :(得分:205)

另外,你可以睡觉:

sleep(10)

由于UITests在另一个进程中运行,因此可行。我不知道它是多么可取,但它确实有效。

答案 1 :(得分:150)

异步UI测试是在Xcode 7 Beta 4中引入的。要等待带有文本的标签" Hello,world!"看来你可以做到以下几点:

let app = XCUIApplication()
app.launch()

let label = app.staticTexts["Hello, world!"]
let exists = NSPredicate(format: "exists == 1")

expectationForPredicate(exists, evaluatedWithObject: label, handler: nil)
waitForExpectationsWithTimeout(5, handler: nil)

我的博客上可以找到更多details about UI Testing

答案 2 :(得分:68)

Xcode 9 引入了XCTWaiter

的新技巧

测试用例明确等待

wait(for: [documentExpectation], timeout: 10)

Waiter实例委托测试

XCTWaiter(delegate: self).wait(for: [documentExpectation], timeout: 10)

Waiter类返回结果

let result = XCTWaiter.wait(for: [documentExpectation], timeout: 10)
switch(result) {
case .completed:
    //all expectations were fulfilled before timeout!
case .timedOut:
    //timed out before all of its expectations were fulfilled
case .incorrectOrder:
    //expectations were not fulfilled in the required order
case .invertedFulfillment:
    //an inverted expectation was fulfilled
case .interrupted:
    //waiter was interrupted before completed or timedOut
}

sample usage

在Xcode 9之前

目标C

- (void)waitForElementToAppear:(XCUIElement *)element withTimeout:(NSTimeInterval)timeout
{
    NSUInteger line = __LINE__;
    NSString *file = [NSString stringWithUTF8String:__FILE__];
    NSPredicate *existsPredicate = [NSPredicate predicateWithFormat:@"exists == true"];

    [self expectationForPredicate:existsPredicate evaluatedWithObject:element handler:nil];

    [self waitForExpectationsWithTimeout:timeout handler:^(NSError * _Nullable error) {
        if (error != nil) {
            NSString *message = [NSString stringWithFormat:@"Failed to find %@ after %f seconds",element,timeout];
            [self recordFailureWithDescription:message inFile:file atLine:line expected:YES];
        }
    }];
}

<强> USAGE

XCUIElement *element = app.staticTexts["Name of your element"];
[self waitForElementToAppear:element withTimeout:5];

<强>夫特

func waitForElementToAppear(element: XCUIElement, timeout: NSTimeInterval = 5,  file: String = #file, line: UInt = #line) {
        let existsPredicate = NSPredicate(format: "exists == true")

        expectationForPredicate(existsPredicate,
                evaluatedWithObject: element, handler: nil)

        waitForExpectationsWithTimeout(timeout) { (error) -> Void in
            if (error != nil) {
                let message = "Failed to find \(element) after \(timeout) seconds."
                self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
            }
        }
    }

<强> USAGE

let element = app.staticTexts["Name of your element"]
self.waitForElementToAppear(element)

let element = app.staticTexts["Name of your element"]
self.waitForElementToAppear(element, timeout: 10)

SOURCE

答案 3 :(得分:56)

iOS 11 / Xcode 9

<#yourElement#>.waitForExistence(timeout: 5)

这是此网站上所有自定义实施的绝佳替代品!

请务必在此处查看我的答案:https://stackoverflow.com/a/48937714/971329。在那里,我描述了一种等待请求的替代方案,这将大大减少测试运行的时间!

答案 4 :(得分:27)

从Xcode 8.3开始,我们可以使用XCTWaiter http://masilotti.com/xctest-waiting/

func waitForElementToAppear(_ element: XCUIElement) -> Bool {
    let predicate = NSPredicate(format: "exists == true")
    let expectation = expectation(for: predicate, evaluatedWith: element, 
                                  handler: nil)

    let result = XCTWaiter().wait(for: [expectation], timeout: 5)
    return result == .completed
}

另一个诀窍就是写一个wait函数,感谢John Sundell向我显示它

extension XCTestCase {

  func wait(for duration: TimeInterval) {
    let waitExpectation = expectation(description: "Waiting")

    let when = DispatchTime.now() + duration
    DispatchQueue.main.asyncAfter(deadline: when) {
      waitExpectation.fulfill()
    }

    // We use a buffer here to avoid flakiness with Timer on CI
    waitForExpectations(timeout: duration + 0.5)
  }
}

并像

一样使用它
func testOpenLink() {
  let delegate = UIApplication.shared.delegate as! AppDelegate
  let route = RouteMock()
  UIApplication.shared.open(linkUrl, options: [:], completionHandler: nil)

  wait(for: 1)

  XCTAssertNotNil(route.location)
}

答案 5 :(得分:9)

修改

实际上我刚刚想到,在Xcode 7b4中,UI测试现在已经有了 expectationForPredicate:evaluatedWithObject:handler:

<强>原始

另一种方法是将运行循环旋转一段时间。如果你知道你需要等待多长时间(估计)

,那真的很有用

的OBJ-C: [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: <<time to wait in seconds>>]]

夫特: NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: <<time to wait in seconds>>))

如果您需要测试某些条件以继续测试,这不是非常有用。要运行条件检查,请使用while循环。

答案 6 :(得分:9)

根据@Ted's answer,我已使用此扩展程序:

extension XCTestCase {

    // Based on https://stackoverflow.com/a/33855219
    func waitFor<T>(object: T, timeout: TimeInterval = 5, file: String = #file, line: UInt = #line, expectationPredicate: @escaping (T) -> Bool) {
        let predicate = NSPredicate { obj, _ in
            expectationPredicate(obj as! T)
        }
        expectation(for: predicate, evaluatedWith: object, handler: nil)

        waitForExpectations(timeout: timeout) { error in
            if (error != nil) {
                let message = "Failed to fulful expectation block for \(object) after \(timeout) seconds."
                self.recordFailure(withDescription: message, inFile: file, atLine: line, expected: true)
            }
        }
    }

}

您可以像这样使用

let element = app.staticTexts["Name of your element"]
waitFor(object: element) { $0.exists }

它还允许等待元素消失,或者任何其他属性改变(通过使用适当的块)

waitFor(object: element) { !$0.exists } // Wait for it to disappear

答案 7 :(得分:4)

以下代码仅适用于Objective C.

- (void)wait:(NSUInteger)interval {

    XCTestExpectation *expectation = [self expectationWithDescription:@"wait"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [expectation fulfill];
    });
    [self waitForExpectationsWithTimeout:interval handler:nil];
}

只需调用此函数,如下所示。

[self wait: 10];

答案 8 :(得分:3)

这将创建一个延迟,而不会使线程进入睡眠状态或在超时时引发错误:

let delayExpectation = XCTestExpectation()
delayExpectation.isInverted = true
wait(for: [delayExpectation], timeout: 5)

由于期望被颠倒了,它将安静地超时。

答案 9 :(得分:3)

我们在我目前的公司是如何做的,我们创建了一个 XCUIElement 表达式期望(以创建一个通用的等待方法)。我们通过以下方式来确保它是可维护的(很多期望变化,并且不想创建很多方法/特定谓词来这样做。

斯威夫特 5

基本方法

该表达式用于形成动态谓词值。我们可以从谓词创建 XCTNSPredicateExpectation,然后我们将其传递给 XCTWaiter 以显式等待。如果结果不是 completed,那么我们会失败并显示可选消息。

@discardableResult
func wait(
    until expression: @escaping (XCUIElement) -> Bool,
    timeout: TimeInterval = 15,
    message: @autoclosure () -> String = "",
    file: StaticString = #file,
    line: UInt = #line
) -> Self {
    if expression(self) {
        return self
    }

    let predicate = NSPredicate { _, _ in
        expression(self)
    }

    let expectation = XCTNSPredicateExpectation(predicate: predicate, object: nil)

    let result = XCTWaiter().wait(for: [expectation], timeout: timeout)

    if result != .completed {
        XCTFail(
            message().isEmpty ? "expectation not matched after waiting" : message(),
            file: file,
            line: line
        )
    }

    return self
}

使用

app.buttons["my_button"].wait(until: { $0.exists })
app.buttons["my_button"].wait(until: { $0.isHittable })

键路径

然后我们将其包装在一个方法中,其中 keyPath 和 match 值构成了表达式。

@discardableResult
func wait<Value: Equatable>(
    until keyPath: KeyPath<XCUIElement, Value>,
    matches match: Value,
    timeout: TimeInterval = 15,
    message: @autoclosure () -> String = "",
    file: StaticString = #file,
    line: UInt = #line
) -> Self {
    wait(
        until: { $0[keyPath: keyPath] == match },
        timeout: timeout,
        message: message,
        file: file,
        line: line
    )
}

使用

app.buttons["my_button"].wait(until: \.exists, matches: true)
app.buttons["my_button"].wait(until: \.isHittable, matches: false)

然后您可以包装该方法,其中对于我发现的最常见的用例,match 值始终为 true

使用

app.buttons["my_button"].wait(until: \.exists)
app.buttons["my_button"].wait(until: \.isHittable)

我写了一篇关于它的帖子,并在那里获取了完整的扩展文件:https://sourcediving.com/clean-waiting-in-xcuitest-43bab495230f

答案 10 :(得分:0)

根据XCUIElement .exists的API可用于检查查询是否存在,因此以下语法在某些情况下可能有用!

let app = XCUIApplication()
app.launch()

let label = app.staticTexts["Hello, world!"]
while !label.exists {
    sleep(1)
}

如果您确信您的期望最终会得到满足,那么您可以尝试运行此功能。应该注意的是,如果等待时间过长可能会导致崩溃,在这种情况下应该使用来自@Joe Masilotti帖子的waitForExpectationsWithTimeout(_,handler:_)

答案 11 :(得分:0)

在我的情况下,sleep产生了副作用,所以我使用了

XCTWaiter.wait(for: [XCTestExpectation(description: "Hello World!")], timeout: 2.0)

答案 12 :(得分:0)

sleep将阻塞线程

“线程被阻塞时,不会发生运行循环处理。”

您可以使用waitForExistence

let app = XCUIApplication()
app.launch()

if let label = app.staticTexts["Hello, world!"] {
label.waitForExistence(timeout: 5)
}