Unit Testing Core Data

As part of my ongoing Unit Testing learning, I've now managed to figure out the setUp and tearDown requirements. After setting up an empty test target in XCode (using the OCUnit framework), add the Core Data model file to your target's Compiled Sources tab:

TargetSettings

The example managed object model graph (entity graph?) I've used here is a single entity with a non-optional String attribute title, which has a default value of (Title):

MOM Example

Next, create a new Objective-C Test Case class (New File->Objective-C test case) making sure the new files are added to your Test target, and enter the following code:

In DefaultTest.h

// // DefaultTest.h // TestCD //

import <sentestingkit/SenTestingKit.h>

@interface DefaultTest : SenTestCase { NSManagedObjectContext managedObjectContext; NSManagedObjectModel managedObjectModel; NSPersistentStoreCoordinator *coodinator; }

@end

In DefaultTest.m

// // DefaultTest.m // TestCD // // Created by Chris Blunt on 17/08/2007. // Copyright 2007 MyCompanyName. All rights reserved. //

import "DefaultTest.h"

@implementation DefaultTest

  • (void)setUp { NSMutableSet *allBundles = [[NSMutableSet alloc] init]; [allBundles addObjectsFromArray:[NSBundle allBundles]]; [allBundles addObjectsFromArray:[NSBundle allFrameworks]];

managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:[allBundles allObjects]] retain];

coodinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];

managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:coodinator]; }

  • (void)tearDown { [managedObjectContext release]; [coodinator release]; [managedObjectModel release]; }

// Test to make sure the test framework is all set up and working - (void)testTruth { STAssertTrue( YES, @"True is not True" ); }

// Test the MOModel, MOContext and persistent stores are all setup - (void)testSetup { STAssertNotNil( managedObjectModel, @"model is nil" ); STAssertNotNil( coodinator, @"coordinator is nil" ); STAssertNotNil( managedObjectContext, @"context is nil" ); }

// Test creation of an entity in the managed object context - (void)testCreateEntity { NSManagedObject *entity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext];

STAssertNotNil( entity, @"Created entity was nil" );

// e.g. test that created entity's default title was set correctly STAssertEqualObjects( @"(Title)", [entity primitiveValueForKey:@"title"], @"New entity's expected title was not set (Title)" ); }

@end

« Previous Post

avatar

Chris Blunt

Plymouth Software

Devon, England

twitter.com/cblunt

github.com/cblunt

 

facebook.com/cbluntuk

flickr.com/photos/cblunt