如何使用CoreData进行UnitTests?

nae*_*ger 9 iphone unit-testing core-data

从CoreData模板开始,我构建了一个使用CoreData来操作数据模型的iPhone应用程序.到目前为止工作......

现在我决定,我需要一些"单元"测试来检查核心数据模型是否被正确操作(到目前为止,我只进行了手动检查并使用CoreDataEditor直接检查数据库).我跟着

http://developer.apple.com/library/ios/#documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html

关于如何在Xcode中设置UnitTests.到目前为止,这对逻辑和应用程序测试都有效.但是,我无法使用CoreData后端进行"单元"测试(它找不到我的数据模型,我不知道要包含什么或链接等...)

是否有关于如何对核心数据iphone应用进行"单元"测试的指针/描述?

PS:我知道用数据库后端测试并不严格来说是"单元"测试.我不关心测试是否在真实应用程序(ApplicationTesting)的模拟器上,或者它是否只是一个专门针对单元测试(LogicTest)的核心数据后端,我将在setUp期间填充一些测试对象.

编辑:我已经找到了 如何对我的模型进行单元测试,因为我正在使用Core Data?和 http://chanson.livejournal.com/115621.html 但现在我遇到了iPhone UnitTesting UITextField值和otest错误133中描述的问题 ......好吧,除了我有错误代码134: - (((任何想法?

nae*_*ger 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添加到新创建的逻辑测试目标:将其从应用程序目标拖动到逻辑测试目标(文件夹"使用库链接二进制文件").

  3. 右键单击*.xcdatamodeld并选择Get Info - > Targets.选择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];
    }
    
    Run Code Online (Sandbox Code Playgroud)

现在,您已经设置了具有核心数据支持的逻辑测试.通过构建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]);
     }
}
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助....玩得开心!