TDD: Unit Testing Asynchronous Calls

夙愿已清 提交于 2019-12-22 14:05:57

问题


guys:

I'm working on an application, and building it with unit testing.

However, I'm now in a situation where I need to test asynchronous calls. For example,

- (void)testUserInfoBecomesValidWhenUserIsBuiltSuccessfully
{
    if ( ![userBuilder userInfoUpToDate] )
    {
        [userBuilder buildUser];
    }

    STAssertTrue([userBuilder userInfoUpToDate], @"User information is not valid before building the user");
}

What is the general practice for testing such things? userInfoUpToDate is expected to be updated asynchronously.

Thanks! William


回答1:


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?




回答2:


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/



来源:https://stackoverflow.com/questions/14868519/tdd-unit-testing-asynchronous-calls

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