Upgrade to Pro — share decks privately, control downloads, hide ads and more …

通信処理を差し替えてみた話

Tatsuya Tanaka
February 15, 2017

 通信処理を差し替えてみた話

URLProtocolとMethod Swizzlingの話
#potatotips 37

Tatsuya Tanaka

February 15, 2017
Tweet

More Decks by Tatsuya Tanaka

Other Decks in Technology

Transcript

  1. Mock༻ͷURLProtocol public class MockURLProtocol: URLProtocol { override open func startLoading()

    { let jsonString = "{\"mock\": \"data\"}" let json = jsonString.data(using: .utf8)! self.client?.urlProtocol(self, didLoad: json) self.client?.urlProtocolDidFinishLoading(self) } // ͦͷଞϝιου͸লུ }
  2. Method SwizzlingͰϞοΫ༻ͷURLProtocol ʹࠩ͠ସ͑ public extension URLSessionConfiguration { public class func

    setup() { let `default` = class_getClassMethod(URLSessionConfiguration.self, #selector(getter: URLSessionConfiguration.default)) let swizzled = class_getClassMethod(URLSessionConfiguration.self, #selector(getter: URLSessionConfiguration.mock)) method_exchangeImplementations(`default`, swizzled) } private dynamic class var mock: URLSessionConfiguration { let configuration = self.mock configuration.protocolClasses?.insert(MockURLProtocol.self, at: 0) URLProtocol.registerClass(MockURLProtocol.self) return configuration } }
  3. QuickͱAlamofireͰͷελϒԽ describe("Quick compatibility test") { it("returns mock data") { let

    url = "http://echo.jsontest.com/key/value/one/two" var json: [String: String]? Alamofire.request(url, method: .post).responseJSON { response in json = response.result.value as? [String: String] } expect(json?["test"]).toEventually(equal("data")) } }