gpt4 book ai didi

ios - 使用核心数据进行 Swift 4 单元测试

转载 作者:行者123 更新时间:2023-12-02 05:54:49 25 4
gpt4 key购买 nike

我有一个 iOS 项目,它在模拟器等上运行良好,但当我使用其测试包时,似乎无法很好地链接到核心数据资源。

我已经在测试类的设置函数中从内存中创建了NSManagedObjectContext。但是,当我尝试运行该程序时,测试功能失败,并且控制台有输出

"An NSManagedObject of class 'Projectname.Deck' must have a valid NSEntityDescription."

我有什么遗漏的吗?我希望能够在开发应用程序时对其数据结构进行单元测试。

谢谢!

编辑

测试类的相关部分:

class ProjectNameTests: XCTestCase {

var testDeck: Deck? = nil

func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!

let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("Adding in-memory persistent store failed")
}

let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

return managedObjectContext
}//setUpInMemoryManagedObjectContext

override func setUp() {
super.setUp()

self.context = setUpInMemoryManagedObjectContext()
testDeck = Deck(context: context)
testDeck!.name = "Test Deck"
}//setUp
}//ProjectNameTests

最佳答案

更新:经过大量研究后,我发现我的问题与从类本身提取 NSEntityDescription 相关,而不是从当前上下文中提取。

我将以下方法添加到我的 Deck 类中(并且将对其他 NSManagedObject 子类执行相同的操作):

public static func entityDescription(context: NSManagedObjectContext)->NSEntityDescription{
return NSEntityDescription.entity(forEntityName: String(describing: self), in: context)!
}//entityDescription

然后,我将测试用例中的初始化调用更改为以下内容:

let deckEntity: NSEntityDescription = Deck.entityDescription(context: context)
testDeck = Deck(entity: deckEntity, insertInto: context)

这样,该对象就可以使用从当前 NSManagedObjectContext 中提取的 NSEntityDescription 进行初始化,这让一切变得更加愉快。

支持Swift, Core Data, and unit testing引导我走上正确的道路。

关于ios - 使用核心数据进行 Swift 4 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49701397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com