简体   繁体   English

如何使用XCTest对脱机方案进行单元测试

[英]How to unit test offline scenarios using XCTest

I'm trying to perform a set of unit tests, which require different network connection statuses. 我正在尝试执行一组单元测试,这需要不同的网络连接状态。 How can I simulate an offline iOS device when using XCTest (in Swift)? 使用XCTest(在Swift中)时,如何模拟离线iOS设备?

Thanks 谢谢

There are more than one approaches to this problem. 解决此问题的方法不止一种。

Mocking/Stubbing is one, you can use a mocking framework like OCMock or OCMockito and force the method return what you need for each test. 模拟/存根是一种,您可以使用OCMock或OCMockito之类的模拟框架,并强制该方法返回每次测试所需的内容。

The alternative "classic" approach (which I prefer) is implementing a stub/dummy class that shares the same API with the networking class and again have it return what you need for each test. 另一种“经典”方法(我更喜欢这种方法)是实现一个存根/虚拟类,该类与网络类共享相同的API,并再次使它返回每次测试所需的内容。

The difference is mostly of philosophical nature 差异主要是哲学性质

The bottom line is that you need a way to force the API to return what you want to test against. 最重要的是,您需要一种方法来强制API返回要测试的对象。

In order to get real world situations, like loss packets, latency, you can install Network Link Conditioner (get it from Apple download center ), but will affect your pc and simulator. 为了获得现实情况,例如丢失数据包,延迟,您可以安装Network Link Conditioner(可从Apple下载中心获取 ),但会影响您的PC和模拟器。 Also, you will needed to use asynchronous test ( check XCTestExpectation at this tutorial ) in order to wait for the responses or timeouts. 另外,您将需要使用异步测试( 请在本教程中检查XCTestExpectation )来等待响应或超时。

To do quick simple tests, you can run the unit tests on the iphone and simple set iphone to airplane mode. 要进行快速的简单测试,您可以在iPhone上运行单元测试,并将iPhone设置为飞行模式。

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

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