Search code examples
swiftcallbackxctestxctestexpectation

XCTest: Check That a Callback is Not Called


I know how to wait for a callback with expectations in XCT. However, what about testing for the inverse?

Below is an example of a test that I have as part of my tests:

manager.state = .initialized
let exp = expectation(description: "expectation")
manager.login { state, error in
    exp.fulfill()
    XCTAssert(state == .initialized)
    XCTAssertNil(error)
}
waitForExpectations(timeout: 1)

In the next test I'm writing I would like a test to ensure that a callback is not called when my manager object's state is a specific value.


Solution

  • This can be done by setting isInverted = true on the XCTestExpectation object like so:

    manager.state = .initialized
    let exp = expectation(description: "inverted expectation")
    exp.isInverted = true
    manager.login { state, error in
        exp.fulfill()
    }
    waitForExpectations(timeout: 1)