The mocking method that a delegate accepts in RhinoMocks

I have the following classes:

public class HelperClass { HandleFunction<T>(Func<T> func) { // Custom logic here func.Invoke(); // Custom logic here } // The class i want to test public class MainClass { pubic readonly HelperClass _helper; //Ctor MainClass(HelperClass helper) { _helper = helper; } public void Foo() { // Use the handle method _helper.HandleFunction(() => { // Foo logic here: Action1(); Action2(); //etc.. } } } 

I want to test only MainClass , I use RhinoMocks to mock HelperClass in my tests.
The problem is that although I am not interested in testing the HandleFunction() method, I am interested in checking Action1 , Action2 and other actions that were sent to HandleFunction() when called.

How can I mock the HandleFunction() method and, avoiding its internal logic, call the code that was sent to it as a parameter?

+6
source share
2 answers

Since your test block most likely requires the delegate to be called before continuing, you need to call it from the layout. There is still a difference between calling a real helper class implementation and a mock implementation. The layout does not include this "user logic". (If you need it, do not scoff at it!)

 IHelperClass helperMock = MockRepository.GenerateMock<IHelperClass>(); helperMock .Stub(x => x.HandleFunction<int>()) .WhenCalled(call => { var handler = (Func<int>)call.Argument[0]; handler.Invoke(); }); // create unit under test, inject mock unitUnderTest.Foo(); 
+5
source

In addition to Stefan's answer, I would like to show another way to determine the stub that calls the passed argument:

 handler .Stub(h => h.HandleFunction(Arg<Func<int>>.Is.Anything)) .Do((Action<Func<int>>)(func => func())); 

Read more about the Do() handler here and here .

+4
source

All Articles