SwiftLocalhost
一个简单的框架,主要用于为 XCUITest 创建模拟本地域服务器。
安装
CocoaPods
SwiftLocalhost 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod 'SwiftLocalhost'
内部结构
Swiftlocalhost
使用 Criollo 库作为内存中的网络服务器。
使用说明 - 按以下 4 个步骤进行配置
SwiftLocalhost
使用 pod 安装到您的 XCUITest 目标中。
1. [Localhost] - 将 创建 Localhost 实例有 2 种方式。
使用特定的端口号
LocalhostServer(portNumber: 9001)
获得一个随机未使用的端口号分配到其上。如果您想并行执行测试,这很重要
LocalhostServer.initializeUsingRandomPortNumber()
一个 XCTestCase 类的示例
import SwiftLocalhost
class MovieListTest: XCTestCase {
var localhostServer: LocalhostServer!
override func setUp() {
continueAfterFailure = false
self.localhostServer = LocalhostServer.initializeUsingRandomPortNumber()
self.localhostServer.startListening()
}
override func tearDown() {
self.localhostServer.stopListening()
}
}
2. [API] - 使用 https://:xxxx(其中 xxxx 是端口号)修改应用程序 API 请求
如果您为 localhost 使用特定端口号,可以直接将域名更改为 https://:xxxx。
class NetworkOperations {
//private let baseUrl: String = "https://api.themoviedb.org/3/movie"
private let baseUrl: String = "https://:9001/3/movie"
}
如果您在测试中使用随机端口号,则需要在启动参数中传递端口号信息。
//In Test Runner, pass the port information using launchArguments
let app = XCUIApplication()
app.launchArguments = ["port:\(self.localhostServer.portNumber)"]
app.launch()
//In Application - Read the ProcessInfo Arguments
ProcessInfo.processInfo.arguments
如果您需要重定向第三方库(例如 Firebase、Google Analytics)到 localhost 服务器,可以使用由 Kenneth Poon 创建的 NetworkInterceptor pod。
3. [Info.plist] - 修改应用 Info.plist
由于我们将使用 http 协议与 localhost 服务器通信,需要在您的 Info.plist 文件中为 localhost 添加一个异常域名。
如果需要,您还可以禁用 SSL Pinning。
4. [Mock Responses] - 设置 localhost 服务器并使用模拟响应。
根据测试用例需要设置特定的模拟响应。将响应文件的 Data
实例设置为测试用例将要覆盖的特定路径的响应。
//let portNumber: UInt = 9001
//Binary of Mock Response Json File
//let jsonFileData: Data!
self.localhostServer.get("/3/movie/popular", routeBlock: { request in
let requestURL: URL = URL(string: "https://:\(portNumber)/3/movie/popular")!
let httpUrlResponse = HTTPURLResponse(url: requestURL, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type":"application/json"])!
return LocalhostServerResponse(httpUrlResponse: httpUrlResponse, data: jsonFileData)
})
可以为相同的路由路径排队模拟响应。模拟响应将按 FIFO 顺序返回。已使用过的响应将从队列中移除,除非队列中只剩下一个响应。
var dataResponse1, dataResponse2, dataResponse3: Data!
self.localhostServer.route(method: .GET,
path: "/3/movie/popular",
responseData: dataResponse1)
self.localhostServer.route(method: .GET,
path: "/3/movie/popular",
responseData: dataResponse2)
self.localhostServer.route(method: .GET,
path: "/3/movie/popular",
responseData: dataResponse2)