XCTest和CoreData [英] XCTest and CoreData
问题描述
我正在尝试使用XCTest类和方法在Xcode 5中对我的模型进行单元测试。
I am trying to Unit test my model in Xcode 5 by using the XCTest classes and methods.
因为我的模型类继承了 managedObject
,我不能只是实例化(alloc / init)它们并调用getter和setter或我需要测试的方法。
我需要使用 NSEntityDescription
创建它们并使用 managedObjectContext
。
Because my model classes inherit of managedObject
, I can't just instantiate (alloc/init) them and call the getters and setters or the methods I need to test.
I need to create them by using the NSEntityDescription
and use a managedObjectContext
.
就这一点而言,我遇到了麻烦。
我不知道在哪里以及如何为单元测试创建 managedObjectContext
。
That is with this point that I get troubles.
I don't know where and how to create the managedObjectContext
for unit tests purpose.
如果任何人都有一些建议或代码示例,这将非常有帮助。
谢谢。
If anyone has some advice or code examples, it will be very helpful. Thanks.
推荐答案
我使用内存存储来进行单元测试并在其中创建所有实体。
I use an in memory store to for my unit tests and create all the entities within that.
此类方法可以放在 TestsHelper.m
+ (NSManagedObjectContext *)managedObjectContextForTests {
static NSManagedObjectModel *model = nil;
if (!model) {
model = [NSManagedObjectModel mergedModelFromBundles:[NSBundle allBundles]];
}
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSPersistentStore *store = [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil];
NSAssert(store, @"Should have a store by now");
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
moc.persistentStoreCoordinator = psc;
return moc;
}
这对我有用,因为我使用依赖注入来传递我的moc而不是使用单身人士。
This works for me because I use Dependency Injection to pass my moc around rather than using a singleton.
这篇关于XCTest和CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!