Space Vatican

Ramblings of a curious coder

Unit Testing Core Data Iphone Apps

This is probably obvious, but in the interest of saving someone else the few minutes I spent scratching my head on this one…

Your app probably has some code that looks like

1
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain]

If you pass nil then the main bundle is searched. When your an iphone app, that is the app itself - no surprises there. But when you are a unit test bundle, you are no longer the main bundle (the test rig application is). You need to tell CoreData to look inside your unit test bundle, with something along the lines of

1
2
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:
[NSArray arrayWithObject:[NSBundle bundleWithIdentifier:@"com.yourcompany.unittests"]]] retain];

For this to work you also need your data model to be present in your unit test bundle. For some reason, unlike your .m files the inspector doesn’t show you a list of targets the model should be included in - you need to drag the data model file into the compile source build phase of your unit test target.