我一直在使用域模型开发 iphone 应用程序,并且一直推迟到现在应用程序的持久性方面。 Core Data 看起来是一个非常好的解决方案,因为我已经有了一个定义明确的模型,但是我在现有的单元测试中遇到了障碍。
这是我现在拥有的简单示例:
- (void)test_full_name_returns_correct_string {
Patient *patient = [[Patient alloc] init];
patient.firstName = @"charlie";
patient.lastName = @"chaplin";
STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");
}
一旦我的 Patient 对象从 NSManagedObject 扩展并将@dynamic 用于 firstName 和 lastName 属性,我该如何进行这项工作?
还有其他人在使用 Core Data 时遇到过这种情况吗?谢谢。
最佳答案
您需要在每个方法中或在 -setUp
中构建核心数据堆栈,然后将其拆除。使用 NSInMemoryPersistentStore
将为您的单元测试保持快速和内存中的事情。将 @property (nonatomic,retain) NSManagedObjectContext *moc
添加到您的 TestCase 子类。那么:
- (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:
返回一个自动发布的实例)。
关于objective-c - 既然我正在使用 Core Data,如何对我的模型进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1849802/