首页 > 解决方案 > XCUITest 验证 ui 中断处理程序发生

问题描述

我对 swift 和 xcuitest 很陌生。我最近遇到addUIInterruptionMonitor了处理可以弹出的警报。我想知道的是如何验证警报是否发生以及处理程序是否已处理。以以下为例

addUIInterruptionMonitorWithDescription("Location Services") { 
  (alert) -> Bool in
  alert.buttons["Allow"].tap()
  return true
}

app.buttons["Request Location"].tap()
app.tap() // need to interact with the app again for the handler to fire
// after this if the handler never gets called I want the test to fail

我想测试警报是否真的发生,但据我了解,在我最后一次之后,tap()如果警报从未被触发,我的处理程序将不会被调用。我需要测试警报是否真的发生了,然后可能会在处理程序的内容中添加一些断言

标签: swiftiphonetestingxcuitest

解决方案


我似乎已经回答了我自己关于进一步调查的问题。对于使用 xcuitest 进行的异步测试,我可以使用XCTestExpectation,它在创建时会导致测试等到期望得到满足,或者在某个超时后失败。这样我上面的代码就变成了:

let expectation = XCTestExpectation(description: "Location Service Alert")

let locationMonitorToken = addUIInterruptionMonitorWithDescription("Location Services") { 
  (alert) -> Bool in
  alert.buttons["Allow"].tap()
  expectation.fulfill() // test waits for this before passing
  return true
}

app.buttons["Request Location"].tap()
app.tap() // alert triggered here
wait(for: [expectation], timeout: 3.0)
removeUIInterruptionMonitor(locationMonitorToken)

更新:忘记放入wait(for: [expectation], timeout: 3.0)触发后的警报以确保调用处理程序。


推荐阅读