大佬教程收集整理的这篇文章主要介绍了ios – 在Swift中为类扩展编写单元测试,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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!") } }
但是,我一直收到“使用未解析的标识符’presentAlert’”的错误.在咨询了SO thread之后,我尝试将公开添加到我的扩展中:
public func presentAlert(title:String,message:String)
但仍然没有运气.有人有见识吗?
编辑
基于@hkgumbs的答案,这是我的警报扩展的当前代码:
import Foundation protocol Presentable {} extension UIViewController { public func presentAlert(title: String,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,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(); }
>使presentAlert静态,以便您可以只使用UIViewController.presentAlert
>使presentAlert成为一个自由函数(不要把它放在扩展中)
>扩展协议 – 我认为这是最干净的选择
protocol Presentable {} extension Presentable { func presentAlert(title: String,message : String) { /* ... */ } }
然后,无论何时需要,您都可以扩展UIViewController:Presentable {}.在测试中,您可以使用虚拟类.这种方法的另一个好处是,如果需要,您可以在任何类型上重用该功能,而不会在不需要时全局暴露它.
附录
当我们扩展协议时,我们说“实现此协议的任何东西都将免费获得此方法.”这里的诀窍是这个协议是空的,因此很容易“实现”.
extension YourViewController: Presentable {}
以上是大佬教程为你收集整理的ios – 在Swift中为类扩展编写单元测试全部内容,希望文章能够帮你解决ios – 在Swift中为类扩展编写单元测试所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。