从后台线程切换到主线程时如何在 SwiftUI 中编写 iOS 单元测试

How to write iOS Unit Testing in SwiftUI when switching from background thread to main thread

后台操作完成后,我需要调用 handleError 函数。由于 isToast,errorMessage 是我需要放入主线程的已发布变量。我为测试 test__Failure() 编写了一个函数,但在 simulateRequestFailure 完成之前,该行在函数 XCTAssertTrue(self.viewModel.isToast) 中执行。怎么放等待,延迟几秒

@Published var isToast: Bool = false
@Published var eMessage: String = ""
func handleError() {
        DispatchQueue.main.async {
            self.isToast = true
            self.eMessage = “Test message”
        }
    }
func test__Failure() {
         // Some simulate response which call handleError    
         self.simulateRequestFailure()
        XCTAssertTrue(self.vm.isToast)

    }

你可以延迟验证并在主线程上检查它,像这样:

let expectation = XCTestExpectation()
self.simulateRequestFailure()
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
    XCTAssertTrue(self.vm.isToast)
    expectation.fulfill()
}
wait(for: [expectation], timeout: 10.0)

这是做什么的:

  • Expectation 允许将测试线程与 main 线程同步。 IE。在 expectation.fulfill() 发生或 10 秒到期之前测试不会完成(您当然可以将 10 秒更改为任何值)
  • simulateRequestFailure() 运行s 在主线程上是异步的,所以我们让它 运行 和在同一个线程上安排验证,但有点延迟(1 秒,但你可以将其更改为有意义的)