OCMock stub class methods of the class that is being tested

615 views Asked by At
+(NSString *) classMethod:(id)someDataObject
{
    NSString *returnStr;

    //do something with someDataObject and set returnStr
    //...    

    returnStr = [NSString stringWithFormat:@"%@%@", returnStr,[self getCurrentTimestamp]];

    return returnStr;
}

+ (NSString *)getCurrentTimestamp
{
    NSNumber *t = [NSNumber numberWithLong:[[NSDate date] timeIntervalSince1970]];
    return [t stringValue];
}

I am struggling to write test case for the classMethod because when I run OCUnit test and pass OCMock object to classMethod the output will be always different as I add timestamp. What is the best approach to stub class method - getCurrentTimestamp? Is it actually possible to stub class methods of the class that is being tested?

I tried like this, but it is not working:

 id mock =  [OCMockObject mockForClass:[MyClass class]];
 [[[mock stub] andReturn:@1378468455] getCurrentTimestamp];

 NSString *str = [MyClass classMethod:someMockObject];
2

There are 2 answers

0
sash On BEST ANSWER

Thank you @BenFlynn. Your example (as well as mine) is working indeed. The problem was that "MyClass.h" was checked in Target Membership for the unite test too. "MyClass.h" should target only project (I am not sure why, maybe someone can explain it).

1
Ben Flynn On

This works fine for me:

+(NSString *) classMethod:(id)someDataObject
{
    NSString *returnStr = @"prefix-";
    returnStr = [NSString stringWithFormat:@"%@%@", returnStr,[self getCurrentTimestamp]];
    return returnStr;
}

+ (NSString *)getCurrentTimestamp
{
    NSNumber *t = [NSNumber numberWithLong:[[NSDate date] timeIntervalSince1970]];
    return [t stringValue];
}

- (void)testClass
{
    id mock =  [OCMockObject mockForClass:[Bar class]];
    [[[mock stub] andReturn:@"1378468455"] getCurrentTimestamp];   
    NSString *str = [Bar classMethod:nil];
    NSLog(@"Str: %@", str);
}

// Result: 
// Str: prefix-1378468455

Can you confirm your OCMock version, change the number to a string, and / or explain how it is not working for you?