从CoreData模板开始,我已经构建了一个使用CoreData来操作数据模型的iPhone应用程序。到目前为止工作......
现在我决定,我需要一些“单元”测试来检查核心数据模型是否被正确操作(到目前为止,我只进行了手动检查并直接使用CoreDataEditor检查了数据库)。我跟着
如何在Xcode中设置UnitTests。到目前为止,这对逻辑和应用程序测试都有效。但是,我无法使用CoreData后端进行“单元”测试(它找不到我的数据模型,我不知道要包含什么或链接等...)
是否有关于如何对核心数据iphone app进行“单元”测试的指针/描述?
PS:我知道用数据库后端测试并不严格来说是“单元”测试。我不关心测试是否在真实应用程序(ApplicationTesting)的模拟器上,或者它是否只是一个专门针对单元测试(LogicTest)的核心数据后端,我将在setUp期间填充一些测试对象。</ p > 编辑:我找到了 How to unit test my models now that I am using Core Data?和 http://chanson.livejournal.com/115621.html 但现在我遇到了所描述的问题 iPhone UnitTesting UITextField value and otest error 133 ......好吧,除了我有错误代码134: - (((任何想法?答案 0 :(得分:11)
行。我搞定了......
按照此处所述创建LogicTests(设置逻辑测试部分): http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html
手动将CoreData.framework添加到新创建的逻辑测试目标中:将其从应用程序目标拖到逻辑测试目标(文件夹“使用库链接二进制文件”)。
右键点击您的* .xcdatamodeld并选择获取信息 - &gt;目标。选择逻辑测试目标(出于某种奇怪的原因,在我的情况下没有选择实际的应用程序目标......但是这样做有效)
在您的单元测试类(您在步骤1中创建:LogicTests.m)中添加以下方法:
- (void) setUp {
NSArray *bundles = [NSArray arrayWithObject:[NSBundle bundleForClass:[self class]]];
NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:bundles];
STAssertNotNil(mom, @"ManangedObjectModel ist nil");
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.context = [[NSManagedObjectContext alloc] init];
self.context.persistentStoreCoordinator = psc;
[mom release];
[psc release];
}
现在您已经设置了具有核心数据支持的逻辑测试。通过构建LogicTests目标,逻辑测试是独立完成的(无需模拟器)。为此,创建了一个临时的内存数据库。在您的测试方法中,您现在可以执行以下操作:
- (void) testStuff {
NSManagedObject *managedObj = [NSEntityDescription insertNewObjectForEntityForName:@"Account" inManagedObjectContext:self.context];
[managedObj setValue:[NSNumber numberWithInt:90000] forKey:@"id"];
NSError *error = nil;
if (![self.context save:&error]) {
STFail(@"Fehler beim Speichern: %@, %@", error, [error userInfo]);
}
}
希望这有帮助....玩得开心!