测试在 swift 中调用函数的计时器

Testing timer which calls function in swift

括号后调用方法someFunc()。我需要在 sleep 方法之后立即调用它(恰好在时间过去之后)。似乎定时器在 testTimer() 超出括号(未通过测试)后调用执行块。

var value: String?

func testTimer() {
    let timer2 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
            self.someFunc()
        }

    sleep(2)
    XCTAssertNotNil(value)
}

func someFunc() {
    value = "someValue"
}

需要这个是因为我正在使用高阶函数并且我需要有一个外部函数(它会在应用程序中定期调用)。

您可能想使用 wait(for:timeout:) 方法。

在您的测试用例中保留 XCTestExpectation 的一个实例:

let expectation = XCTestExpectation(description: "value not nil")

在您的 someFunc 中,实现该期望:

expectation.fulfill()

在你的测试方法中,你做:

let timer2 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { timer in
        self.someFunc()
    }

wait(for: [expectation], timeout: 2)