Forwarding contribution proposal: stubbing callbacks

3 views
Skip to first unread message

loomis

unread,
Jul 9, 2010, 4:09:20 PM7/9/10
to mockito-flex
Below there is a message I got from Peter, hope he does not mind:

Here's some async stuff I threw together today. Helps with rpc and
callbacks. Ever need to mock a ResultEvent?

Maybe you can incorporate this into the next release, and possibly on
the Stubber and integrations for convenience(i.e. callback() instead
of having to instantiate it).

internal class CallbackAnswer implements Answer, StubbingContextAware
{

private var _stubbingContext:StubbingContext;
private var _index:int;
private var _args:Array;

public function CallbackAnswer(index:int, args:Array = null) {
_index = index;
_args = args;
}

public function give():* {
if (!_stubbingContext)
throw new IllegalOperationError("A stubbing context has not been set
or an answer has been given already");
var callback:Function = _stubbingContext.args[_index] as Function;
return callback.apply(null, _args);
}

public function useContext(stubbingContext:StubbingContext):void {
_stubbingContext = stubbingContext;
}
}


Example:

given(mockService.someRPC(any(), anyOf(Function),
anyOf(Function))).will(new CallbackAnswer(1, [ResultEvent.create(new
Foo())]));

Or make me a contributor :)

-Peter Babinski

loomis

unread,
Jul 9, 2010, 4:10:31 PM7/9/10
to mockito-flex
I'd suggest changing the API/naming a bit to be little less cryptic.

A class I'd name InvokeCallbackFromArg.

And maybe we should leave only the arg number on the constructor and
add a function withArgs(...args):Answer;

The usage would look like:

given(mockService.someRPC(any(), anyOf(Function),
anyOf(Function))).will(new
InvokeCallbackFromArg(1).withArgs(ResultEvent.create(new Foo())));

A shorthand would be pretty similar:

given(mockService.someRPC(any(), anyOf(Function),
anyOf(Function))).will(invokeCallbackFromArg(1).withArgs(ResultEvent.create(new
Foo())));

In a actual test I'd even go further and create a shorthand that is
more expressive about what happens:

given(mockService.someRPC(any(), anyOf(Function),
anyOf(Function))).will(respondWithResult(new Foo()));

What do you think guys?

Cheers,
Kris
Reply all
Reply to author
Forward
0 new messages