HomeiOS Developmentios - Swift Unit Testing Community Request

ios – Swift Unit Testing Community Request


I wish to write unit assessments for my DataService. I learn that you do not really wish to make community requests within the assessments, and as an alternative, it is best to make a MockDataService. Nevertheless, what ought to the physique of the fetchBusinesses technique appear to be within the MockDataService? I have to account for instances of invalidURL, fail to decode and many others…

protocol DataServiceProtocol {
    func fetchBusinesses(location: CLLocationCoordinate2D) async throws -> [Business]
}

ultimate class DataService: DataServiceProtocol {
    func fetchBusinesses(location: CLLocationCoordinate2D) async throws -> [Business] {
    
        let url = strive createURL(latitude: location.latitude, longitude: location.longitude)
        let request = setupURLRequest(url: url)
        
        let (information, response) = strive await URLSession.shared.information(for: request)
        
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            let statusCode = (response as! HTTPURLResponse).statusCode
            throw DataServiceError.invalidStatusCode(statusCode: statusCode)
        }
        
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        
        let decodedAPIResponse = strive decoder.decode(SearchResponse.self, from: information)
        return decodedAPIResponse.companies
    }
    
    personal func createURL(latitude: Double, longitude: Double) throws -> URL {
        let endpoint = "https://api.yelp.com/v3/companies/search?latitude=(latitude)&longitude=(longitude)&sort_by=distance&time period=boba"
        guard let url = URL(string: endpoint) else {
            throw DataServiceError.invalidURL
        }
        return url
    }
    
    personal func setupURLRequest(url: URL) -> URLRequest {
        let apiKey = "<API Key>"
        
        var request = URLRequest(url: url)
        request.setValue("Bearer (apiKey)", forHTTPHeaderField: "Authorization")
        return request
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments