gpt4 book ai didi

ios - 使用简单的初始化在测试中创建 CoreData 对象

转载 作者:行者123 更新时间:2023-11-28 05:44:13 25 4
gpt4 key购买 nike

我有一组 NSManagedObject 子类,它们由 ClassToBeTested 使用。

ClassToBeTested 仅对 NSManagedObject 子类的几个属性进行操作,不需要关系或整个 CoreData 堆栈。

我能否以某种方式通过以常规方式创建它们来在测试中使用相同的对象:

        let template = CoreDataClass()
template.name = randomString(length: 40) // This fails!
templates.append(template)

目前它因错误而失败:

failed: caught "NSInvalidArgumentException", "-[CoreDataClass setTemplate_name:]: unrecognized selector sent to instance 0x600000af4c40"

最佳答案

虽然我在尝试这样做时遇到了不同的错误(没有调用指定的初始化程序),但在任何一种情况下,您的问题的答案都是:不,您不能那样做。

但是现在有了 NSPersistentContainer,很容易使用内存中的单例核心数据堆栈进行此类测试。将您的数据模型包含在您的测试包中,然后将其放入您的测试的全局范围内:

var sharedTestContext: NSManagedObjectContext = {
// Swift is smart enough to execute this only once.
let container = NSPersistentContainer(name: "<YourDataModelName>")
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { (description, error) in
if let error = error {
fatalError("Failed to load store for test: \(error)")
}
}
return container.newBackgroundContext()
}()

并为这样的测试定义一个特殊的托管对象初始值设定项:

/**
Initializes a managed object for testing

- important: This assumes your managed object subclass name is the same
as its entity name.
*/
public extension NSManagedObject {
convenience init(testContext: NSManagedObjectContext?) {
let context = testContext ?? sharedTestContext
/* The following contraption is necessary to avoid warning:
"Multiple NSEntityDescriptions claim the NSManagedObject subclass"
For explanation see:
https://stackoverflow.com/questions/51851485/multiple-nsentitydescriptions-claim-nsmanagedobject-subclass */
let name = String(describing: type(of: self))
let entity = NSEntityDescription.entity(forEntityName: name, in: context)!
self.init(entity: entity, insertInto: context)
}
}

现在您可以这样创建您的测试对象:

let template = CoreDataClass(testContext: nil)

关于ios - 使用简单的初始化在测试中创建 CoreData 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55516563/

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