I had the same puzzle. I like to keep unit test coverage at 100% whenever possible. There is no easy way to generate an organic error condition. Actually, I'm not sure that the current implementation of the 4 types of storage that come with Core Data will ever throw an error in response to executeFetchRequest: error. But, as this may happen in the future, here is what I did:
case unit test, , , executeFetchRequest: error. NSIncrementalStore, . [NSManagedObjectContext executeFetchRequest:error] [NSPersistentStoreCoordinator executeRequest:withContext:error:], [NSPersistentStore executeRequest:withContext:error:] . , "" - executeRequest:withContext:error:. , , NSPersistentStore, .
#define kErrorProneStore @"ErrorProneStore"
@interface ErrorProneStore : NSIncrementalStore
@end
@implementation ErrorProneStore
- (BOOL)loadMetadata:(NSError **)error
{
NSDictionary * metaData = @{NSStoreTypeKey : kErrorProneStore, NSStoreUUIDKey : @""};
[self setMetadata:metaData];
return YES;
}
-(void)populateError:(NSError **)error
{
if (error != NULL)
{
*error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain
code:NSPersistentStoreOperationError
userInfo:nil];
}
}
- (id)executeRequest:(NSPersistentStoreRequest *)request
withContext:(NSManagedObjectContext *)context
error:(NSError **)error
{
[self populateError:error];
return nil;
}
- (NSIncrementalStoreNode *)newValuesForObjectWithID:(NSManagedObjectID *)objectID
withContext:(NSManagedObjectContext *)context
error:(NSError **)error
{
[self populateError:error];
return nil;
}
- (id)newValueForRelationship:(NSRelationshipDescription *)relationship
forObjectWithID:(NSManagedObjectID *)objectID
withContext:(NSManagedObjectContext *)context
error:(NSError **)error
{
[self populateError:error];
return nil;
}
- (NSArray *)obtainPermanentIDsForObjects:(NSArray *)array
error:(NSError **)error
{
[self populateError:error];
return nil;
}
@end
Core Data ErrorProneStore , .
- (void)testFetchRequestErrorHandling
{
NSManagedObjectModel * model = [NSManagedObjectModel mergedModelFromBundles:nil];
[NSPersistentStoreCoordinator registerStoreClass:[ErrorProneStore class]
forStoreType:kErrorProneStore];
NSPersistentStoreCoordinator * coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSManagedObjectContext * context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[context setPersistentStoreCoordinator:coordinator];
[coordinator addPersistentStoreWithType:kErrorProneStore
configuration:nil
URL:nil
options:nil
error:nil];
NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"AValidEntity"];
NSError * error;
[context executeFetchRequest:request
error:&error];
STAssertNotNil(error, @"Error should always be nil");
}