Q:

Unit Testing with Core Data objects in XCode 4.5 using OCUnit in iOS-Development

Is there a simple way out there to create NSManagedObjects for testing reasons without to use the managed object context created for the release Application?
I'm now into Core Data coding for a couple of weeks but still having some issues in the details ... why can't I just alloc and init objects for testing? Do I really have to handle with a second persistant store / managed object context (and which one)?
I have to test some methods written in my NSManagedObject subclasses ...

A:

Trust me, you do NOT want to test core data objects without using a MOC.  You have to do unsound things at best.
However, if you don't want to use your actual database, use an in memory store.  It's very simple to set up.  In fact, it's what I use for a lot of my own unit testing.
I caution you, though.  There are a number of things that do not behave the same with SQL stores and in-memory stores.  The most common problem will be with predicates.  Read the docs to make sure your predicates are right.
I will say that during testing, you can use the in-memory MOC, but you should have a configuration that runs ALL you tests on the actual database itself to make sure it al works.  For speed, maybe you use the in-memory database for normal use, and use the actual one for scheduled continuous-integration testing.
As an example, you can do something like this to create your in-memory MOC...
- (NSManagedObjectContext*)managedObjectContextWithConcurrencyType:(NSManagedObjectContextConcurrencyType)concurrencyType {
    NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:nil];
    STAssertNotNil(mom, @"Can not create MOM from main bundle");

    NSPersistentStoreCoordinator *psc = [[MyPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
    STAssertNotNil(psc, @"Can not create persistent store coordinator");
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:0];
    STAssertNotNil(store, @"Can not create In-Memory persistent store");

    MyManagedObjectContext *moc = [[MyManagedObjectContext alloc] initWithConcurrencyType:concurrencyType];
    moc.persistentStoreCoordinator = psc;

    return moc;
}

