HTTPMock
是一个允许你在 HTTP 调用时下载模拟数据的库。 当你需要对需要网络调用的应用程序进行单元测试,而又没有服务器时,它非常有用。
为了在使用 URLSession
时能够接收到 stub 的数据,你需要在 URLSessionConfiguration.protocolClasses
中注册自定义的类。 有以下三种注册方法:
直接在 URLSessionConfiguration
中注册。
let configuration = URLSessionConfiguration.default
URLProtocolService.registerStub(in: configuration)
let session = URLSession(configuration: configuration)
...
如果你想在创建 URLSessionConfiguration
时自动注册,请使用以下方法。
URLProtocolService.registerStubInDefaultConfiguration()
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
...
URLSession
创建后无法更改其 configuration
。 因此,如果使用 URLSession.shared
,则需要调用以下方法。
URLProtocolService.registerStubInSharedSession()
如果想取消注册,请使用以下方法。
URLProtocolService.unregisterStub(from: configuration)
URLProtocolService.unregisterStubFromDefaultConfiguration()
URLProtocolService.unregisterStubFromEphemeralConfiguration()
URLProtocolService.unregisterStubFromSharedSession()
let bundle = Bundle(for: type(of: self))
let responseFileURL = bundle.url(forResource: "items", withExtension: "json")!
stub(when: .isHost("server.com"), then: .fileURL(responseFileURL))
// stub 시 다양한 설정 가능. ex) 2초 딜레이 후 1KB씩 전송
stub(when: .isHost("server.com") && .hasLastPathComponent("items.json"),
then: .fileURL(responseFileURL)
.settingResponseDelay(2.0)
.settingPreferredBytesPerSecond(1_000))
完成上述两个操作后(顺序无关),调用 URLSession.dataTask(with:)
或 URLSession.downloadTask(with:)
即可获取 stub 的数据。
.package(url: "https://github.com/nearfri/HTTPMock", from: "0.9.0")