我想在我的單元測試中刪除依賴到操作系統對象像URLSessions和UserDefaults。我被困在試圖將預緩存的數據模擬到我爲測試目的而製作的模擬UserDefaults對象中。模擬UserDefaults對象在單元測試返回_ArrayBuffer
我做了一個測試類,它具有編碼和解碼功能,並將模擬數據存儲在[String:AnyObject]字典的成員變量中。在我的應用程序中,啓動時會檢查緩存中的數據,如果發現任何數據,則會跳過網絡呼叫。
所有我已經能夠得到的是零的或者這一個持續的錯誤:
fatal error: NSArray element failed to match the Swift Array Element type
望着調試器,解碼器應該有回報的自定義類型「問題」的數組。相反,我得到一個_ArrayBuffer對象。
奇怪的是,如果我的應用程序將數據加載到我的模擬userdefaults對象中,它工作正常,但是當我將對象硬編碼到它中時,出現此錯誤。
這裏是我的代碼爲模擬對象UserDefaults:
class MockUserSettings: DataArchive {
private var archive: [String: AnyObject] = [:]
func decode<T>(key: String, returnClass: T.Type, callback: (([T]?) -> Void)) {
print("attempting payload from mockusersettings with key: \(key)")
if let data = archive[key] {
callback(data as! [T])
} else {
print("Found nothing for: \(key)")
callback(nil)
}
}
public func encode<T>(key: String, payload: [T]) {
print("Adding payload to mockusersettings with key: \(key)")
archive[key] = payload as AnyObject
}
}
我試圖測試通過:
func testInitStorageWithCachedQuestions() {
let expect = XCTestExpectation(description: "After init with cached questions, initStorage() should return a cached question.")
let mockUserSettings = MockUserSettings()
var questionsArray: [Question] = []
for mockQuestion in mockResponse {
if let question = Question(fromDict: mockQuestion) {
questionsArray.append(question)
}
}
mockUserSettings.encode(key: "questions", payload: questionsArray)
mockUserSettings.encode(key: "currentIndex", payload: [0])
mockUserSettings.encode(key: "nextFetchDate", payload: [Date.init().addingTimeInterval(+60)])
let questionStore = QuestionStore(dateGenerator: Date.init, userSettings: mockUserSettings)
questionStore.initStore() { (question) in
let mockQuestionOne = Question(fromDict: self.mockResponse[0])
XCTAssertTrue(question == mockQuestionOne)
XCTAssert(self.numberOfNetworkCalls == 0)
expect.fulfill()
}
wait(for: [expect], timeout: 1.0)
}
如果有人可以幫助我滿腦子都在我的」如果做錯了,將不勝感激。我是否正確地存儲了我的模擬對象?這是什麼ArrayBuffer和ArrayBridgeStorage的東西?