Created
November 28, 2023 07:45
-
-
Save jayesh15111988/d2f3b6b9f511966edd05303a41fe8efa to your computer and use it in GitHub Desktop.
A sample code to demonstrate how to use protocols to facilitate unit testing in iOS app
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
// | |
// TestableNetworkServiceExample.swift | |
// KayakCodingChallenge | |
// | |
// Created by Jayesh Kawli on 11/28/23. | |
// | |
import Foundation | |
import XCTest | |
struct Name: Decodable { | |
let firstName: String | |
let lastName: String | |
} | |
protocol NetworkServiceableProtocol: AnyObject { | |
func loadSampleData(completion: @escaping (Result<Name, Error>) -> Void) | |
} | |
final class NetworkServiceClass: NetworkServiceableProtocol { | |
func loadSampleData(completion: @escaping (Result<Name, Error>) -> Void) { | |
let url = URL(string: "www.google.com")! | |
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in | |
let decoder = JSONDecoder() | |
let responsePayload = try! decoder.decode(Name.self, from: data!) | |
completion(.success(responsePayload)) | |
} | |
task.resume() | |
} | |
} | |
//View Model | |
final class MyViewModel { | |
private let networkService: NetworkServiceable | |
init(networkService: NetworkServiceable) { | |
self.networkService = networkService | |
} | |
func loadData() { | |
networkService.loadData(with: "www.google.com") { result in | |
} | |
} | |
} | |
//Test framework | |
class MockNetworkService: NetworkServiceableProtocol { | |
func loadSampleData(completion: @escaping (Result<Name, Error>) -> Void) { | |
completion(.success(Name(firstName: "Tom", lastName: "Bob"))) | |
} | |
} | |
class NetworkServiceTest: XCTestCase { | |
let mockNetworkService = MockNetworkService() | |
override func setup() { | |
super.setUp() | |
let viewModel = MyViewModel(networkService: mockNetworkService) | |
viewModel.loadData() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment