Reputation: 3583
I'm trying to figure out why this crashes when both unit tests are run together.
When run separately, one test at a time, everything works. But when I try to run the tests for the whole class, the second one fails with "The model configuration used to open the store is incompatible with the one that was used to create the store."
Here is a link to a GitHub repo with a dead-simple project with the reproducible issue: https://github.com/MatthewWaller/CoreDataTestingIssueNonBeta
Also, the relevant portion of my code is below. To make it work, add your xcdatamodel file with a "Note" entity with a String "title" attribute and add it to the test target.
import XCTest
import CoreData
@testable import CoreDataTestingIssue
class CoreDataTestingIssueTests: XCTestCase {
private var context: NSManagedObjectContext?
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
self.context = NSManagedObjectContext.contextForTests()
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExampleOne() throws {
guard let context = context else {
return
}
let note = Note(context: context)
note.title = "Hello"
try! context.save()
}
func testExampleTwo() throws {
guard let context = context else {
return
}
let note = Note(context: context)
note.title = "There"
try! context.save()
}
}
extension NSManagedObjectContext {
class func contextForTests() -> NSManagedObjectContext {
// Get the model
let model = NSManagedObjectModel.mergedModel(from: Bundle.allBundles)!
// Create and configure the coordinator
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
try! coordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
// Setup the context
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
return context
}
}
Upvotes: 0
Views: 295
Reputation: 2273
I have reproduced the fail. The problem is that your code implements this Note
class twice.
In the File Inspector of .xcdatamodeld
file, you should only choose one Target Membership.
Choose the application target if you need this data model in the app and tests, or choose the tests' target if you will only use it in your test code.
Upvotes: 1