In the following code, test 1 (test_postNotification) fails while test 2 (test_notificationsArePostedOnTheMainQueue) passes.
What concerns me, though, is that if I substitute the lines "let result = XCTWaiter.wait(for: [expectation], timeout: 0); XCTAssertEqual(result, .timedOut)" of test 2 with "wait(for: [expectation], timeout: 0.1)", then test number 1 passes.
I have cleaned the build folder and restarted Xcode and my computer, but the issue persists.
This concerns me because I would have said that the tests of the NotificationPosterTests class were isolated, but apparently they are not, since changing test 2 makes test 1 go from failing to passing.
Is this expected behavior?
import Foundation
import XCTest
extension Notification.Name {
static let menuPostRequest = Notification.Name("menuPostRequest")
static let editingOrderError = Notification.Name("editingOrderError")
}
class NotificationPoster {
let notificationCenter: NotificationCenter
init(notificationCenter: NotificationCenter = .default) {
self.notificationCenter = notificationCenter
}
func postNotification(_ notification: Notification) {
let _notificationCenter = notificationCenter // you can't use optional chaining nor conditional unwrapping on self to reference self.notificationCenter in the dispatch block because self is nil when self.postNotification(_:) is called
DispatchQueue.main.async {
_notificationCenter.post(notification)
}
}
}
final class NotificationPosterTests: XCTestCase {
private var sut: NotificationPoster!
private var notificationCenter: NotificationCenter!
override func setUp() {
super.setUp()
notificationCenter = NotificationCenter()
sut = NotificationPoster(notificationCenter: notificationCenter)
}
override func tearDown() {
notificationCenter = nil
sut = nil
super.tearDown()
}
func test_postNotification() {
let notification = Notification(name: .menuPostRequest)
let expectation = XCTNSNotificationExpectation(
name: notification.name,
object: notification.object,
notificationCenter: notificationCenter
)
sut.postNotification(notification)
wait(for: [expectation], timeout: 0.1) // don't make it 0.01
}
func test_notificationsArePostedOnTheMainQueue() {
let notification = Notification(name: .editingOrderError)
let expectation = XCTNSNotificationExpectation(
name: notification.name,
object: notification.object,
notificationCenter: notificationCenter
)
sut.postNotification(notification)
let result = XCTWaiter.wait(for: [expectation], timeout: 0)
XCTAssertEqual(result, .timedOut)
}
}