Eri*_*ika 6 ios xctest swift uialertcontroller
我正在测试一个提供 UIAlertController 的函数,但测试一直失败。这是函数的样子:
func presentBuyingErrorDialogue() {
let alert = UIAlertController(
title: "Warning",
message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.",
preferredStyle: .alert
)
let okButton = UIAlertAction(title: "OK", style: .default)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)
由于此函数位于名为 ShopViewController 的类中,因此我假设测试此函数的正确方法是调用该函数shopViewController.presentBuyingErrorDiaologue()然后使用XCTAssertTrue(shopViewController.presentedViewController is UIAlertController). 但是,当我运行测试时,断言语句失败。测试 UIAlertController 是呈现视图的正确方法是什么?
You should wait that UIAlertController is fully presented before testing its visibility, so you might try to change your test following this way:
import XCTest
class UIAlertControllerTests: XCTestCase {
func presentBuyingErrorDialogue() {
let alert = UIAlertController(title: "Warning", message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default)
alert.addAction(okButton)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
func testPresentBuyingErrorDialogue() {
self.presentBuyingErrorDialogue()
let expectation = XCTestExpectation(description: "testExample")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
XCTAssertTrue(UIApplication.shared.keyWindow?.rootViewController?.presentedViewController is UIAlertController)
expectation.fulfill()
})
wait(for: [expectation], timeout: 1.5)
}
}
Run Code Online (Sandbox Code Playgroud)
你可能会UIApplication.shared.keyWindow?.rootViewController随着你的ShopViewController.
import ViewControllerPresentationSpyshopViewController.presentBuyingErrorDialogue()然后调用它的verify方法:
alertVerifier.verify(
title: "Warning",
message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.",
animated: true,
presentingViewController: shopViewController,
actions: [
.default("OK"),
]
)
Run Code Online (Sandbox Code Playgroud)
这会检查:
shopViewController..alert(默认情况下)除了捕获值之外,AlertVerifier 还可以让您轻松执行警报按钮的操作:
func test_alertOKButton() throws {
shopViewController.presentBuyingErrorDiaologue()
try alertVerifier.executeAction(forButton: "OK")
// Test the results here
}
Run Code Online (Sandbox Code Playgroud)
测试不需要任何等待的期望,因此它们非常快。
| 归档时间: |
|
| 查看次数: |
5352 次 |
| 最近记录: |