OCMock模拟协议的静态类方法。

时间:2014-10-27 16:44:13

标签: objective-c unit-testing ocmock

OCMock 3中的新功能是模拟class methods

是否可以模拟协议中定义的类方法?即

@protocol AViewControllerProtocol <NSObject>
+ (Type)typeForViewController;
@end

在我的单元测试课程中

- (void)testProtocolClassMethod {
    id mockedViewController = OCMProtocolMock(@protocol(AViewControllerProtocol));

    //This line compiles fine, but throws an exception at run time.
    OCMStub([mockedViewController typeForViewController]).andReturn(SomeType);
}

异常抛出

  

NSInvalidArgumentException:无法存根/期望/验证方法&#39; typeForViewController&#39;因为模拟类

中不存在这样的方法

1 个答案:

答案 0 :(得分:0)

这看起来像是在OCMock 3.1中的疏忽,但如果你愿意,你可以自己修复。

// OCProtocolMockObject.m
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    struct objc_method_description methodDescription = protocol_getMethodDescription(mockedProtocol, aSelector, YES, YES);
    if(methodDescription.name == NULL) 
    {
        methodDescription = protocol_getMethodDescription(mockedProtocol, aSelector, NO, YES);
    }
    // Add this case for required class methods
    if (methodDescription.name == NULL)
    {
        methodDescription = protocol_getMethodDescription(mockedProtocol, aSelector, YES, NO);
    }
    // Add this case for optional class methods
    if (methodDescription.name == NULL)
    {
        methodDescription = protocol_getMethodDescription(mockedProtocol, aSelector, NO, NO);
    }
    if(methodDescription.name == NULL)
    {
        return nil;
    }
    return [NSMethodSignature signatureWithObjCTypes:methodDescription.types];
}

我通过此测试验证了此修复程序:

- (void)testProtocolClassMethod {
    id mockedViewController = OCMProtocolMock(@protocol(AViewControllerProtocol));

    // FIXED: This line compiles fine, but throws an exception at run time.
    OCMStub([mockedViewController typeForViewController]).andReturn(SomeType);

    Type type = [mockedViewController typeForViewController];

    XCTAssertEqual(type, SomeType, @"Not equal!");

    OCMVerify([mockedViewController typeForViewController]);
}

我会在项目页面上提出请求。