此 Pod 用于在功能测试期间返回应用程序请求的 URL 的预存响应,以帮助测试。
要模拟单个请求,请使用 mockNext
- 该方法可以多次调用,并且响应将以相同的顺序返回
let body1 = "Test response 1".data(using: String.Encoding.utf8)!
let body2 = "Test response 2".data(using: String.Encoding.utf8)!
let url = URL(string: "https://www.example.com/1")!
let request = URLRequest(url: url)
// Mock calls to that request returning both responses in turn
_ = URLSession.mockNext(request: request, body: body1, delay: 1)
_ = URLSession.mockNext(request: request, body: body2, delay: 1)
要模拟对请求的每个调用,请使用 mockEvery
URLSession.mockEvery(request: request, body: body, delay: 1)
如果需要更简洁的代码,则参数 body
和 delay
可选,例如,要返回 200 状态码且没有数据,您可以这样做:
URLSession.mockEvery(request: request)
短暂的模拟优先于永久模拟。也就是说,如果您对同一请求添加了永久模拟和短暂模拟,则先返回并消耗短暂模拟
如果您想使响应依赖于调用 URL,则可以传递一个类似这样的函数:
let expression = "https://www.example.com/product/([0-9]{6})"
// Return a valid test product JSON response with the correct pid
URLSession.mockEvery(expression: expression) { (matches:[String]) in
let pid = matches.first!
let body = "{ 'productId':'\(pid)', 'description':'This is a test product' }".data(using: String.Encoding.utf8)!
return .success(statusCode: 200, headers: [:], body: body)
}
如果您想模拟错误(内部 iOS 错误,不是服务器错误;它们只是 statusCode 为 500 的响应),您可以返回一个 .Failure
let expression = "https://www.example.com/some_url.json"
// Return a valid test product JSON response with the correct pid
URLSession.mockEvery(expression: expression) { (matches:[String]) in
let error = NSError(domain: "TestNetworkingLayerError", code: 0, userInfo: [NSLocalisedDescriptionKey: "Could not open session blah blah something"])
return .failure(error)
}
要删除所有模拟(或仅删除其中一些),可以进行如下操作:
// Remove everything
NSURLSession.removeAllMocks()
// Remove all mocks matching a request
NSURLSession.removeAllMocks(of: request)
如果您想对联立请求失败,将 NSURLSession 的请求评估器设置为返回是否允许请求。例如,要确保对所有 Net-A-Porter 域的调用都是模拟的,您可以:
NSURLSession.requestEvaluator = { request in
guard let url = request.URL else { return .reject }
return url.host == "www.net-a-porter.com" ? .reject : .passThrough
}
如果对 www.net-a-porter.com 的请求没有被模拟,则会抛出异常。
此 Pod 为 AFNetworking (~>2.0) 考虑周全 - 将通过 AFNetworking 的 AFHTTPSessionManager
方法对 NSURLSession 进行模拟。请查看 AFNetworkingTests.swift
以获取示例。
要运行示例项目,先从仓库克隆,然后在 Example 目录中先运行 pod install
。该项目包含一个测试套件,应显示如何使用 pod 的示例。
NSURLSession-Mock 可通过 CocoaPods 获取。要安装它,只需在您的 Podfile 中添加以下行
pod "NSURLSession-Mock"
Sam Dean, [email protected]
NSURLSession-Mock 在 Apache 许可协议下提供。有关更多信息,请参阅 LICENSE 文件。