Skip to content

Instantly share code, notes, and snippets.

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

  • Save fxm90/23dc7debc5ee8245237c08e5af8679bc to your computer and use it in GitHub Desktop.

Select an option

Save fxm90/23dc7debc5ee8245237c08e5af8679bc to your computer and use it in GitHub Desktop.
XCTest - Assert notification is (not) posted.
import XCTest
@MainActor
final class NotificationTestCase: XCTestCase {
func test_notification_isPosted() {
// Given
expectation(
forNotification: .fooBar,
object: nil,
handler: nil,
)
// When
let notificationCenter = NotificationCenter.default
notificationCenter.post(
name: .fooBar,
object: self,
)
// Then
waitForExpectations(timeout: 0.1, handler: nil)
}
func test_notification_isNotPosted() {
// Given
let expectation = expectation(
forNotification: .fooBar,
object: nil,
handler: nil,
)
expectation.isInverted = true
// When
// Run code that should not trigger a notification.
if false {
let notificationCenter = NotificationCenter.default
notificationCenter.post(
name: .fooBar,
object: nil,
)
}
// Then
waitForExpectations(timeout: 0.1, handler: nil)
}
}
// 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