Created
August 6, 2018 12:57
-
-
Save fxm90/3c6f146ed977100d21f0a1f3e7bb37a2 to your computer and use it in GitHub Desktop.
XCTest - Use custom notification center in test case and assert notification (not) triggered.
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
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