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

Network Testing in Swift with DVR

Sam Soffes
October 08, 2015

Network Testing in Swift with DVR

Walkthrough of how to use DVR and the design behind it. Given at Realm on 2015-10-08.

Sam Soffes

October 08, 2015
Tweet

More Decks by Sam Soffes

Other Decks in Programming

Transcript

  1. // Example XCTest func testTimeline() { let expectation = expectationWithDescription("Networking")

    // Your network client let client = APIClient() client.getTimeline { success in XCTAssertTrue(success) expectation.fulfill() } waitForExpectationsWithTimeout(1, handler: nil) }
  2. // DVR Session let dvr = Session(cassetteName: "timeline") // Pass

    into initializer let client = APIClient(session: dir)
  3. func getTimeline(completion: Bool -> Void) { let request = NSURLRequest(URL:

    timelineURL) session.dataTaskWithRequest(request) { _, _, _ completion(true) }.resume() }
  4. class Session: NSURLSession { let cassetteName: String let backingSession: NSURLSession

    init(cassetteName: StringbackingSession: NSURLSession = NSURLSession.sharedSession()) { self.cassetteName = cassetteName self.backingSession = backingSession super.init() } override func dataTaskWithRequest(request: NSURLRequest) -> NSURLSessionDataTask { return SessionDataTask(session: self, request: request) } }
  5. { "name" : "example", "interactions" : [ { "recorded_at" :

    1434688721.440751, "request" : { "method" : "GET", "url" : "http:\/\/example.com" } "response" : { "body" : "hello", "status" : 200, "url" : "http:\/\/example.com\/", "headers" : { "Cache-Control" : "max-age=604800", "Content-Type" : "text\/plain", "Last-Modified" : "Fri, 09 Aug 2013 23:54:35 GMT", "Content-Length" : "5" } } } ] }
  6. Mocks are inherently fragile. You have to couple your tes7ng

    code with the implementa7on details of your test. — Dave Abrahams, Protocol-Oriented Programming in Swi3
  7. class DisabledSession: NSURLSession { override func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?,

    NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask? { XCTFail("Networking disabled") return nil } }