I am trying to use CoreData in a SenTestCase. The problem is the NSManagedObjectModel which is not found. I have tried to initialize it with a URL by searching for the mom file in the application bundle but I could not find it. That is why I switched to:
NSManagedObjectModel *objectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
This does work properly but only in the main application. If I try to run it in the SenTestCase the returned objectModel does not have any entities:
(gdb) po objectModel
(<NSManagedObjectModel: 0xab72480>) isEditable 0, entities {
}, fetch request templates {
}
I have to admit that I do not know what kind of setup is needed to generate the mom file. I have added the .xcdatamodeld file to the list of compiled sources in the application's target and the test target.
The following code is working properly in the applications ViewController viewDidLoad method but is not working in a test case of a SenTestCase class:
- (void)testCoreData {
NSManagedObjectModel *objectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: objectModel];
[context setPersistentStoreCoordinator: coordinator];
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"TestDatabase"];
NSLog(@"Path: %@", url);
NSError *error;
NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:nil
error:&error];
if (newStore == nil) {
NSLog(@"Store Configuration Failure\n%@",
([error localizedDescription] != nil) ?
[error localizedDescription] : @"Unknown Error");
}
TaskSet *taskSet = [NSEntityDescription insertNewObjectForEntityForName:@"TaskSet"
inManagedObjectContext:context];
taskSet.taskSetId = @"1234";
NSLog(@"TaskSet: %@", taskSet);
NSError *saveError;
if ([context save:&saveError]) {
NSLog(@"Store Saved successfully");
} else {
NSLog(@"Store not saved! Error: %@", saveError);
}
}
Error:
Catchpoint 3 (exception thrown).Unknown.m:0: error: -[ControllerTest testCoreData] : +entityForName: could not locate an entity named 'TaskSet' in this model.
What is the difference between running in a SenTestCase and running in viewDidLoad ? What do I need to do to compile the core data model into a test case?
This question has been answered before: Unit Test can't find Core Data model file
The credit goes to Luther Baker for pointing out that SenTestCases are not using the main Bundle. If you want to write data to a file you have to create the bundle with an identifier as described in his answer.