I am working in swift, I want to refresh a page so I am sending it using notification, I am posting a notification in one ViewController and adding observer in another and i
Here is a simpler solution:
Step 1: Capture the notificationCenter object in an ambiant variable to be able to replace it with some spy class in your unit tests.
// In your production code:
var notificationCenter = NSNotificationCenter.defaultCenter()
// The code you are testing:
notificationCenter.postNotificationName("notificationName", object: nil)
Step 2: Define your spy class using inheritance to be able to detect whether the notification was posted or not.
// In your test code
private class NotificationCenterSpy: NotificationCenter {
var notificationName: String?
override func post(_ notificationName: String, object anObject: Any?)
{
self.notificationName = aName
}
}
Step 3: replace the ambiant variable in your unit test.
// In your test code:
// Given
// setup SUT as usual ...
let notificationCenterSpy = NotificationCenterSpy()
sut.notificationCenter = notificationCenterSpy
// When
sut.loadView()
// Then
XCTAssertEqual(notificationCenterSpy.notificationName, "notificationName")
Step 4: Testing the receiver View Controller
You should not test whether the receiver View Controller observes the change or not, you should test behaviour.
Something should be happening when the notification is received? That is what you should be testing, from your test code, post a notification and see if this behaviour happened (in your case if the page gets refreshed).