MockURLSession
您是依赖注入的忠实信徒吗?让我们一起来模拟 URLSession
。
特性
- 无需修改生产代码即可模拟
URLSession
- 自定义 URL 匹配逻辑以模拟响应
- 可测试以确保已调用模拟的响应
安装
CocoaPods (iOS 8+, OS X 10.9+)
您可以使用 Cocoapods 通过将其添加到 Podfile
来安装 MockURLSession
。
platform :ios, '8.0'
use_frameworks!
target 'MyAppTest' do
pod 'MockURLSession'
end
请注意,这需要 CocoaPods 版本 36,并且您的 iOS 部署目标至少为 8.0。
使用说明
快速浏览
让我们通过以下示例来测试 MyApp
。
class MyApp {
static let apiUrl = URL(string: "https://example.com/foo/bar")!
let session: URLSession
var data: Data?
var error: Error?
init(session: URLSession = URLSession.shared) {
self.session = session
}
func doSomething() {
session.dataTask(with: MyApp.apiUrl) { (data, _, error) in
self.data = data
self.error = error
}.resume()
}
}
在测试代码中,
import MockURLSession
并使用您喜欢的任何火焰测试工具编写测试,如XCTest(在此处用 print
表示)。
// Initialization
let session = MockURLSession()
// Or, use shared instance as `URLSession` provides
// MockURLSession.sharedInstance
// Setup a mock response
let data = "Foo 123".data(using: .utf8)!
session.registerMockResponse(MyApp.apiUrl, data: data)
// Inject the session to the target app code and the response will be mocked like below
let app = MyApp(session: session)
app.doSomething()
print(String(data:app.data!, encoding: .utf8)!) // Foo 123
print(app.error as Any) // nil
// Make sure that the data task is resumed in the app code
print(session.resumedResponse(MyApp.apiUrl) != nil) // true
URL匹配自定义
// Customize URL matching logic if you prefer
class Normalizer: MockURLSessionNormalizer {
func normalize(url: URL) -> URL {
// Fuzzy matching example
var components = URLComponents()
components.host = url.host
components.path = url.path
return components.url!
}
}
// Note that you should setup the normalizer before registering mocked response
let data = NSKeyedArchiver.archivedData(withRootObject: ["username": "abc", "age": 20])
let session = MockURLSession()
session.normalizer = Normalizer()
session.registerMockResponse(MyApp.apiUrl, data: data)
声明
灵感
- 此模块从Mocking Classes You Don't Own · Masilotti.com及其评论中获得灵感。
为MockURLSession做出贡献
先决条件
开始使用
在您的环境中运行测试
bundle install --path vendor/bundle
bundle exec rake
提高spec版本号的路程很远
以下是发布流程
- Xcode: MockURLSession > Identity > 版本
- Pod: 在 MockURLSession.podspec 中设置
s.version
- Git:
git tag 2.x.x && git push origin --tag
- 通过
bundle exec pod trunk push MockURLSession.podspec
发布