Tuesday, September 01, 2009

Mocking Delegates

I never realised you could do this; use Rhino Mocks to mock a delegate:

using System;
using Rhino.Mocks;
using NUnit.Framework;

namespace Mike.MockingLambdas
{
    [TestFixture]
    public class Can_a_lambda_be_mocked
    {
        [Test]
        public void Lets_try()
        {
            const string text = "some text";

            var mockAction = MockRepository.GenerateMock<Action<string>>();
            var runsAnAction = new RunsAnAction(mockAction);
            runsAnAction.RunIt(text);

            mockAction.AssertWasCalled(x => x(text));
        }
    }

    public class RunsAnAction
    {
        private readonly Action<string> action;

        public RunsAnAction(Action<string> action)
        {
            this.action = action;
        }

        public void RunIt(string text)
        {
            action(text);
        }
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.