gpt4 book ai didi

objective-c - OCMock : Make a stub do something

转载 作者:行者123 更新时间:2023-12-03 17:27:16 25 4
gpt4 key购买 nike

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

最佳答案

我原来的答案偏离了轨道:OCMock 不支持这个!如果您想更改 OCMock 以支持此功能,则需要执行一些操作,例如向 OCMockRecorder 添加 BOOL returnValueIsFromInspiration 字段,并添加一个方法来设置此功能:

- (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)被框架隐藏。

关于objective-c - OCMock : Make a stub do something,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/483789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com