TDD: Unit Testing Asynchronous Calls

…衆ロ難τιáo~ 提交于 2019-12-06 09:55:42

Sometimes there is a temptation to test things which you don't usually test using Unit Testing. This basically comes from misunderstanding and desire to test everything. And then you realize you don't know how to test it with unit-testing.

You would better ask yourself - what do I test here?

Do I test that the data is not available until request completes?

Then you can write non-async version of the test which will check that the data is available after request completes.

Do I test that the response saved correctly after request?

You can also test it using flags in your logic.

You can do all logic tests without running asynchronous tests.

So at the bottom I would even ask you why do you think you need to test async call?

The unit tests supposed to run quickly - so consider it as another reason to not test async calls. Imagine continuous integration system which runs these test - it will need extra time.

And reading your comments to another answer - I think it's not common to use async in testing at all. E.g. Kent Beck in TDD book. mentioned that Concurrent Unit Testing is possible but very rare case.

So - what & why you really want to test?

Use a run loop, polling until completion or a timeout is reached: https://codely.wordpress.com/2013/01/16/unit-testing-asynchronous-tasks-in-objective-c/

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