ios - 在单元测试中模拟 UserDefaults 对象返回 _ArrayBuffer
<p><p>我试图在我的单元测试中删除对操作系统对象(如 URLSessions 和 UserDefaults)的依赖关系。我一直试图将预缓存的数据模拟到我为测试目的而制作的模拟 UserDefaults 对象中。</p>
<p>我创建了一个具有编码和解码功能的测试类,并将模拟数据存储在一个成员变量中,该成员变量是一个 字典。在我的应用中,启动时它会检查缓存中的数据,如果找到,则会跳过网络调用。</p>
<p>我所能得到的只是 nil 或这个持续错误:</p>
<blockquote>
<p>fatal error: NSArray element failed to match the Swift Array Element
type</p>
</blockquote>
<p>查看调试器,解码器应该返回一个自定义类型“问题”的数组。相反,我得到一个 _ArrayBuffer 对象。</p>
<p>奇怪的是,如果我的应用程序将数据加载到我的模拟 userdefaults 对象中,它可以正常工作,但是当我将对象硬编码到其中时,我会收到此错误。</p>
<p>这是我模拟 UserDefaults 对象的代码:</p>
<pre><code>class MockUserSettings: DataArchive {
private var archive: = [:]
func decode<T>(key: String, returnClass: T.Type, callback: ((?) -> Void)) {
print("attempting payload from mockusersettings with key: \(key)")
if let data = archive {
callback(data as! )
} else {
print("Found nothing for: \(key)")
callback(nil)
}
}
public func encode<T>(key: String, payload: ) {
print("Adding payload to mockusersettings with key: \(key)")
archive = payload as AnyObject
}
}
</code></pre>
<p>以及我想要通过的测试:</p>
<pre><code>func testInitStorageWithCachedQuestions() {
let expect = XCTestExpectation(description: "After init with cached questions, initStorage() should return a cached question.")
let mockUserSettings = MockUserSettings()
var questionsArray: = []
for mockQuestion in mockResponse {
if let question = Question(fromDict: mockQuestion) {
questionsArray.append(question)
}
}
mockUserSettings.encode(key: "questions", payload: questionsArray)
mockUserSettings.encode(key: "currentIndex", payload: )
mockUserSettings.encode(key: "nextFetchDate", payload: )
let questionStore = QuestionStore(dateGenerator: Date.init, userSettings: mockUserSettings)
questionStore.initStore() { (question) in
let mockQuestionOne = Question(fromDict: self.mockResponse)
XCTAssertTrue(question == mockQuestionOne)
XCTAssert(self.numberOfNetworkCalls == 0)
expect.fulfill()
}
wait(for: , timeout: 1.0)
}
</code></pre>
<p>如果有人可以帮助我弄清楚我做错了什么,我将不胜感激。我是否正确存储了我的模拟对象?这个 ArrayBuffer 和 ArrayBridgeStorage 是什么东西??</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>我解决了我的问题。我的自定义类同时针对我的应用程序和测试。在单元测试中,我使用的是测试目标版本的类构造函数,而不是主应用程序的版本。</p>
<p>因此,要从中吸取的教训就是使用 <code>@testable import</code> 而不是让您的应用类以测试为目标。</p></p>
<p style="font-size: 20px;">关于ios - 在单元测试中模拟 UserDefaults 对象返回 _ArrayBuffer,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/45451374/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/45451374/
</a>
</p>
页:
[1]