Why is asynchronous network testing difficult in Objective-C/Swift?

303 views Asked by At

So I'm learning more about how to test asynchronous code when I come across the following:

As soon as a given test method completes, XCTest methods will consider a test to be finished and move onto the next test. That means that any asynchronous code from the previous test will continue to run while the next test is running. Networking code is usually asynchronous, since you don’t want to block the main thread while performing a network fetch. That, coupled with the fact that tests finish when the test method finishes, can make it hard to test networking code."

However, this is contradicting in my mind. If I'm understanding correctly, he says first that XCTest methods will continue to run even if asynchronous code is finishing. However, he then says that tests finish when the test method finishes. But these two statements contradict, as the test is not finished because asynchronous code is still running, yet it proceeds in the serial queue to the next process to execute. In other words, do the tests finish when the async code finishes, or do the tests continue while the async code is still running? On top of that, what makes network testing so difficult? Thank you.

1

There are 1 answers

5
John Difool On BEST ANSWER

Breaking down this statement tells us that each test method finishes when it returns. Because you are testing network code with an async callback, the callback may not happen BEFORE the method ends. Therefore testing async code can be considered potentially difficult ** if you don't pay attention **

To this I will add that I am using the simple dispatch group to wrap code and wait for the code to finish. Here is a great example that I have inspired myself from to test my own code.