XCTest and CoreData

core-data, ios, unit-testing, xctest

Solution

I use an in memory store to for my unit tests and create all the entities within that.

This class method can be placed in `TestsHelper.m`

+ (NSManagedObjectContext *)managedObjectContextForTests {
    static NSManagedObjectModel *model = nil;
    if (!model) {
        model = [NSManagedObjectModel mergedModelFromBundles:[NSBundle allBundles]];
    }

    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil];
    NSAssert(store, @"Should have a store by now");

    NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    moc.persistentStoreCoordinator = psc;

    return moc;
}

This works for me because I use Dependency Injection to pass my moc around rather than using a singleton.

Problem

I am trying to Unit test my model in Xcode 5 by using the XCTest classes and methods. Because my model classes inherit of `managedObject`, I can't just instantiate (alloc/init) them and call the getters and setters or the methods I need to test. I need to create them by using the `NSEntityDescription` and use a `managedObjectContext`. That is with this point that I get troubles. I don't know where and how to create the `managedObjectContext` for unit tests purpose. If anyone has some advice or code examples, it will be very helpful. Thanks.

Original source