Last active
March 2, 2021 15:29
-
-
Save fishkingsin/94153e40faf2c2780e6bc9fbf6c9f51c to your computer and use it in GitHub Desktop.
unitTestAPIService404
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
import Foundation | |
class APIService { | |
let defaultSession = URLSession(configuration: .default) | |
typealias APIServiceCompletionHandler = (Int?) -> Void | |
var urlString: String? | |
init(urlString: String) { | |
self.urlString = urlString | |
} | |
func fetch( completionHandler: @escaping APIServiceCompletionHandler) { | |
if let urlString = urlString, let url = URL(string: urlString ) { | |
let request = URLRequest(url: url) | |
let dataTask = self.defaultSession.dataTask(with: request, completionHandler: { (data, response, error) -> Void in | |
if let httpResponse = response as? HTTPURLResponse { | |
completionHandler(httpResponse.statusCode) | |
} | |
}) | |
dataTask.resume() | |
} | |
} | |
} | |
class Mock404Service: APIService { | |
override func fetch(completionHandler: @escaping APIService.APIServiceCompletionHandler) { | |
completionHandler(404) | |
} | |
} | |
class Interactor: NSObject { | |
var service: APIService = APIService(urlString: "") | |
var statusCode: Int? | |
var statusString: String? | |
func getSomthing(callback: (() -> Void)) { | |
service.fetch { (statusCode) in | |
self.statusCode = statusCode | |
if statusCode == 404 { | |
self.statusString = "Status Code is 404" | |
} | |
} | |
} | |
} | |
func test404() { | |
let interactor = Interactor() | |
interactor.service = Mock404Service(urlString: "") | |
interactor.getSomthing { | |
XCTAssertEqual(interactor.statusCode, 404) | |
XCTAssertEqual(interactor.statusString, "Status Code is 404") | |
} | |
} | |
test404() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment