OCMock期望一种类方法

时间:2013-10-15 16:58:17

标签: objective-c unit-testing ocmock

所以我希望能够期望为我的一个类

调用一个类方法
@implementation CustomClass

+ (void)method:(NSString*)string{
    [[self class] method:string object:nil];

}

+ (void)method:(NSString *)string object:(id)object {
    //do something with string and object
}

@end

我希望致电[CustomClass method:@""]并期待method: string:

我已经尝试了方法调配,但似乎只对存根有用。

1 个答案:

答案 0 :(得分:3)

您可以使用方法调配或OCMock进行测试。

使用方法调配,首先我们在测试实现文件中声明以下变量:

static NSString *passedString;
static id passedObject;

然后我们实现了一个存根方法(在测试类中)并继续调整:

+ (void)stub_method:(NSString *)string object:(id)object
{
    passedString = string;
    passedObject = object;
}

- (void) test__with_method_swizzling
{
    // Test preparation 
    passedString = nil;
    passedObject = [NSNull null];// Whatever object to verify that we pass nil

    Method originalMethod =
        class_getClassMethod([CustomClass class], @selector(method:object:));
    Method stubMethod =
        class_getClassMethod([self class], @selector(stub_method:object:));

    method_exchangeImplementations(originalMethod, stubMethod);

    NSString * const kFakeString = @"fake string";

    // Method to test
    [CustomClass method:kFakeString];

    // Verifications
    STAssertEquals(passedString, kFakeString, nil);
    STAssertNil(passedObject, nil);

    method_exchangeImplementations(stubMethod, originalMethod);
}

但我们可以用更简单的方式完成OCMock的相同工作:

- (void) test__with_OCMock
{
    // Test preparation 
    id mock = [OCMockObject mockForClass:[CustomClass class]];

    NSString * const kFakeString = @"fake string";
    [[mock expect] method:kFakeString object:nil];

    // Method to test
    [CustomClass method:kFakeString];

    // Verifications 
    [mock verify];
}