【问题标题】:How to trigger failed test on timeout with waitForExpectations()?如何使用 waitForExpectations() 触发超时测试失败?
【发布时间】:2017-06-21 16:06:26
【问题描述】:

我从这里重新创建了示例:http://www.mokacoding.com/blog/testing-callbacks-in-swift-with-xctest/

我想使用waitForExpectations() 测试超时。这应该模拟一个已超时的长时间运行的进程。为此,我在被调用函数中设置了一个sleep() 命令,该命令比waitForExpectations() 中的超时时间长。

但是,sleep() 没有任何作用。测试总是通过。我也尝试将sleep() 放在completion(true) 之前,但这不会改变结果(即通过测试)。

任何想法我正在做什么以在超时时触发测试失败?

class SomeService {
    func doSomethingAsync(completion: (_ success: Bool) -> ()) {
        completion(true)
        sleep(5)
    }
}

在测试课中

let service = SomeService()
service.doSomethingAsync { (success) in
    XCTAssertTrue(success, "assert is true")
    expect.fulfill()
}

waitForExpectations(timeout: 3) { (error) in
    if let error = error {
        XCTFail("timeout errored: \(error)")
    }
}

【问题讨论】:

    标签: swift xcode xctest timeoutexception


    【解决方案1】:

    您的测试通过了,因为您在sleep 之前调用了completion,因此您的期望几乎立即得到满足 - 您等待 5 秒之前;虽然完成块是异步执行的,但它可能会在一秒钟内完成。

    如果您在completion 内部调用sleep,那么您的测试将按预期失败。但是,如果在调用 expect.fulfill() 时测试不再运行,您的测试可能会崩溃,因为 expect 在执行时可能不再存在,因为它可能在测试失败后立即被清理(大约 2期望实现前几秒)。

    class SomeService {
        func doSomethingAsync(completion: (_ success: Bool) -> ()) {
            DispatchQueue.main.async {
                completion(true)
            }
        }
    }
    

    测试:

    let service = SomeService()
    service.doSomethingAsync { (success) in
        XCTAssertTrue(success, "assert is true")
        sleep(5)
        expect.fulfill()
    }
    
    waitForExpectations(timeout: 3) { (error) in
        if let error = error {
            XCTFail("timeout errored: \(error)")
        }
    }
    

    【讨论】:

    • 如前所述,将sleep() 放在completion 之前没有任何效果。
    • 是的,有道理对不起,我已经改写了我的答案是正确的 - 您需要从异步完成块而不是在同步的 doSomethingAsync 中调用睡眠,因此睡眠将在测试开始等待。
    • 你将如何重新编码上面的代码,以便在 completion 中调用 sleep()
    • 用示例更新了答案。我还注意到您需要异步调用完成块,也添加了这一点。
    • 很棒的答案!我试过你所拥有的减去DispatchQueue.main.async{}。为什么这一切都不同?
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2017-04-20
    • 2016-03-15
    • 1970-01-01
    • 2017-12-04
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多