문제

+(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

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).

다른 팁

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top