【问题标题】:How to write iOS Unit Testing in SwiftUI when switching from background thread to main thread从后台线程切换到主线程时如何在 SwiftUI 中编写 iOS 单元测试
【发布时间】:2020-08-05 12:37:18
【问题描述】:

一旦我的后台操作完成,我需要调用 handleError 函数。由于 isToast,errorMessage 是我需要放在主线程中的已发布变量。我为测试 test__Failure() 编写了一个函数,但在模拟请求失败完成之前,此行在函数 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)

    }

【问题讨论】:

  • 您如何知道代码中的请求何时失败意味着 test_Failure 方法内部没有回调?如果可能,请更新您的代码,@Neha Pant。

标签: ios swift swiftui xctest


【解决方案1】:

您也可以延迟验证并在主线程上进行检查,如下所示:

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() 在主线程上异步运行,所以我们让它在同一个线程上运行和安排验证,但有点延迟(延迟 1 秒,但您可以将其更改为任何有意义的值)

【讨论】:

  • 嗨 Kiril,它对我有用,非常感谢 :),我们需要添加 1 个问题“等待(对于:[期望],超时:10.0)”?
  • 是的,你需要它来确保你的测试不会过早完成(它确保在主线程上运行的代码首先完成)。您当然可以将超时更改为较小的数字(尽管该超时仅在不满足期望时才重要)
猜你喜欢
  • 2019-11-17
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2012-07-21
  • 2020-01-24
  • 2011-05-16
相关资源
最近更新 更多