Ayende @ Wiki

Sometimes you want to be able to verify/affect the invocation of a delegate (this is especially useful if you're used to functional programming) and pass delegates around to do your bidding. Personally, I find it a very useful technique. Rhino Mocks allows you to handle that cleanly by mocking the delegate call, and put it under all the usual capabilities that you have in Rhino Mocks. Here is an example:

[Test]
public void GenericDelegate()
{
  Action<int> action = mocks.CreateMock<Action<int>>();
  for (int i = 0; i < 10; i++)
  {
    action(i);
  }
  mocks.ReplayAll();
  ForEachFromZeroToNine(action);
  mocks.VerifyAll();
}

private void ForEachFromZeroToNine(Action<int> act) { for (int i = 0; i < 10; i++) { act(i); } }


The example here is using a generic delegate, but of course all delegates are supported.

The following example shows mocking a Func<int, int> delegate using the Arrange Act Assert (AAA) syntax introduced in Rhino Mocks 3.5.

//Class under test:
public class SomeClass {
    private readonly Func<int, int> _mapper;
    public SomeClass(Func<int, int> mapper) {
        _mapper = mapper;
    }
    public int DoSomething(int toThisInt) {
        return _mapper(toThisInt);
    }
}

//In test fixture: [Test] public void MockingDelegates() { var stubMapper = MockRepository.GenerateStub<Func<int, int>>(); var expectedResult = 1234; stubMapper.Stub(x => x(10)).Return(expectedResult); var someClass = new SomeClass(stubMapper);

var result = someClass.DoSomething(10);

Assert.AreEqual(expectedResult, result); }


Up: Rhino Mocks Documentation
Next: Rhino Mocks Events

ScrewTurn Wiki version 2.0 Beta. Some of the icons created by FamFamFam.