Paulo Andrade

Keeper of Secrets.

twitter github stackoverflow linkedin email
Inverted Expectations
Feb 14, 2019
One minute read

While writing some unit tests I needed to assert a notification did not get sent after calling a method.

The usual pattern for testing the sending of notifications is to use the existing XCTNSNotificationExpectation like so:

let notificationExpectation = expectation(forNotification: NSNotification.Name.SomeNotification, object: obj, handler: nil)
// exercise your code and wait for the expectation
wait(for: [notificationExpectation], timeout: 1.0)

But what about asserting a notification isn’t sent? Waiting for an expectation that’s not fulfilled will always result in an error… So I started browsing the headers of XCTest and I came across isInverted property on XCTestExpectation. The header documentation for that property states:

If an expectation is set to have inverted behavior, then fulfilling it will have a similar effect that failing to fulfill a conventional expectation has […]

I don’t remember anyone ever mentioned that this existed but this sounded like exactly what I wanted. So I changed my code enabled that and…

let notificationExpectation = expectation(forNotification: NSNotification.Name.SomeNotification, object: obj, handler: nil)
notificationExpectation.isInverted = true
// exercise your code and wait for the expectation
wait(for: [notificationExpectation], timeout: 1.0)

…voilà. When an expectation is inverted waiting for it will succeed if that expectation isn’t fulfilled 👌.


Tags: testing iOS macOS

Back to posts