问题的症结在于您的核心数据模型在测试中不可用,因此当您尝试存根读取的属性时,该方法不存在。Core Data 在运行时动态拦截属性访问器。
为了使您的模型可用,您需要确保您的 .xcdatamodeld 包含在您的单元测试目标中,并且您需要在测试中设置模型。我不确定您是否能够模拟动态属性,但在测试中对 Core Data 对象执行 CRUD 操作变得微不足道,因此无需模拟它们。这是在测试中初始化模型的一种方法:
static NSManagedObjectModel *model;
static NSPersistentStoreCoordinator *coordinator;
static NSManagedObjectContext *context;
static NSPersistentStore *store;
-(void)setUp {
[super setUp];
if (model == nil) {
@try {
NSString *modelPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"my-model" ofType:@"mom"];
NSURL *momURL = [NSURL fileURLWithPath:modelPath];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];
}
@catch (NSException *exception) {
NSLog(@"couldn't get model from bundle: %@", [exception reason]);
@throw exception;
}
}
coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSError *error;
store = [coordinator addPersistentStoreWithType: NSInMemoryStoreType
configuration: nil
URL: nil
options: nil
error: &error];
assertThat(store, isNot(nil));
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:coordinator];
}
-(void)tearDown {
// these assertions ensure the test was not short-circuited by a failure to initialize the model
assertThat(model, isNot(nil));
assertThat(context, isNot(nil));
assertThat(store, isNot(nil));
assertThat(coordinator, isNot(nil));
NSError *error = nil;
STAssertTrue([coordinator removePersistentStore:store error:&error],
@"couldn't remove persistent store: %@", [error userInfo]);
[super tearDown];
}
或者,您可以使用MagicalRecord显着简化事情。即使您不在应用程序中使用它,您也可以在测试中使用它来封装所有核心数据设置。这是我们的单元测试设置在带有 MagicalRecord 的应用程序中的样子:
-(void)setUp {
[super setUp];
[MagicalRecordHelpers setupCoreDataStackWithInMemoryStore];
}
-(void)tearDown {
[MagicalRecordHelpers cleanUp];
[super tearDown];
}