在测试运行时如何在Xcode UI测试中模拟网络请求? [英] How do I mock network requests in Xcode UI tests while the tests are running?

查看:225
本文介绍了在测试运行时如何在Xcode UI测试中模拟网络请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们为使用 KIF 编写的应用程序提供了一套UI测试我希望转换为使用新的Xcode UI测试框架。

We've got a suite of UI tests for our app written using KIF which I'd like to convert to use the new Xcode UI test framework.

该应用程序是Rest AI的客户端,我们目前正在使用NSURLProtocol进行模拟预定义的JSON文件响应GET,POST,PUT等...所有测试都是使用这些文件中的数据定义的,所以我想继续使用它们。服务器上的相同端点在测试中的不同点返回不同的数据,因此我无法预先模拟它们,我需要能够在测试运行时调用方法来模拟服务器的下一个响应。

The app is a client of a Rest AI whose responses we're currently mocking by using NSURLProtocol to serve predefined JSON files in response to the GETs, POSTs, PUTs, etc... All the tests are defined using the data in these files, so I want to continue using them. The same endpoints on the server return different data at different points in the tests, so I can't mock them up-front, I need to be able to call a method while the test is running to mock the server's next response.

不幸的是,在Xcode UI测试中使用NSURLProtocol不会影响测试的应用程序,我只看到通过启动参数或环境向应用程序发送数据的方法,例如如此答案。我需要在测试期间的不同阶段以不同方式模拟它们。如何以在测试期间发生变化的方式模拟UI测试中的网络请求?或者我如何与正在测试的应用程序通信,以便我可以让它来模拟请求本身?

Unfortunately, using NSURLProtocol inside an Xcode UI test doesn't affect the tested app, and I've only seen ways of sending data to the app via launch arguments or environment, such as in this answer. I need to mock them differently at different stages during my tests. How can I mock network requests from inside the UI test in a way that changes during the test? Or how can I communicate with the app being tested so I can get it to mock the requests itself?

推荐答案

我们已经开发了纯Swift中的嵌入式HTTP服务器,您可以在测试用例中使用简单的模拟响应处理程序运行HTTP服务器,然后通过环境变量将URL传递给目标应用程序,如 API_BASE_URL 。我写了一篇关于如何做的文章

We've developed an embedded HTTP server in pure Swift, you can run the HTTP server with simple mock response handler in your test case, then pass the URL to the target app via environment variable like API_BASE_URL. I wrote an article about how to do it

用于iOS UI测试的嵌入式Web服务器

基本上有两个库,一个是 Embassy ,它是简单的异步HTTP服务器。另一个是大使,一个用于模拟API端点的简单Web框架。

Basically there are two libraries, one is Embassy, it's the simple async HTTP server. Another one is Ambassador, a simple web framework for mocking API endpoints.

这篇关于在测试运行时如何在Xcode UI测试中模拟网络请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆