2009-01-27 64 views
1

我已經習慣了OCMock。來自Java/JMock背景我現在正在尋找能夠說[[[myMock stub] returnValueFromCustomMethod] someMockedMethod];其中returnValueFromCustomMethod在測試類中定義。我原本是按照[[[myMock stub] usingSelector:@selector(myMethod:)] someMockedMethod];的條款思考的,但寫完後我不知道我的第一種方法是否更有意義。無論哪種方式,有人可以告訴我是否以及如何做到這一點?OCMock:做一個存根做某事

回答

0

我原來的答案偏離軌道:OCMock不支持這個!如果你想改變OCMock來支持這一點,你需要做的像添加BOOL returnValueIsFromInvocation場OCMockRecorder,並添加一個方法進行此設置:

 
- (id)andReturnResultOfInvocation:(NSInvocation *)anInvocation { 
    returnValueIsFromInvocation = YES; 
    returnValueIsBoxed = NO; 
    returnValueShouldBeThrown = NO; 
    [returnValue autorelease]; 
    returnValue = [anInvocation retain]; 
    return self; 
} 

然後教setUpReturnValue調用調用(變化黑體):

 
- (void)setUpReturnValue:(NSInvocation *)anInvocation 
{ 
    if (returnValueIsFromInvocation) { 
    NSInvocation *returnValueInvocation = (NSInvocation *)returnValue; 
    [returnValueInvocation invoke]; 
    void *buffer = malloc([[anInvocation methodSignature] methodReturnLength]); 
    [returnValueInvocation getValue:buffer]; 
    [anInvocation setReturnValue:buffer]; 
    free(buffer); 
    } 
    else if(returnValueShouldBeThrown) 
    { 
    @throw returnValue; 
    } 
    else if(returnValueIsBoxed) 
    { 
    if(strcmp([[anInvocation methodSignature] methodReturnType], 
       [(NSValue *)returnValue objCType]) != 0) 
     [NSException raise:NSInvalidArgumentException 
        format:@"Return value does not match method signature."]; 
    void *buffer = malloc([[anInvocation methodSignature] methodReturnLength]); 
    [returnValue getValue:buffer]; 
    [anInvocation setReturnValue:buffer]; 
    free(buffer); 
    } 
    else 
    { 
    const char *returnType = [[anInvocation methodSignature] methodReturnType]; 
    const char *returnTypeWithoutQualifiers = returnType + (strlen(returnType) - 1); 
    if(strcmp(returnTypeWithoutQualifiers, @encode(id)) == 0) 
     [anInvocation setReturnValue:&returnValue]; 
    } 
} 

這種變化是很難通過引入子類,因爲你必須重寫返回OCMockRecorders方法(如stubexpect等),但OCMockObject(OCClassMockObject和OCProtocolMockObject的具體子類)做被隱藏該框架。