首页 > 解决方案 > 快速/灵活的通知用户信息测试

问题描述

我正在快速/灵活地查看通知支持,例如:

expect {
    NotificationCenter.default.postNotification(testNotification)
}.to(postNotifications(equal([testNotification]))

有没有办法让我掌握返回以检查 userInfo 的通知?我的目标是调用一个发布通知的方法,然后检查该通知 userInfo 并确保键/值对正确。

快速:2.1.0
敏捷:8.0.1

标签: iosunit-testingquick-nimble

解决方案


我最终这样做了:

func equalName(_ expectedName: Notification.Name, condition: @escaping (([AnyHashable: Any]) -> Bool)) -> Predicate<[Notification]> {
    return Predicate.define("equal <\(stringify(expectedName))>") { actualExpression, msg in
        guard let actualValue = try actualExpression.evaluate() else {
            return PredicateResult(status: .fail, message: msg)
        }

        let actualNames = actualValue
            .filter { $0.name == expectedName }
            .filter { notification in
                guard let userInfo = notification.userInfo else {
                    return false
                }

                return condition(userInfo)
            }
            .compactMap { $0.name }
        let matches = actualNames.contains(expectedName)
        return PredicateResult(bool: matches, message: msg)
    }
}

然后在呼叫站点您可以提供条件..


推荐阅读