Skip to content

Commit 24f79ca

Browse files
Mark Pospeselmpospese
authored andcommitted
[Issue-9] Fix flaky unit test
1 parent 947e305 commit 24f79ca

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Sources/YNetwork/NetworkManager/Mock/URLProtocolStubNetworkEngine.swift.swift

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ final public class URLProtocolStubNetworkEngine: NetworkEngine {
1313
private(set) var session: URLSession!
1414
internal let protocolClasses: [AnyClass]
1515

16+
/// Whether created background upload and download tasks should be autoresumed.
17+
/// Default = `true`.
18+
///
19+
/// For unit testing it is sometimes useful to set this to `false` and manually call `resume()`
20+
/// on the `URLSessionTask` returned from the submit methods.
21+
public var autoResumesBackgroundTasks: Bool = true
22+
1623
/// Initializes an URLProtocolStubNetworkEngine with protocolClasses
1724
/// - Parameter protocolClasses: URLProtocol class that need to be stub
1825
/// default class will be URLProtocolStub
@@ -75,7 +82,9 @@ final public class URLProtocolStubNetworkEngine: NetworkEngine {
7582
// make a URLSessionDownloadTask, resume it, then return it
7683
let downloadTask = session.downloadTask(with: request)
7784
downloadTask.taskDescription = "\(request: request)"
78-
downloadTask.resume()
85+
if autoResumesBackgroundTasks {
86+
downloadTask.resume()
87+
}
7988
return downloadTask
8089
}
8190

@@ -100,7 +109,9 @@ final public class URLProtocolStubNetworkEngine: NetworkEngine {
100109
// make a URLSessionUploadTask, resume it, then return it
101110
let uploadTask = session.uploadTask(with: request, from: data)
102111
uploadTask.taskDescription = "\(request: request)"
103-
uploadTask.resume()
112+
if autoResumesBackgroundTasks {
113+
uploadTask.resume()
114+
}
104115
return uploadTask
105116
}
106117
}

Tests/YNetworkTests/NetworkManager/NetworkManagerUploadTests.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,16 @@ final class NetworkManagerUploadTests: XCTestCase {
6464
let expectation = expectation(description: "Wait for upload failure.")
6565
sut.expectation = expectation
6666

67+
let engine = try XCTUnwrap(sut.configuration?.networkEngine as? URLProtocolStubNetworkEngine)
68+
engine.autoResumesBackgroundTasks = false
69+
6770
URLProtocolStub.appendStub(withData: data, statusCode: 200, type: .upload)
6871

6972
XCTAssertNil(sut.receivedError)
7073

71-
let task = try XCTUnwrap(sut.submitBackgroundUpload(request) { _ in })
74+
let task = try XCTUnwrap(sut.submitBackgroundUpload(request) { _ in } as? URLSessionTask)
7275
task.cancel() // this will make it fail
76+
task.resume() // resume it
7377

7478
wait(for: [expectation], timeout: timeout)
7579

0 commit comments

Comments
 (0)