如何使用CoreData进行单元测试?

9
从CoreData模板开始,我构建了一个iPhone应用程序,使用CoreData来操作数据模型。目前为止运行良好...
现在我决定需要一些“单元”测试来检查核心数据模型是否被正确操作(到目前为止我只进行了手动检查,并直接使用CoreDataEditor检查了数据库)。我已经按照如下所述设置了Xcode中的UnitTests:http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html
这对于逻辑测试和应用程序测试都有效。然而,我无法让“单元”测试与CoreData后端一起工作(它找不到我的数据模型,我不知道要包含或链接什么等...)
有没有指针/描述如何对core data iphone应用程序进行“单元”测试?
PS:我知道使用数据库后端进行测试严格来说不是“单元”测试。我不关心测试是在模拟器上进行的还是在真实应用程序中进行的(ApplicationTesting),或者是否只是专门用于单元测试(LogicTest)的CoreData后端,在setUp期间我会填充一些测试对象。
编辑:我已经发现如何在使用Core Data的情况下对我的模型进行单元测试?http://chanson.livejournal.com/115621.html,但现在我遇到了iPhone UnitTesting UITextField值和otest错误133所描述的问题...好吧,除了我有错误代码134 :-( 任何想法?
1个回答

11

好的,我懂了......

  1. 按照这里所描述(设置逻辑测试节)创建LogicTests: http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html

  2. 将CoreData.framework手动添加到新创建的Logic Tests目标中:将其从应用程序目标拖到逻辑测试目标中(文件夹“链接二进制文件和库”)。

  3. 右键单击*.xcdatamodeld文件并选择“获取信息->目标”。 选择Logic Tests目标(由于某种奇怪的原因,在我的情况下实际应用程序目标未被选中...但那没关系)。

  4. 在你的单元测试类(在步骤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];
    }
    
    现在您已经设置了支持Core Data的逻辑测试。逻辑测试是在孤立环境中进行的(不使用模拟器),通过构建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]);
         }
    }
    

    希望这能帮到你... 祝玩得愉快!


1
很遗憾,该链接已经失效了。 - Houman
我找到了这个样例代码的链接,它似乎是那个无法使用的链接的伴侣: https://developer.apple.com/library/ios/samplecode/UnitTests/Introduction/Intro.html - idStar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接