I want to add unit tests for my Core Data app, but I am sure how to reset the context between tests.
This is my CoreDataStack
object:
public final class CoreDataStack {
var storeType: StoreType!
public init(storeType: StoreType) {
self.storeType = storeType
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Transaction")
container.loadPersistentStores(completionHandler: { (description, error) in
if let error = error {
fatalError("Unresolved error \(error), \(error.localizedDescription)")
} else {
description.type = self.storeType.type
}
})
return container
}()
public var context: NSManagedObjectContext {
return persistentContainer.viewContext
}
}
And this is how I am using it in my tests:
class PaymentTests: XCTestCase {
var context: NSManagedObjectContext!
override func setUp() {
super.setUp()
let coreDataStack = CoreDataStack(storeType: .inMemory)
context = coreDataStack.context
}
}
I tried to call context.reset()
inside tearDown
function but, the data is not reset, it's always persistent.
So how can I tear down the Core Data Stack ?
Overview. Core Data provides a set of classes that collaboratively support your app's model layer: An instance of NSManagedObjectModel describes your app's types, including their properties and relationships. An instance of NSManagedObjectContext tracks changes to instances of your app's types.
The Core Data stack consists of multiple objects that interface with our entities to save and load instances to a persistent store. The stack also includes the model file that describes our entities.
The persistent store should be located in the AppData > Library > Application Support directory.
Overview. Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.
The old data has nothing to do with your context but with your PersistentStore
. This is what you are using Core Data for, persist your data.
Delete the store to get rid of your data before initializing your stack in setup()
. You can find it like this:
let storeUrl = persistentContainer.persistentStoreCoordinator.persistentStores.first!.url!
and remove it like this:
let fileManager = FileManager.default
fileManager.removeItem(at: storeUrl)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With