我已经习惯了OCMock。来自Java / JMock背景,我现在正在寻找说出[[[myMock stub] returnValueFromCustomMethod] someMockedMethod];其中在测试类中定义returnValueFromCustomMethod的功能。我本来是按照[[[myMock stub] usingSelector:@selector(myMethod:)] someMockedMethod];的方式思考的,但是写完之后,我想知道我的第一种方法是否更有意义。不管怎样,有人可以告诉我是否以及如何做到这一点?

最佳答案

我原来的回答是偏离轨道的:OCMock不支持此功能!如果要更改OCMock以支持此操作,则需要执行一些操作,例如向OCMockRecorder添加BOOL returnValueIsFromInvocation字段,并添加一种方法来进行设置:

-(id)andReturnResultOfInvocation:(NSInvocation *)anInvocation {
  returnValueIsFromInvocation = YES;
  returnValueIsBoxed = NO;
  returnValueShouldBeThrown = NO;
  [returnValue自动发布];
  returnValue = [anInvocation保留];
  返回自我
}


然后教导setUpReturnValue调用调用(更改以粗体显示):

-(void)setUpReturnValue:(NSInvocation *)anInvocation
{
  如果(returnValueIsFromInvocation){
    NSInvocation * returnValueInvocation =(NSInvocation *)returnValue;
    [returnValueInvocation调用];
    无效*缓冲区= malloc([[[inInvocation methodSignature] methodReturnLength]);
    [returnValueInvocation getValue:buffer];
    [anInvocation setReturnValue:buffer];
    免费(缓冲区);
  }
  否则if(returnValueShouldBeThrown)
  {
    @throw returnValue;
  }
  否则if(returnValueIsBoxed)
  {
    if(strcmp([[[anInvocation methodSignature] methodReturnType],
              [(NSValue *)returnValue objCType])= 0)
      [NSException引发:NSInvalidArgumentException
                  格式:@“返回值与方法签名不匹配。”];
    无效*缓冲区= malloc([[[inInvocation methodSignature] methodReturnLength]);
    [returnValue getValue:buffer];
    [anInvocation setReturnValue:buffer];
    免费(缓冲区);
  }
  其他
  {
    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)。

关于objective-c - OCMock:使 stub 做某事,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/483789/

10-09 02:41