我正在使用Xcode和Swift的测试驱动开发来开发一个应用程序。
我想添加定时通知提醒人们回到应用程序执行一个动作。为此,我需要使用通知中心向我的用户请求授权。
为此,我希望在单元测试中编写一个测试,该测试仅在共享requestAuthorization(options:completionHandler:)实例调用其UNUserNotificationCenter方法时才通过。
我试过嘲笑UNUserNotificationCenter:
extension NotificationsExperimentsTests {
class MockNotificationCentre: UNUserNotificationCenter {
var didRequestAuthorization = false
override func requestAuthorization(options: UNAuthorizationOptions = [], completionHandler: @escaping (Bool, Error?) -> Void) {
didRequestAuthorization = true
}
}
}但当我试着在测试中初始化它时,
func test_requestAuthorization_IsCalled() {
var mockNotificationCenter = MockNotificationCentre()
}编译器告诉我:
无法构造'NotificationsExperimentsTests.MockNotificationCentre‘,因为它没有可访问的初始化器。
我不知道下一步该做什么,或者我想做的事是否可能?
发布于 2019-11-23 14:24:00
到目前为止我就在这里。感谢先前的答复:
Unit testing iOS 10 notifications
我的测试课:
import XCTest
import UserNotifications
@testable import NotificationsExperiments
class TestClass: XCTestCase {
override func setUp() {
super.setUp()
}
func testDoSomething() {
//Given
// Class being tested
let exampleClass = ExampleClass()
// Create your mock class.
let mockNotificationCenter = MockNotificationCenter()
exampleClass.notificationCenter = mockNotificationCenter
//When
exampleClass.doSomething()
//Then
XCTAssertTrue(mockNotificationCenter.didRequestAuthorization)
}
}
extension TestClass {
class MockNotificationCenter: MockUserNotificationCenterProtocol {
var didRequestAuthorization = false
func requestAuthorization(options: UNAuthorizationOptions, completionHandler: ((Bool, Error?) -> Void)) {
didRequestAuthorization = true
}
}
}我的示例类:
import Foundation
import UserNotifications
class ExampleClass {
#if DEBUG
var notificationCenter: MockUserNotificationCenterProtocol = UNUserNotificationCenter.current()
#else
var notificationCenter = UNUserNotificationCenter.current()
#endif
func doSomething() {
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
}
}
#if DEBUG
protocol MockUserNotificationCenterProtocol: class {
func requestAuthorization(options: UNAuthorizationOptions, completionHandler: ((Bool, Error?) -> Void))
}
extension UNUserNotificationCenter: MockUserNotificationCenterProtocol {
func requestAuthorization(options: UNAuthorizationOptions, completionHandler: ((Bool, Error?) -> Void)) {
print("Requested Authorization")
}
}
#endif这是可行的,但它不只是有点烦人。在调试模式下,它实际上不会发送授权请求,但在发布时会发送请求。
任何进一步的捐款都将欣然接受。
https://stackoverflow.com/questions/58960233
复制相似问题