0
+(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];
}

我正在努力为 classMethod 编写测试用例,因为当我运行 OCUnit 测试并将 OCMock 对象传递给 classMethod 时,输出总是会随着我添加时间戳而不同。存根类方法的最佳方法是什么- getCurrentTimestamp?实际上是否可以存根正在测试的类的类方法?

我试过这样,但它不工作:

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

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

2 回答 2

1

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?

于 2013-09-06T15:22:42.357 回答
0

谢谢@BenFlynn。您的示例(以及我的示例)确实有效。问题是“MyClass.h”也在 Target Membership 中进行了联合测试。“MyClass.h”应该只针对项目(我不知道为什么,也许有人可以解释一下)。

于 2013-09-06T16:38:30.463 回答