断言代码在单元测试中的某个时刻得到 运行?

Assert that code gets ran at some point in unit test?

我有这个单元测试:

func testState() {
    searchController.filter.query = "Missouri"
    searchController.resultsSignal.subscribePast(with: self) { sections in

        if sections.count < 1 { return }
        // Want to test that code at least gets to here at some point
        ...
    }
}

而且我想确保我至少在某个时候超过了 if sections.count < 1 { return } 线。

因为当信号被触发时它得到 运行,我不关心是否有不同的信号在某个时候被触发,但我确实想确保 sections.count > 0 在测试的某个时刻。

有办法吗?我正在考虑使用布尔值并将其初始化为 false,然后如果 sections.count 大于 1 则将其设置为 true,并断言该值为 true,但这不起作用,除非我做了延迟,因为我我正在使用信号。谢谢

您可以使用 XCTestExpectation 并在 sections.count 之后调用 .fulfill 来通知测试异步测试已成功。

func testState() {
    let expectation = XCTestExpectation(description: "Should execute")
    searchController.filter.query = "Missouri"
    searchController.resultsSignal.subscribePast(with: self) { sections in

        if sections.count < 1 { return }
        // Want to test that code at least gets to here at some point
        expectation.fulfill()
        ...
    }
    wait(for: [expectation], timeout: 10) // Will fail if .fulfill does not get called within ten seconds
}