-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathNotificationCenterObserveOnceTests.swift
More file actions
52 lines (46 loc) · 2.32 KB
/
Copy pathNotificationCenterObserveOnceTests.swift
File metadata and controls
52 lines (46 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import XCTest
@testable import WordPressShared
private let counterKey = "counter"
class NotificationCenterObserveOnceTests: XCTestCase {
let testNotification = Notification.Name("NotificationCenterObserveOnceTestNotification")
let notificationCenter = NotificationCenter.default
var observer: NSObjectProtocol?
override func tearDown() {
super.tearDown()
observer = nil
}
func testNotificationIsOnlyReceivedOnce() {
var timesReceived = 0
observer = notificationCenter.observeOnce(forName: testNotification, object: nil, queue: nil, using: { _ in
timesReceived += 1
})
notificationCenter.post(name: testNotification, object: nil)
XCTAssertEqual(timesReceived, 1, "Observer should get the notification once")
notificationCenter.post(name: testNotification, object: nil)
XCTAssertEqual(timesReceived, 1, "Observer should get the notification only once")
}
func testNotificationIsOnlyReceivedWhenMatchesFilter() {
var timesReceived = 0
observer = notificationCenter.observeOnce(forName: testNotification, object: nil, queue: nil, using: { _ in
timesReceived += 1
}, filter: { notification in
guard let counter = notification.userInfo?[counterKey] as? Int else {
return false
}
return counter > 2
})
notificationCenter.post(notification(counter: 0))
XCTAssertEqual(timesReceived, 0, "Observer should not receive the notification for counter < 2")
notificationCenter.post(notification(counter: 1))
XCTAssertEqual(timesReceived, 0, "Observer should not receive the notification for counter < 2")
notificationCenter.post(notification(counter: 2))
XCTAssertEqual(timesReceived, 0, "Observer should not receive the notification for counter < 2")
notificationCenter.post(notification(counter: 3))
XCTAssertEqual(timesReceived, 1, "Observer should get the notification once")
notificationCenter.post(notification(counter: 4))
XCTAssertEqual(timesReceived, 1, "Observer should get the notification only once")
}
private func notification(counter: Int) -> Foundation.Notification {
return Notification(name: testNotification, object: nil, userInfo: [counterKey: counter])
}
}