unit test async function by using XCTestExpectation but it doesn't wait for the seconds I set

孤街浪徒 提交于 2019-12-06 05:27:35

As soon as you begin to waitForExpectations, your dispatch_async will get a chance to run. It will assert that your data have been checked, and then -- regardless of whether your data has been checked or not -- it marks the expectation as fulfilled. Once fulfilled, we no longer need to wait and we can finish.

That's probably not what you want to do, but it's what the code says.

OK, solved.

I should use dispatch_after insteand of dispatch_async, because I don't have a completion block in my function under test while the example in that tutorial has one. So, I need to change to this:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        XCTAssert(...);
        [expectation fulfill];
});

If you want to use dispatch_async please check @Avi's comment, use a while loop in the async block to wait.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!