您需要在每个方法中或在-setUp
中构建一个核心数据堆栈,然后将其拆下.在单元测试中,使用NSInMemoryPersistentStore
将使事情保持快速和内存.在TestCase子类中添加一个@property (nonatomic,retain) NSManagedObjectContext *moc
.然后:
- (void)setUp {
NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:bundleContainingXCDataModel]];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
STAssertTrue([psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL] ? YES : NO, @"Should be able to add in-memory store");
self.moc = [[NSManagedObjectContext alloc] init];
self.moc.persistentStoreCoordinator = psc;
[mom release];
[psc release];
}
- (void)tearDown {
self.moc = nil;
}
您的测试方法如下所示:
- (void)test_full_name_returns_correct_string {
Patient *patient = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.moc];
patient.firstName = @"charlie";
patient.lastName = @"chaplin";
STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");
}
假设你的实体名为Person
.顺便说一句,你的方法版本有内存泄漏;在非核心数据版本中,患者应为-release
(insertNewObjectForEntityForName:managedObjectContext:
返回自动删除的实例).