Skip to content

Instantly share code, notes, and snippets.

@fxm90
Last active January 25, 2026 15:07
Show Gist options
  • Select an option

  • Save fxm90/3c6f146ed977100d21f0a1f3e7bb37a2 to your computer and use it in GitHub Desktop.

Select an option

Save fxm90/3c6f146ed977100d21f0a1f3e7bb37a2 to your computer and use it in GitHub Desktop.
XCTest - Assert notification is (not) posted when using a custom notification center.
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