我一直在使用域模型开发iphone应用程序,并将应用程序的持久性方面推迟到现在.核心数据看起来是一个非常好的解决方案,因为我已经有了一个定义良好的模型,但我在现有的单元测试中遇到了障碍.

以下是我现在拥有的简单例子:

- (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属性,我该如何实现这一点?

有没有其他人在核心数据方面遇到过这种情况?谢谢

推荐答案

您需要在每个方法中或在-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:返回自动删除的实例).

Objective-c相关问答推荐

NSMutableDictionary 的深层可变副本

如何删除警告按钮的框架在运行时会有所不同.

Objective C for循环中断并继续

setFont 已弃用?

增加推送通知徽章 iPhone

Objective-C (cocoa) 等价于python的endswith/beginswith

块引用作为Objective-C中的实例变量

UIScreen MainScreen Bounds 返回错误的大小

在 iOS 中创建带有 URL 的 UIImage

在 ObjC 实现文件中声明的实例变量

iOS 在设备旋转时更改自动布局约束

主队列上的 dispatch_sync 与 dispatch_async

如何在 Objective-C 中将 NSString 解析为 BOOL?

在 switch 语句中使用 NSString

计算 UILabel 文本大小

UIScrollView - 显示滚动条

如何在 Objective-C 中添加具有自己的 UIViewController 的子视图?

点击手势识别器 - 哪个对象被点击了?

当 UIView 框架更改时,视图内的 AVPlayer 层不会调整大小

Objective-C in,out,inout,byref,byval, .. 等等.这些是什么?