OCMock for a method with an argument and returns a value

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)
    {
        // some stuff happens here
        return YES;
    }

    return NO;
}   
@end

Any suggestions?

+3
source share
1 answer

Not sure if you understood this, but this is probably due to using a validation stub. You must use a pending check.

i.e.

[[[userDefaultsMock expect] andReturn:dictionary] dictionaryForKey:@"response"];
...
[userDefaultsMock verify];

In this example, you use validation to confirm that your method actually called the expected method (dictionaryForKey :). You use a stub so that your method calls this method on the Mock Object, but you do not need to verify that it has been called.

+5
source

Source: https://habr.com/ru/post/1727518/


All Articles