简体   繁体   English

为什么在Objective-C / Swift中很难进行异步网络测试?

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

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. 给定的测试方法完成后,XCTest方法将认为测试已完成并移至下一个测试。 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. 如果我理解正确,他首先说XCTest方法将继续运行,即使异步代码正在完成。 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. 谢谢。

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 . 这是我启发自己测试自己的代码的一个很好的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM