Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Created November 28, 2023 07:45
Show Gist options
  • Save jayesh15111988/d2f3b6b9f511966edd05303a41fe8efa to your computer and use it in GitHub Desktop.
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
//
// 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