views:

262

answers:

1

I'm writing unit tests using RhinoMocks for mocking, and now I'm in need of some new functionality which I haven't used before.

I'd like to call a function, which again will call an async function. To simulate that the async function finishes and triggers the given callback with the result from execution I assume I can use the Callback functionality in RhinoMocks, but how do I do this?

Basically what I'd like to do is something like this:

fakeSomething = MockRepository.GenerateMock<ISomething>();
fakeSomething.FictionousFunctionSettingCallback(MyFunctionCalled, MyCallback, theParameterToGiveCallback);
var myObj = new MyClass(fakeSomething);    
myObj.Foo(); 
// Foo() now fires the function MyFunctionCalled asynchronous, 
// and eventually would trigger some callback

So; is there a true function I can replace this "FictionousFunction" with to set this up? Please ask if this was unclear..

+2  A: 

Just specify it using WhenCalled:

fakeSomething = MockRepository.GenerateMock<ISomething>();
fakeSomething
  .Stub(x => x.Foo())
  .WhenCalled(call => /* do whatever you want */);

for instance, you can use the Arguments property of the call argument:

fakeSomething
  .Stub(x => x.Foo(Arg<int>.Is.Anything))
  .WhenCalled(call => 
  { 
    int myArg = (int)call.Arguments[0]; // first arg is an int
    DoStuff(myArg);
  });

It is not asynchronous. You most probably don't need it to be asynchronous, it makes your life easier anyway if it isn't.

Stefan Steinegger
Thanks! This sounds like just the functionality I'm looking for. Christmas is catching up on me here, so have to wait a few days before I get to test it.. Awaiting to accept the answer in case I have some follow up questions. Thanks again!
stiank81
And no - I definitely don't want this to be async in my tests. The functionality I'm mocking is async, but I will fake it in a sync way - which is why I need to trigger another function call when the mocked function is called.
stiank81
Finally tested it. This was just what I needed! Works fine - just need to add .Stub(..) after fakeSomething. Thanks again!
stiank81
Yes, Stub was missing, fixed it.
Stefan Steinegger