I have a core data application that uses an NSPredicate in one of its fetch requests. That predicate is defined as follows:
NSDictionary *teamsParams = [NSDictionary dictionaryWithObject:teamArray forKey:@"TEAMS"];
NSPredicate *predicate = [[NSPredicate predicateWithFormat:@"(homeTeam IN $TEAMS) AND (awayTeam IN $TEAMS)"] predicateWithSubstitutionVariables:teamsParams]
I apply this predicate to a fetch request and run it and it works as I expect: At least it works with the limited amount of data I have in my data store at this time.
I am now trying to write a set of unit tests for this code. To do this I am using OCMock to create an NSManagedObjectContext with its executeFetchRequest stubbed out with my own test implementation:
id contextMock = [OCMockObject mockForClass:[NSManagedObjectContext class]];
[[[contextMock stub] andCall:@selector(stubbedExecuteFetchRequest:error:) onObject:self] executeFetchRequest:[OCMArg any] error:(NSError * __autoreleasing *) [OCMArg anyPointer]];
- (NSArray *)stubbedExecuteFetchRequest:(NSFetchRequest *)request error:(NSError **)error {
// allGames is an array containing a list of "mocked" game instances
NSArray *result = [allGames filteredArrayUsingPredicate:[request predicate]];
return result;
}
So basically, I am trying to take the NSPredicate that was defined to run against a core data fetch request, and to run it against an array of mocked objects. The mocked objects all implement the homeTeam and awayTeams methods so as far as the predicate is concerned, this should work. Unfortunately, when running filteredArrayUsingPredicate against my dta array, it returns an empty array. I’m really stuck trying to figure this out, and I’m not sure how to effectively debug this one.
So I have two questions here, really:
- Is there a reason I’m missing here why using filteredArrayUsingPredicate against array of mock objects (instances of an NSProxy subclass) that implement the properties referenced in the predicate?
- Assuming there’s no obvious reasons, can anyone suggest an effective way of debugging this to see what it is filteredArrayUsingPredicate is evaluating here and why its failing for me?
Thanks for any help you can provide
I have managed to figure out most of what was happening here. The primary problem I was encountering here is that when I use filteredArrayUsingPredicate with a predicate containing a term such as “homeTeam”, my array objects are evaluated against this predicate by calling their valueForKey method with a key of “homeTeam”. I had expected this valueForKey invocation to return the value of the homeTeam accessor method, but for some reason that is not happening with my mock objects (that’s the part I still don’t understand about this)
Once I also stubbed the valueForKey method on my mock objects, and then worked through an OCMock bug (or limitation?) documented here, I was able to get my tests working,