4

所以我希望能够为我的一个类调用一个类方法

@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:

我尝试过方法调配,但似乎这只对存根有用。

4

1 回答 1

4

您可以使用方法 swizzling 或 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];
}
于 2013-10-16T15:32:52.160 回答