2

I have some problems with notifications testing. I reproduced the case in completely new and clean project and still can't receive my notification in tests.

In viewDidLoad() method I post my notification like this:

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    NotificationCenter.default.post(name: Notification.Name("Test"), object: nil, userInfo: nil);
}

and in my test I try to catch it:

var app: XCUIApplication!        
override func setUp() {
     super.setUp()
     continueAfterFailure = false
     app = XCUIApplication()
     app.launch()
}
func testExample() {
     expectation(forNotification: Notification.Name("Test"), object: nil) { notification in
         return true
     }
     waitForExpectations(timeout: 10, handler: nil)
}  

But it does not work.

I found some info here on Stackoverflow that I should fulfill expectation but my handler is not triggered to do so.

Simple code, simple test but it does not work - So frustrating.

BTW I'm using UITests with Xcode 9.4.1 and have found that with UnitTests all works fine. Possible bug?

Monet_z_Polski
  • 326
  • 5
  • 12
  • @Ashley Mills Why marked as a duplicated after 2 seconds? I already have implemented linked solution in my example code – Monet_z_Polski Sep 07 '18 at 07:41
  • Please post the whole of your test code including the bit where you instantiate the view controller. – Oletha Sep 08 '18 at 08:23
  • @Oletha Thx for response. I'm using UITests so manual controllers instantiation is not my case. I have updated my test snippet to include all test related code – Monet_z_Polski Sep 10 '18 at 06:56

1 Answers1

3

You will not be able to test the receipt of Notifications in UI tests because the UI test runner is run in a separate runtime to your app.

To directly test that a Notification is posted using expectation(forNotification:object:handler:), you will need to use a unit test. If you want to UI test this scenario, you will need to test the outcome of the notification is shown on screen, therefore implying that the notification was sent. If there is no visible outcome of the notification being posted, you will not be able to UI test it.

Oletha
  • 7,324
  • 1
  • 26
  • 46
  • I managed to test one part of notifications by output in UITest and the rest by listening to them in UnitTests. This is not perfect solution but good enough. Thx @Oletha for saving hairs on my head:) – Monet_z_Polski Sep 18 '18 at 05:50