Last active
January 25, 2026 15:07
-
-
Save fxm90/3c6f146ed977100d21f0a1f3e7bb37a2 to your computer and use it in GitHub Desktop.
XCTest - Assert notification is (not) posted when using a custom notification center.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import XCTest | |
| @MainActor | |
| final class CustomNotificationCenterTestCase: XCTestCase { | |
| func test_notification_isPosted() { | |
| // Given | |
| let notificationCenter = NotificationCenter() | |
| let notificationExpectation = XCTNSNotificationExpectation( | |
| name: .fooBar, | |
| object: nil, | |
| notificationCenter: notificationCenter, | |
| ) | |
| // When | |
| notificationCenter.post( | |
| name: .fooBar, | |
| object: self, | |
| ) | |
| // Then | |
| wait(for: [notificationExpectation], timeout: 0.1) | |
| } | |
| func test_notification_isNotPosted() { | |
| // Given | |
| let notificationCenter = NotificationCenter() | |
| let notificationExpectation = XCTNSNotificationExpectation( | |
| name: .fooBar, | |
| object: nil, | |
| notificationCenter: notificationCenter, | |
| ) | |
| notificationExpectation.isInverted = true | |
| // When | |
| // Run code that should not trigger a notification. | |
| if false { | |
| notificationCenter.post( | |
| name: .fooBar, | |
| object: nil, | |
| ) | |
| } | |
| // Then | |
| wait(for: [notificationExpectation], timeout: 0.1) | |
| } | |
| } | |
| // MARK: - Helper | |
| private extension Notification.Name { | |
| static let fooBar = Notification.Name(rawValue: "fooBar") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment