Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

objective c - How to unit test my models now that I am using Core Data?

I have been developing an iphone application using a domain model, and have put off the persistence aspect of the app until now. Core Data looks like a really good solution since I already have a well defined model but I am running into a snag with my existing unit tests.

Here is simple example of what I have now:

- (void)test_full_name_returns_correct_string {
    Patient *patient = [[Patient alloc] init];  
    patient.firstName = @"charlie";
    patient.lastName = @"chaplin";
    STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");
}  

How can I make this work once my Patient object extends from NSManagedObject and uses @dynamic for the firstName and lastName properties?

Has anyone else run into this type of this with Core Data? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to build a Core Data stack, either within each method or in -setUp and then tear it down. Using an NSInMemoryPersistentStore will keep things fast and in-memory for your unit tests. Add a @property (nonatomic,retain) NSManagedObjectContext *moc to your TestCase subclass. Then:

- (void)setUp {
  NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:bundleContainingXCDataModel]];
  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.moc = [[NSManagedObjectContext alloc] init];
  self.moc.persistentStoreCoordinator = psc;

  [mom release];
  [psc release];

}

- (void)tearDown {
  self.moc = nil;
}

Your test method then looks like:

- (void)test_full_name_returns_correct_string {
    Patient *patient = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.moc];

    patient.firstName = @"charlie";
    patient.lastName = @"chaplin";
    STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");
}

assuming your entity is named Person. There was a memory leak in your version of the method, by the way; patient should be -release'd in the non-Core Data version (insertNewObjectForEntityForName:managedObjectContext: returns an autoreleased instance).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...