【发布时间】:2016-12-19 21:24:18
【问题描述】:
我正在尝试为 Swift 中的类扩展编写单元测试。类扩展本身将呈现一个带有指定标题和消息的UIAlert:
extension UIViewController {
func presentAlert(title: String, message : String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
我为我的单元测试创建了一个包含以下代码的文件:
import XCTest
class AlertTest: XCTestCase {
func testAlert() {
let alert = presentAlert("Presented Alert", "This is an Alert!")
}
}
但是,我不断收到"Use of unresolved identifier 'presentAlert'" 的错误消息。在咨询此SO thread 后,我尝试将public 添加到我的扩展中:
public func presentAlert(title: String, message : String)
但仍然没有运气。有人有什么见解吗?
编辑
根据@hkgumbs 的回答,这是我当前的警报扩展代码:
import Foundation
protocol Presentable {}
extension UIViewController {
public func presentAlert(title: String, message : String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
在视图控制器中,我想在其中显示警报,这仍然是调用警报的正确方法,对吗?
self.presentAlert("Invalid URL", message: "Please try again")
其次,根据您的评论,这就是我通过在虚拟值上调用Presentable 所理解的,但这是不正确的,因为SomethingPresentable 没有成员PresentAlert。我的理解哪里出错了?
func testAlert() {
let app = XCUIApplication()
struct SomethingPresentable: Presentable {}
SomethingPresentable.presentAlert("Presented Alert", message: "This is an Alert!")
XCTAssert(app.alerts["Presented Alert"].exists)
app.alerts["Presented Alert"].tap();
}
编辑 2 @hkgumbs,根据你的最新评论,这就是我的扩展:
import Foundation
protocol Presentable {}
extension Presentable {
func presentAlert(title: String, message : String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
这就是我试图从我的 ViewController 中调用它的方式:
Presentable.presentAlert("Invalid URL", message: "Please try again")
但是,我收到错误消息“在类型 Self 上使用实例成员 presentAlert;您的意思是改用 Self 类型的变量吗?”
那么,我猜这就是测试的样子?
func testAlert() {
let app = XCUIApplication()
struct SomethingPresentable: Presentable {}
SomethingPresentable.presentAlert("Presented Alert", message: "This is an Alert!")
XCTAssert(app.alerts["Presented Alert"].exists)
app.alerts["Presented Alert"].tap();
}
【问题讨论】:
-
您的分机在
UIViewController,因此您需要在UIViewController上调用它。您调用它的方式也与声明不匹配。 -
@dan 感谢您发现这个错字...我刚刚在问题中修正了它。在单元测试中在 ViewController 上调用它会是什么样子?
标签: ios swift unit-testing xctest