@@ -28,23 +28,30 @@ import Foundation
2828import XCTest
2929
3030/// A class used to mock URLSession objects for testing purposes.
31- final class MockSession : URLSession {
31+ @objc public class MockSession : URLSession {
32+
33+ var wait : UInt32 = 0
3234
3335 var completionHandler : ( ( Data ? , URLResponse ? , Error ? ) -> Void ) ?
3436
3537 static var mockResponse : ( data: Data ? , urlResponse: URLResponse ? , error: Error ? )
3638
37- override class var shared : URLSession {
39+ override public class var shared : URLSession {
3840 return MockSession ( )
3941
4042 }
4143
42- override func dataTask( with request: URLRequest , completionHandler: @escaping ( Data ? , URLResponse ? , Error ? ) -> Void ) -> URLSessionDataTask {
44+ override public func dataTask( with request: URLRequest , completionHandler: @escaping ( Data ? , URLResponse ? , Error ? ) -> Void ) -> URLSessionDataTask {
4345 self . completionHandler = completionHandler
44- return MockTask ( response: MockSession . mockResponse, completionHandler: completionHandler)
46+ let task = MockTask ( response: MockSession . mockResponse, completionHandler: completionHandler)
47+ task. wait = wait
48+ return task
4549 }
4650
47- final class MockTask : URLSessionDataTask {
51+ @objc public class MockTask : URLSessionDataTask {
52+
53+ var wait : UInt32 = 0
54+ var canceled = false
4855
4956 typealias Response = ( data: Data ? , urlResponse: URLResponse ? , error: Error ? )
5057 var mockResponse : Response
@@ -55,8 +62,27 @@ final class MockSession: URLSession {
5562 self . completionHandler = completionHandler
5663 }
5764
58- override func resume( ) {
59- completionHandler!( mockResponse. data, mockResponse. urlResponse, mockResponse. error)
65+ override public func resume( ) {
66+ DispatchQueue . global ( qos: . background) . async {
67+ let wait = self . wait
68+ if wait > 0 {
69+ sleep ( wait)
70+ }
71+ DispatchQueue . main. async {
72+ if self . canceled {
73+ let error = NSError ( domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil )
74+ self . completionHandler!( nil , nil , error)
75+ } else {
76+ self . completionHandler!( self . mockResponse. data, self . mockResponse. urlResponse, self . mockResponse. error)
77+ }
78+
79+ }
80+ }
81+
82+ }
83+
84+ public override func cancel( ) {
85+ canceled = true
6086 }
6187
6288 }
@@ -66,6 +92,7 @@ final class MockSessionTests: XCTestCase {
6692
6793 func testMockSessionCreation( ) {
6894 let mockSession = MockSession . shared
95+ ( mockSession as! MockSession ) . wait = 0
6996 XCTAssertTrue ( mockSession is MockSession , " Failed " )
7097 }
7198
0 commit comments