Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Last active December 16, 2016 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayesh15111988/477d6747df5a9e07654344b9ca0ab915 to your computer and use it in GitHub Desktop.
Save jayesh15111988/477d6747df5a9e07654344b9ca0ab915 to your computer and use it in GitHub Desktop.
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