8

I am testing an asynchronous call using XCTestExpectation.

The following code works(the test succeeds) when the completionHandler is executed before the given 1 second timeout.

func test__async_call() {
        // prepare
        let sut = ClassToTest()
        let expectation: XCTestExpectation = self.expectationWithDescription(nil)

        // test
        sut.methodToTestWithCompletionHandler() { () -> () in
            expectation.fulfill()
        }

        // verify
        self.waitForExpectationsWithTimeout(1, handler: nil)
    }

However, if the completionHandler is not called, and therefore the expectation not fulfilled, instead of getting an test failure when calling waitForExpectationsWithTimeout I get an EXC_BAD_ACCESS, which is not very handy since this makes it impossible to see the whole test suite results.

How can I avoid this and get a normal test failure?

e1985
  • 6,239
  • 1
  • 24
  • 39

1 Answers1

4

Seems that what is causing the EXC_BAD_ACCESS is passing a nil description when creating the expectation.

Passing any string to this call makes it work and we get the expected test failure when the expectation is not fulfilled.

let expectation: XCTestExpectation = self.expectationWithDescription("...")
e1985
  • 6,239
  • 1
  • 24
  • 39
  • 2
    Got a similar error when I assumed that the handler block parameter `error` was never `nil`. The handler actually gets called whether it succeeds or fails. So, you have to check for an error in that case. – Albert Bori Mar 31 '15 at 04:55
  • 3
    Setting the description does not fix the problem for me. I set description on all my expectations but they still occasionally crash due to unfulfilled expectations. – Mike Taverne Oct 06 '15 at 23:14
  • Setting a description doesn't fix it for me either :\ – bogardon Sep 25 '19 at 23:04