fabb
fabb

Reputation: 11735

Stub Method and Dynamically Set its Return Value to an Input Parameter

I'd like to dynamically return a value dependent of a parameter to a mocked method, conceptionally like this:

[realObject stub] myMethod:CAPTUREDARGUMENT) andReturn:myMethod:CAPTUREDARGUMENT];

Or access the invocation in a block like with OCMock:

void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
    /* code that reads and modifies the invocation object */
};
[[[mock stub] andDo:theBlock] someMethod:[OCMArg any]];

Is that possible with Kiwi?

Upvotes: 1

Views: 804

Answers (2)

Adam Sharp
Adam Sharp

Reputation: 3668

The recommended way to capture arguments is using a capture spy, e.g.:

id testDouble = [SomeClass mock];
object.property = testDouble;

KWCaptureSpy *spy = [testDouble captureArgument:@selector(methodWithParam:) atIndex:0];

[object doSomethingWithProperty];

[[spy.argument should] equal:someResult];

It can also be achieved using stub:withBlock:, but capture spies tend to be make your intention clearer when it comes to the task of inspecting method arguments. This makes for more readable specs.

Upvotes: 0

fabb
fabb

Reputation: 11735

It is possible using stub:withBlock::

[realObject stub:@selector(myMethod:) withBlock:^id(NSArray *params) {
    return [params objectAtIndex:0];
];

Upvotes: 5

Related Questions