Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
XCTest - Use custom notification center in test case and assert notification (not) triggered.
class CustomNotificationCenterTestCase: XCTestCase {
var notificationCenter: NotificationCenter!
override func setUp() {
super.setUp()
notificationCenter = NotificationCenter()
}
override func tearDown() {
notificationCenter = nil
super.tearDown()
}
func testTriggerNotification() {
let notificationExpectation = XCTNSNotificationExpectation(name: .fooBar,
object: nil,
notificationCenter: notificationCenter)
notificationCenter.post(name: .fooBar,
object: self)
wait(for: [notificationExpectation], timeout: 0.1)
}
func testDidNotTriggerNotification() {
let notificationExpectation = XCTNSNotificationExpectation(name: .fooBar,
object: nil,
notificationCenter: notificationCenter)
notificationExpectation.isInverted = true
// Run code that should not trigger a notification
if false {
notificationCenter.post(name: .fooBar,
object: nil)
}
wait(for: [notificationExpectation], timeout: 0.1)
}
}
extension Notification.Name {
static let fooBar = Notification.Name(rawValue: "fooBar")
}
// Run tests in playground
CustomNotificationCenterTestCase.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.