其他分享
首页 > 其他分享> > 利用 URLProtocol 假冒一个服务器来测试网络

利用 URLProtocol 假冒一个服务器来测试网络

作者:互联网

利用 URLProtocol 假冒一个服务器来测试网络

制造一个假的服务器

class MockURLProtocol: URLProtocol {
    static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
    override func startLoading() {
        guard let handler = MockURLProtocol.requestHandler else {
            XCTFail("Received unexpected request with no handler set")
            return
        }
        do {
            let (response, data) = try handler(request)
            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            client?.urlProtocol(self, didLoad: data)
            client?.urlProtocolDidFinishLoading(self)
        } catch {
            client?.urlProtocol(self, didFailWithError: error)
        }
    }
}

用这个假的服务器来测试

class APILoaderTests: XCTestCase {
    var loader: APIRequestLoader<PointsOfInterestRequest>!
    override func setUp() {
        let request = PointsOfInterestRequest()
        let configuration = URLSessionConfiguration.ephemeral
        configuration.protocolClasses = [MockURLProtocol.self]
        let urlSession = URLSession(configuration: configuration)
        loader = APIRequestLoader(apiRequest: request, urlSession: urlSession)
    }
}

区分测试和正式

参考

posted on 2018-06-18 23:56  花老????  阅读(247)  评论(0)  编辑  收藏

标签:假冒,self,request,client,let,URLProtocol,服务器,configuration
来源: https://blog.51cto.com/u_15223551/2834030