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
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/
来源:https://stackoverflow.com/questions/14868519/tdd-unit-testing-asynchronous-calls