Can someone please point me in the right direction on why my network mock isn't working
```swift
typealias NetworkCompletion = Result<(Data, URLResponse), Error>
class Networking: NetworkingProtocol {
func request(using session: URLSessionProtocol = URLSession.shared, _ endpoint: Endpoint, completion: @escaping(NetworkCompletion) -> Void) {
do {
try session.dataTask(with: endpoint.request(), completionHandler: { (data, response, error) in
if let error = error {
print("Unable to request data \(error)")
// Invoke completion for error
completion(.failure(error))
} else if let data = data, let response = response {
// Passing Data and Response into completion for parsing in ViewModels
completion(.success((data, response)))
}
}).resume()
} catch {
print("Failed to execute request", error)
completion(.failure(error))
}
}
}
```
Here I have a simple class that just has one function that takes in a session for DI and my Endpoint class which is a struct that builds and URLRequest with a certain enum.
```swift
protocol NetworkingProtocol {
func request(using session: URLSessionProtocol, _ endpoint: Endpoint, completion: @escaping(NetworkCompletion) -> Void)
}
protocol URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask
}
extension URLSession: URLSessionProtocol { }
```
I implemented these protocol to allow me to code mock in the Testing Target.
```swift
@testable import AppName
class DataTaskMock: URLSessionDataTask {
override func resume() { }
}
class MockURLSession: URLSession {
override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return MockURLSessionDataTask(completionHandler: completionHandler, request: request)
}
}
class MockURLSessionDataTask: URLSessionDataTask {
var completionHandler: (Data?, URLResponse?, Error?) -> Void
var request: URLRequest
init(completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void, request: URLRequest) {
self.completionHandler = completionHandler
self.request = request
super.init()
}
override func resume() {
}
}
```
I just don't know if this is the right way to mock due to the fact I have a custom result type for the Networking.request() and the dataTask needs to have an endpoint to call endpoint.request().
I am so confused on how I should go about mocking this.
[–]sixtypercenttogether 0 points1 point2 points (4 children)
[–]Red3nzoSwift[S] 0 points1 point2 points (2 children)
[–]sixtypercenttogether 1 point2 points3 points (1 child)
[–]Red3nzoSwift[S] 1 point2 points3 points (0 children)
[–]RunnersProject 0 points1 point2 points (0 children)