Created
May 13, 2022 19:03
-
-
Save slo-addy/3189dee385426e4d96a07ec52536c126 to your computer and use it in GitHub Desktop.
An alternative example of a simple user name storage using UserDefaults that includes basic tests. This is in reference to https://www.youtube.com/watch?v=8IiRB28N5OI
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
import Foundation | |
protocol CredentialKeeper { | |
func store(userName: String) | |
func getUserName() -> String? | |
} | |
class UserCredentialStorage: CredentialKeeper { | |
var userDefaults: UserDefaults = .standard | |
var storageKey: String = "foo.user-name-store" | |
func store(userName: String) { | |
userDefaults.set(userName, forKey: storageKey) | |
} | |
func getUserName() -> String? { | |
userDefaults.string(forKey: storageKey) | |
} | |
} | |
class ViewModel { | |
private let userCredentialStorage: UserCredentialStorage | |
init(userCredentialStorage: UserCredentialStorage) { | |
self.userCredentialStorage = userCredentialStorage | |
} | |
var userName: String { | |
userCredentialStorage.getUserName() ?? "Unknown" | |
} | |
func save(userName: String) { | |
userCredentialStorage.store(userName: userName) | |
} | |
} | |
// MARK: Tests | |
import XCTest | |
class UserCredentialStorageTests: XCTestCase { | |
func testSample() { | |
let sut = UserCredentialStorage() | |
sut.userDefaults = UserDefaults() | |
sut.storageKey = "mock.user-cred-store-test" | |
let expectedUserName = "Luke Skywalker" | |
sut.store(userName: expectedUserName) | |
let storedUserName = sut.getUserName() | |
XCTAssertEqual(storedUserName, expectedUserName) | |
} | |
} | |
class ViewModelTests: XCTestCase { | |
func testSample() { | |
let storage = UserCredentialStorage() | |
storage.userDefaults = UserDefaults() | |
storage.storageKey = "mock.view-model-test" | |
let sut = ViewModel(userCredentialStorage: storage) | |
let expectedUserName = "Han Solo" | |
sut.save(userName: expectedUserName) | |
XCTAssertEqual(sut.userName, expectedUserName) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment