Objective C - Unit testing dispatch_async block?

前端 未结 3 1935
北荒
北荒 2020-12-29 08:28

I read other posts that come up with solutions to this question. However, their solutions require hacky code to be added to my application in order to be able to test it. To

3条回答
  •  [愿得一人]
    2020-12-29 08:39

    Make a dispatch_async wrapper with a similar method signature that in turn calls the real dispatch_async. Dependency inject the wrapper into your production class and use that.

    Then make a mock wrapper, which records enqueued blocks and has an extra method for synchronously running all enqueued blocks. Maybe perform a recursive "blockception" if the blocks being executed in turn enqueued more blocks.

    In your unit tests, inject the mock wrapper into the system under test. You can then make everything happen synchronously even though the SUT thinks it is doing async work.

    dispatch_group sounds like a good solution as well, but would require your production class to "know" to ping the dispatch group at the end of the blocks it enqueues.

提交回复
热议问题