如何在XCUITest中获取通知内容与通知标识符
在XCUITest中获取通知内容与标识符的方法
一、修正基础的通知定位逻辑
你的UITest代码存在几处关键问题,先修正基础的通知获取流程:
- Springboard初始化语法错误:原代码拆分了初始化语句,需合并为正确的初始化方式
- 通知元素定位错误:Springboard中的通知并非
buttons[@"NotificationCell"],需根据通知的标题/正文等实际内容定位 - 下拉通知中心的操作优化:直接操作Springboard的坐标比原App坐标更稳定
修正后的基础验证代码:
- (void)checkNotification { XCUIApplication *app = [[XCUIApplication alloc] init]; [app launch]; [app.buttons[@"btn"] tap]; // 触发通知展示 // 正确初始化Springboard XCUIApplication *springboard = [[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"]; // 下拉打开通知中心 XCUICoordinate *start = [springboard coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.0)]; XCUICoordinate *finish = [springboard coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)]; [start pressForDuration:0.1 thenDragToCoordinate:finish]; // 根据通知实际标题定位元素(替换为你的通知标题) XCUIElement *notificationTitle = springboard.staticTexts[@"测试通知标题"]; // 验证通知是否显示 XCTAssertTrue([notificationTitle waitForExistenceWithTimeout:5], @"通知未正常显示"); }
二、获取通知标识符的可行方案
XCUITest无法直接从Springboard的通知元素中拿到UNNotificationRequest的标识符(Springboard不暴露该内部属性),可以通过以下两种方式解决:
方案1:通过App Group共享标识符
利用App Group在主App和UITest Target之间共享通知ID:
- 在Xcode中给主App和UITest Target配置同一个App Group(Capabilities -> App Groups)
- 修改主App的
showNotificationWithIdentifier:方法,将生成的ID存入共享UserDefaults:
// 在return _id之前添加 NSUserDefaults *groupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.your.app.bundle.id"]; [groupDefaults setValue:_id forKey:@"LastNotificationIdentifier"]; [groupDefaults synchronize];
- 在UITest中读取共享的标识符:
- (void)checkNotificationIdentifier { // 触发通知后执行 NSUserDefaults *groupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.your.app.bundle.id"]; NSString *notificationId = [groupDefaults stringForKey:@"LastNotificationIdentifier"]; XCTAssertNotNil(notificationId, @"未获取到通知标识符"); // 此处可添加标识符的验证逻辑 }
方案2:将标识符嵌入通知可见内容
如果业务允许,可将标识符放入通知的subtitle字段(或userInfo),再在UITest中读取:
- 修改主App的通知创建代码:
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = title; content.body = description; content.subtitle = _id; // 将标识符放入subtitle content.sound = [UNNotificationSound defaultSound];
- 在UITest中读取subtitle作为标识符:
// 假设预期的标识符是"test_notification_id" XCUIElement *notificationSubtitle = springboard.staticTexts[@"test_notification_id"]; XCTAssertTrue([notificationSubtitle waitForExistenceWithTimeout:5], @"通知标识符不匹配");
三、验证通知标签(Category Identifier)
如果你的通知设置了categoryIdentifier,同样可以通过App Group共享的方式传递验证:
- 主App中存入共享数据:
content.categoryIdentifier = @"your_category_id"; [groupDefaults setValue:content.categoryIdentifier forKey:@"LastNotificationCategory"];
- UITest中读取验证:
NSString *categoryId = [groupDefaults stringForKey:@"LastNotificationCategory"]; XCTAssertEqualObjects(categoryId, @"your_category_id", @"通知标签不匹配");
内容的提问来源于stack exchange,提问作者Dung Tran
相关产品推荐
相关产品推荐

