Network Testing in Swift with DVR

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →
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

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

21 slides
  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 } }

More Decks by Sam Soffes

Other Decks in Programming