Reputation: 7762
Is this possible to create new temporary core data database when I run tests?
Because I have a problem, when I run my test I create wishlist:
import XCTest
@testable import TestProj
class ChangeWishListTests: XCTestCase {
func testSaveWishList() {
self.wishList = self.changeWishListVC?.saveWishList(title: "Test wish list",
desc: "My description",
wishlistType: WishListType.Shared,
hidden: false)
XCTAssertNotNil(wishList, "Wishlist not created.")
}
}
Than it appears in simulator. Or if it is impossible, how can I manage my fake objects.
Upvotes: 2
Views: 737
Reputation: 2031
Yes, you can but in order to do that you have to be able to change (tell the VC) managed object context that is used to perform Core Data operations. By doing you can then user test managed object in your test and the true one in production application code.
By test managed object context I mean the one that stores data only in memory without saving anything to the disc - the results of operations performed on that kind of context aren't persisted between different launches of the tests.
Creating managed object context that stores data only in memory is pretty simple:
let managedObjectModel = NSManagedObjectModel.init(contentsOfURL: modelURL)
var managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: managedObjectModel)
var error: NSError?
let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true];
let persistentStore = try! managedObjectContext.persistentStoreCoordinator?.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: options)
The simplest way to give yourself possibility to use test managed object context is to use dependency injection. Create initializer of your VC that takes managed object context as an argument - inject test managed object context in test code and normal managed object context in production code.
Upvotes: 4