虽然Sweeper的评论很有帮助,应该是答案(因为没有他的回答,我无法得出自己的答案),但我仍然会继续分享我对Defaults类所做的事情,让它处理非JSON编码对象(例如String、Int、Array等等)。
这是:
默认值。敏捷的
import Foundation
enum MVDefaultsKey: String {
case requestToken = "defaultsRequestToken"
case someOtherKey = "defaultsKeyForTests"
}
/// The class that has multiple class functions for handling defaults.
/// Also has the helper class functions for handling auth tokens.
class MVDefaults {
// MARK: - Functions
/// Stores object.
class func store<T: Encodable>(_ object: T, key: MVDefaultsKey) {
let encoder = JSONEncoder()
let encoded = try? encoder.encode(object)
if encoded == nil {
UserDefaults.standard.set(object, forKey: key.rawValue)
return
}
UserDefaults.standard.set(encoded, forKey: key.rawValue)
}
/// Removes the stored object
class func removeDefaultsWithKey(_ key: MVDefaultsKey) {
UserDefaults.standard.removeObject(forKey: key.rawValue)
}
/// Returns stored object (optional) if any.
class func getObjectWithKey<T: Decodable>(_ key: MVDefaultsKey, type: T.Type) -> T? {
if let savedData = UserDefaults.standard.data(forKey: key.rawValue) {
let object = try? JSONDecoder().decode(type, from: savedData)
return object
}
return UserDefaults.standard.object(forKey: key.rawValue) as? T
}
}
下面是我为测试默认方法而编写的测试(规范)。都过去了!
@testable import Movieee
import Foundation
import Quick
import Nimble
class MVDefaultsSpec: QuickSpec {
override func spec() {
describe("Tests for MVDefaults") {
context("Tests the whole MVDefaults.") {
it("tests the store and retrieve function for any Codable object") {
let data = stubbedResponse("MovieResult")
expect(data).notTo(beNil())
let newMovieResult = try? JSONDecoder().decode(MovieResult.self, from: data!)
MVDefaults.store(newMovieResult, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: MovieResult.self)
// Assert
expect(retrievedObject).notTo(beNil())
// Assert
expect(retrievedObject?.movies?.first?.id).to(equal(newMovieResult?.movies?.first?.id))
}
it("tests the store and retrieve function for String") {
let string = "Ich bin ein Berliner"
MVDefaults.store(string, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: String.self)
// Assert
expect(retrievedObject).notTo(beNil())
// Assert
expect(retrievedObject).to(equal(string))
}
it("tests the removal function") {
MVDefaults.removeDefaultsWithKey(.someOtherKey)
let anyRetrievedObject = UserDefaults.standard.object(forKey: MVDefaultsKey.someOtherKey.rawValue)
let stringRetrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: String.self)
// Assert
expect(anyRetrievedObject).to(beNil())
// Assert
expect(stringRetrievedObject).to(beNil())
}
it("tests the store and retrieve function for Bool") {
let someBool: Bool = true
MVDefaults.store(someBool, key: .someOtherKey)
let retrievedObject = MVDefaults.getObjectWithKey(.someOtherKey, type: Bool.self)
// Assert
expect(retrievedObject).to(equal(someBool))
// Assert
expect(retrievedObject).notTo(beNil())
}
}
}
}
}