您如何在测试运行之间清理内存中的核心数据实例?

How do you clean up an in-memory core data instance between test runs?

我有一些代码可用于生成内存中的 CoreData 实例

class CoreDataContainer: NSPersistentContainer {
    init(name: String, mom: NSManagedObjectModel, inMemory: Bool = false) {
        super.init(name: name, managedObjectModel: mom)
        configureDefaults(inMemory)
    }
    private func configureDefaults(_ inMemory: Bool = false) {
        if let storeDescription = persistentStoreDescriptions.first {
            storeDescription.shouldAddStoreAsynchronously = true
            if inMemory {
                storeDescription.url = URL(fileURLWithPath: "/dev/null")
                storeDescription.shouldAddStoreAsynchronously = false
            }
        }
    }
}

并且我在每次 setUp() 调用之前像这样检索容器:

static func persistentContainer(mom: NSManagedObjectModel) -> CoreDataContainer {
    return CoreDataContainer(name: "Model", mom: mom, inMemory: true)
}

不过好像没有清空。我需要做些什么来同步清除每个 运行 之间的数据吗?

在测试中将您的 CoreDataContainer 声明为 属性 class

var coreDataContainer: CoreDataContainer!

然后在setUpWithError中初始化它,以便为每个测试创建一个新实例

func setUpWithError() throws {
    coreDataContainer = …
 }

您还应该重写 CoreDataContainer,以便您有一个只接受 inMemory 参数而没有其他任何东西的 init。如果您在 Xcode.

中创建一个新的 Core Data 项目,请查看包含的 PersistenceController