Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTest and CoreData

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.

like image 902
Maxime Capelle Avatar asked Jan 30 '14 15:01

Maxime Capelle


People also ask

What is XCTest used for?

A testing framework that allows to create and run unit tests, performance tests, and UI tests for your Xcode project. Tests assert that certain conditions are satisfied during code execution, and record test failures if those conditions are not satisfied.

What is XCTest framework?

Overview. Use the XCTest framework to write unit tests for your Xcode projects that integrate seamlessly with Xcode's testing workflow. Tests assert that certain conditions are satisfied during code execution, and record test failures (with optional messages) if those conditions aren't satisfied.

Should I use Core Data?

The next time you need to store data, you should have a better idea of your options. Core Data is unnecessary for random pieces of unrelated data, but it's a perfect fit for a large, relational data set. The defaults system is ideal for small, random pieces of unrelated data, such as settings or the user's preferences.


1 Answers

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.

like image 102
Abizern Avatar answered Sep 18 '22 15:09

Abizern