Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift testing with Protocols
import Foundation
import UIKit
protocol DownloadAccountProtocol {
func downloadAccount(with name: String, completion: (Person) -> ())
}
class ServerDownloader: DownloadAccountProtocol {
func downloadAccount(with name: String, completion: (Person) -> ()) {
let personDictionary: [String: String] = [:] // Dictionary JSON downloaded from server
if let firstName = personDictionary["first_name"], let lastName = personDictionary["last_name"] {
let personModel = Person(firstName: firstName, lastName: lastName)
completion(personModel)
} else {
completion(Person(firstName: "John", lastName: "Adams"))
}
}
}
class DownloadAccountClass {
var downloadedAccount: Person?
init(downloadProtocol: DownloadAccountProtocol) {
downloadProtocol.downloadAccount(with: "Adam", completion: {value in
self.downloadedAccount = value
})
}
}
import Foundation
import Quick
import Nimble
@testable import SampleSwiftCode
class DownloadAccountSpec: QuickSpec {
override func spec() {
describe("Sample testing") {
it("This test should correctly mock the desired function call", closure: {
let downloader = DownloadAccountClass(downloadProtocol: DummyAccountDownloader())
expect(downloader.downloadedAccount?.firstName).to(equal("Gavin"))
expect(downloader.downloadedAccount?.lastName).to(equal("Belson"))
})
}
}
class DummyAccountDownloader: DownloadAccountProtocol {
func downloadAccount(with name: String, completion: (Person) -> ()) {
// This data is being read from the local json file instead of network call
// Local JSON file
// { "first_name": "Gavin", "last_name": "Belson" }
let dummyJsonPersonalData: [String: String] = [:]
let personModel = Person(firstName: dummyJsonPersonalData["first_name"], lastName: dummyJsonPersonalData["last_name"])
completion(personModel)
}
}
}
let downloader = DownloadAccountClass(downloadProtocol: ServerDownloader())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment