使馆和肉质公司在Xcode中进行UI测试

大家好!

我们课程列表中的另一个新奇之处: “ iOS开发人员” ,这意味着在准备课程时发现有趣的片段的时机已经到来。 在本文中,作者分析了如何记录和回放用于UI测试的API请求。



走吧

我最近将EmbassySucculent集成到我的UI测试中。 如果您需要为使用这些API的应用程序运行UI测试,则本指南可能提供模拟/存根的替代方法。

问题:

  • 该应用程序使用API​​数据填充UI。
  • 使用存根可能需要写入和维护大量文件;
  • 使用模拟时,应用程序逻辑可能与实际的网络调用有所不同;
  • 使用此连接API-完全排除,变量过多且崩溃


使馆+肉质解决方案

解决方案是创建应用程序定向到的本地服务器(使用Embassy),并记录/应答网络呼叫(使用Succulent)。

第一次运行测试时,将进行标准网络调用并将其写入跟踪文件。

下次,这些相同的网络呼叫将被自动应答。 不错,不是吗? 无需编写模拟,您可以模拟滞后和错误,所有这些都在XCtest内部的构建机器中运行!

如何使用?

1.下载并在Succulent下安装。 在撰写本文时,cocoapods.com上没有pod,因此您需要下载源并将其添加到子文件中,如下所示:

target “UI Tests” do inherit! :search_paths pod 'Succulent', :path => 'Succulent/' end 

大使馆需要肉质植物,它将被自动安装。

2.创建一个新的测试UI文件,并从Succulent GitHub复制说明。 结果,您应该获得以下文件:

 import Succulent @testable import TestAppUITests class SucculentTestUITest: XCTestCase { private var succulent: Succulent! var session: URLSession! var baseURL: URL! /// The name of the trace file for the current test private var traceName: String { return self.description.trimmingCharacters(in: CharacterSet(charactersIn: "-[] ")).replacingOccurrences(of: " ", with: "_") } /// The URL to the trace file for the current test when running tests private var traceUrl: URL? { let bundle = Bundle(for: type(of: self)) return bundle.url(forResource: self.traceName, withExtension: "trace", subdirectory: "Traces") } /// The URL to the trace file for the current test when recording private var recordUrl: URL { let bundle = Bundle(for: type(of: self)) let recordPath = bundle.infoDictionary!["TraceRecordPath"] as! String return URL(fileURLWithPath: "\(recordPath)/\(self.traceName).trace") } override func setUp() { super.setUp() continueAfterFailure = false if let traceUrl = self.traceUrl { // Replay using an existing trace file succulent = Succulent(traceUrl: traceUrl) } else { // Record to a new trace file succulent = Succulent(recordUrl: self.recordUrl, baseUrl: URL(string: "https//base-url-to-record.com/")!) } succulent.start() let app = XCUIApplication() app.launchEnvironment["succulentBaseURL"] = "http://localhost:\(succulent.actualPort)/" app.launch() } override func tearDown() { super.tearDown() } } 

启动多肉植物时,您可以指定基本URL,由于该基本URL,将记录包括基本URL在内的所有请求,而所有其他请求将被忽略。

3.将以下行添加到测试UI的Info.plist目标:

 <key>TraceRecordPath</key> <string>$(PROJECT_DIR)/Succulent/Traces</string> 

4.将应用程序定向到本地服务器。

要在您的主应用程序中执行此操作,您需要检查环境变量“ succulentBaseURL”是否存在以及是否已配置。

它显示了本地Web服务器的URL,并在setUp函数中进行了配置,该函数已在上面的步骤2中复制。

 #if DEBUG if let localServerUrl = ProcessInfo.processInfo.environment[“succulentBaseURL”] { return URL(string: localServerUrl)! } #endif 

仅此而已!

现在,当您执行一个简单测试并运行它时,Succulent将编写一个API请求并在您的UI测试目标目录的Traces文件夹中创建一个.trace文件。 下次运行相同的测试时,它将检查文件是否存在并运行它。

您可以直接从Xcode打开.trace文件,监视所有网络请求并根据需要进行修改。

希望这篇文章对您有用,这是披萨:



结束

像往常一样,我们在这里等待评论,问题等,或者您可以在开放日里向那里的老师提问。

Source: https://habr.com/ru/post/zh-CN412955/


All Articles