gpt4 book ai didi

ios - 单元测试本地通知

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:45 24 4
gpt4 key购买 nike

我花了大约一天的时间试图找出一种方法来对我的本地通知进行单元测试。

我正在使用 Swift 2.2 和 Xcode 7.3

本质上,我有一个精简的 API,它生成 UILocalNotification,这是通过 UIApplication.sharedApplication().presentLocalNotificationNow 触发的

在我的 AppDelegate 中,我实现了 application:didReceiveLocalNotification 方法来显示 UIAlertController 如下

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
if application.applicationState == .Active {
var topController : UIViewController = (application.keyWindow?.rootViewController)!

while ((topController.presentedViewController) != nil) {
topController = topController.presentedViewController!
}

let alert = UIAlertController(title: notification.alertTitle, message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in}))

topController.presentViewController(alert, animated: true, completion: nil)
}
}

手动运行时,效果很好。我可以看到生成的消息和显示的警报。

不过,我想做的是提供一个单元测试来验证此功能。

我没有测试 iOS 的经验。

我的第一个想法是以某种方式模拟 UIApplicationDeledgate,这样我就可以测试是否调用了 application:didReceiveLocalNotification,比如 UIApplication.sharedApplication ().delegate = mockedDelegate,当我尝试这样做时它崩溃了。

我的下一个想法是对警报对话框使用 UI 测试和监视器。这在一定程度上起作用了,我能够注册通知(并获得“允许通知”对话框,我能够使用 XCTestCase API 点按该对话框),但通知显示为横幅,而不是警报(来自应用程序本身)!?

此时我不知道接下来要尝试什么。

我目前没有使用任何模拟框架,我的理解是 Swift 不适合它们,但这只是我的阅读(除非我愿意从 NSObject 扩展) >).

最佳答案

您可以通过创建本地通知并在您的测试中直接调用它来测试委托(delegate)方法,如下所示:

let notification = UILocalNotification()
notification.alertBody = "Attention!"
var userInfo = [String: String]()
userInfo["name"] = "notification"
notification.userInfo = userInfo
// further notification setup

let appDelegate = UIApplication.sharedApplication().delegate
appDelegate?.application!(UIApplication.sharedApplication(), didReceiveLocalNotification: notification)

您可以调用其他委托(delegate)方法,类似于测试通知操作等。

关于ios - 单元测试本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126388/

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