gpt4 book ai didi

ios - 如何测试 UIAlertController

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:38 25 4
gpt4 key购买 nike

我正在测试一个呈现 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)
}

因为这个函数在一个名为 ShopViewController 的类中,我假设测试它的正确方法是调用函数 shopViewController.presentBuyingErrorDiaologue() 然后使用 XCTAssertTrue(shopViewController .presentedViewController 是 UIAlertController)。但是,当我运行测试时断言语句失败。测试 UIAlertController 是呈现 View 的正确方法是什么?

最佳答案

在测试其可见性之前,您应该等待 UIAlertController 完全呈现,因此您可以尝试按照以下方式更改您的测试:

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)
}
}

您可以将 UIApplication.shared.keyWindow?.rootViewController 更改为您的 ShopViewController

关于ios - 如何测试 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48246885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com