1

コアデータを使用して、sqlite db からデータを保存および取得するアプリケーションに取り組んでいます。このために、データ リンク層のように機能する別のクラスを作成しました - LocalDBController

以下は、そのメソッドの 1 つである selectAddressWithAddressId の実装です。

- (NSDictionary *)selectAddressWithAddressId:(NSString *)addressId
{
    NSDictionary *dictToReturn = nil;

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"address_id == %@",addressId];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Address" inManagedObjectContext:self.moc]; // returning nil when invoked from test case class
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    [request setPredicate:predicate];

    NSError *err = nil;
    NSArray *array = [self.moc executeFetchRequest:request error:&err];

    // some more code...

    return dictToReturn;
}

現在、テスト ケース クラス (SenTestCase クラス) を実装しようとしています。

環境変数の値が「Run」の場合はデフォルトの永続ストアを使用し、環境変数の値が「Test」の場合はインメモリの永続ストアを使用するように、LocalDBController クラスの init メソッドを以下に記述しました。

- (id)init
{
    if (self = [super init]) {
        // initializing moc based on if run setting is used or test is used
        if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TARGET"] isEqualToString:@"TEST"]) {

            NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:nil];
            NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
            [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL];
            self.moc = [[NSManagedObjectContext alloc] init];
            self.moc.persistentStoreCoordinator = psc;
        }
        else
        {
            self.moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
        }

    }

    return self;
}

私のテストクラスでは、以下のメソッドを呼び出そうとしています:

STAssertNotNil([self.localDBController selectAddressWithAddressId:@"123"], @"No data found"); 

問題は-

この場合、selectAddressWithAddressId:メソッドで取得したentityDescriptionの値は nil ですが、self.moc の値は nil ではありません。そのため、コンソールにこの例外メッセージがスローされています: raise executeFetchRequest:error: A fetch request must have an entity..

テスト ケース バンドルに含まれていないクラス (appDelegate など) から上記のメソッドを実行すると、正常に動作します。

私が何か間違ったことをしているなら、誰かが私に提案できますか?

4

0 に答える 0