2017-04-26 8 views
0

私のcoredataメソッドはこちらです。これをチェックするユニットテストケースを書く方法。目的のcでコアデータを使用したユニットテスト

方法は

- (NSArray *)fetchUserWithUsername:(NSString *)username { 
if (username != nil) { 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

    NSEntityDescription *userEntity = [NSEntityDescription entityForName:@“EntityName” inManagedObjectContext:[self sharedContext]]; 
    [fetchRequest setEntity:userEntity]; 
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"username = %@", username]; 

    NSError *error; 
    NSArray *fetchedObjects = [[self sharedContext] executeFetchRequest:fetchRequest error:&error]; 

    return fetchedObjects; 
} 

return nil; 
} 

答えて

0

は、メモリ内ストアを作成し、オブジェクトにこれを注入coredataからフェッチするcoredataに

- (void)saveUserDetails:(Model *)userDetail { 
if(userDetail != nil) { 
    UserEntity *user = [NSEntityDescription insertNewObjectForEntityForName:@“EntityName” inManagedObjectContext:[self sharedContext]]; 

    NSArray *fetchArray = [self fetchUserWithUsername:userDetail.username]; 

    if ([fetchArray count] == 0) { 
     user.username = userDetail.username; 
     [self saveContext]; 
    } 
} 
} 

メソッドを保存します。

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyResource" withExtension:@"momd"]; 
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom]; 
XCTAssertTrue([psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL] ? YES : NO, @"Should be able to add in-memory store"); 

NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
context.persistentStoreCoordinator = psc; 
+0

Iは、上記のコードの端 UserDetails *ユーザー= [NSEntityDescription insertNewObjectForEntityForName: "UserDetails" inManagedObjectContext @:コンテキスト]でこのコードを追加しました。 user.username = @ "XXX"; テストケースが成功しましたが、saveメソッドがわかる方法は –

+0

となりますが、これは実際のデータベースでは変更されません。私は正しい? –

+0

*変更*します。述語のセットが異なるため、特にフェッチは異なります。https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/PersistentStoreFeatures.htmlと、*述語のフェッチと記述子の並べ替え*。ただし、コードに制限が適用されない場合は、インメモリストアを使用できます。テストの開始時にSQLストアを構築することは現実に近いものです。多くの場合、テストのためにストア内にいくつかのインスタンスを置く必要があります。 –

関連する問題