Re: Using Core Data with OCUnit
Re: Using Core Data with OCUnit
- Subject: Re: Using Core Data with OCUnit
- From: Bill Garrison <email@hidden>
- Date: Mon, 10 Mar 2008 20:10:44 -0400
I've been doing Core Data unit tests using a MOC backed by an in-
memory store. It gets the model using [NSManagedObjectModel
mergedModelFromBundles:nil]. I didn't have to include the app's model
file to the unit test target or anything. It seems to load it it fine
directly from the app bundle.
I use this category on NSManagedObjectContext to get a MOC for unit
testing. YMMV.
@implementation NSManagedObjectContext (UnitTests)
// Configure a MOC backed by an in-memory store based on all bundled
model files.
+ (NSManagedObjectContext *) inMemoryMOCForTesting;
{
// Set up a persistent store coordinator with an in-memory store.
NSManagedObjectModel* model = [NSManagedObjectModel
mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *coordinator =
[[[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:model] autorelease];
if (coordinator == nil) {
NSLog(@"Can't get instance of an NSPersistentStoreCoordinator.");
return nil;
}
// Add an in-memory persistent store to the coordinator.
NSError *addStoreError = nil;
[coordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil URL:nil options:nil error:&addStoreError];
if (addStoreError) {
NSLog(@"Error setting up in-memory store unit test: ", addStoreError);
return nil;
}
// Now we can set up the managed object context and assign it to
persistent store coordinator.
NSManagedObjectContext *moc = [[[NSManagedObjectContext alloc] init]
autorelease];
[moc setPersistentStoreCoordinator: coordinator];
NSAssert( moc != nil, @"Can't set up managed object context for unit
test.");
return moc;
}
@end
----
In the test case's -setUp method, I invoke [NSManagedObjectContext
inMemoryMOCForTesting] and assign the returned MOC to an ivar. If the
MOC needs to be populated with model objects for testing, I can do
that in -setUp using this instance, or do it later as part of the
individual tests.
Not sure if this will help, or if there's something fundamentally
whacked with this approach. It's been working fine for me, though.
Bill
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden