I have a class that relies on NSUserDefaults, which I am trying to do unit-test, and I am providing NSUserDefaults as a layout in my test class. When I run the test, I get an error message:
OCMockObject [NSUserDefaults]: unexpected method called: dictionaryForKey: @ "response"
I am trying to make fun of this instance method of the NSUserDefaults class:
- (NSDictionary *)dictionaryForKey:(NSString *)defaultName;
using call format:
[[[mockClass stub] andReturn:someDictionary] dictionaryForKey:@"aKey"]
to tell the layout that it needs to expect the dictionaryForKey method. But anyway, this is not written down or is not suitable for saying that the layout is expecting, since the error tells me that the layout never expected to call the dictionary for the dictionary.
The way I call the stub and Return seems very similar to this question , but in this case the poster says it gets the return value. My test case:
-(void)testSomeWork
{
id userDefaultsMock = [OCMockObject mockForClass:[NSUserDefaults class]];
MyClass *myClass = [[MyClass alloc] initWith:userDefaultsMock];
NSDictionary *dictionary = [NSDictionary dictionary];
[[[userDefaultsMock stub] andReturn:dictionary] dictionaryForKey:@"response"];
BOOL result = [myClass doSomeWork];
STAssertTrue(result, @"not working right");
[myClass release];
[userDefaultsMock verify];
}
My class:
@implementation MyClass
@synthesize userDefaults;
- (id)initWith:(NSUserDefaults *aValue)
{
if (self = [super init])
{
self.userDefaults = aValue;
}
return self;
}
- (BOOL)doSomeWork
{
NSDictionary *response = [userDefaults dictionaryForKey:@"response"];
if (response != nil)
{
return YES;
}
return NO;
}
@end
Any suggestions?
source
share