如何对以下的代码进行单元测试?
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
NSString *sumOfTotalPaidBySelf = @"sumOfTotalPaidBySelf";
expressionDescription.name = sumOfTotalPaidBySelf;
expressionDescription.expression = [NSExpression expressionForKeyPath:@"@sum.moneyInMainCurrency"];
expressionDescription.expressionResultType = NSDoubleAttributeType;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MCPayment"];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"payingPerson = %@", self];
fetchRequest.propertiesToFetch = @[expressionDescription];
NSError *error = nil;
NSArray *fetchResult = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"%@: error fetching: %@", self, error);
return nil;
}
return [[fetchResult firstObject] objectForKey:sumOfTotalPaidBySelf];
到目前为止我学到的是,这个代码在查询已经包含存储在磁盘上的数据的数据库时应该可以工作。但是对于单元测试,我使用的是持久存储类型NSInMemoryStoreType,它在安装过程中预先填充了一些数据,并且数据仍然驻留在managedObjectContext中。
这是我的单元测试。
MCSharedBill *tonightsBill = [MCSharedBill addSharedBillToContext:_context];
MCPerson *fred = [tonightsBill addPerson];
fred.firstName = @"Fred";
MCPerson *anna = [tonightsBill addPerson];
anna.firstName = @"Anna";
MCPayment *drinks = [tonightsBill addPayment];
drinks.payingPerson = fred;
drinks.money = @(10);
drinks.descriptionOfPayment = @"coffee";
NSNumber *totalPaidByFred = fred.totalSumPaid;
// NSError *error = nil;
// [_context save:&error];
// XCTAssertFalse(error);
XCTAssertEqualWithAccuracy(@(10).doubleValue, totalPaidByFred.doubleValue, 0.001);
任何帮助都将不胜感激。
干杯。