Udontknow
Udontknow

Reputation: 1580

Handling parameterized calls in Rhino Mocks

I have a mailer class, it has a "SendMessage" method that needs an object implementing an interface IEMailConfiguration. I wanted to mock the mailer so that it does not send the mail but instead just adds the given mail configuration object to a list.

This is what i got so far (not too much, i know):

 var mailsSent = new List<IEmailConfiguration>();
 mailerMock = MockRepository.GenerateStrictMock<Mailer>();

I have used Expect() and Do() calls for mocking parameterless calls, which was fairly easy, but now i don´t see the solution: How do i get the argument of the Expect part to be used in the Do call?

mailerMock.Expect( x=> x.SendMessage(**AnyConfiguration**)).Do(mailsSent.Add(**AnyConfiguration**)

Upvotes: 1

Views: 41

Answers (1)

alex.b
alex.b

Reputation: 4567

Probably you want to use WhenCalled method:

    class Program
    {
        static void Main()
        {
        List<IEmailConfiguration> performedCalls = new List<IEmailConfiguration>();

        // preparing test instance
        var mailerMock = MockRepository.GenerateStrictMock<Mailer>();
        mailerMock.Expect(x => x.SendMessage(Arg<DummyEmailConfiguration>.Is.Anything))
                  .WhenCalled(methodInvocation => // that's what you need
                  {
                      var config = methodInvocation.Arguments.OfType<IEmailConfiguration>().Single();
                      performedCalls.Add(config);
                  });

        // testing 
        for (int i = 0; i < 10; i++)
        {
            mailerMock.SendMessage(new DummyEmailConfiguration("world" + i + "@mail.com", "hello world" + i));
        }

        // dumping info
        foreach (var call in performedCalls)
        {
            Console.WriteLine(call);
        }
    }
}

public interface IEmailConfiguration
{
    string To { get; }
    string Message { get; }
}

public interface Mailer
{
    void SendMessage(IEmailConfiguration config);
}

internal class DummyEmailConfiguration : IEmailConfiguration
{
    public DummyEmailConfiguration(string to, string message)
    {
        To = to;
        Message = message;
    }

    public string To
    {
        get;
        private set;
    }

    public string Message
    {
        get;
        private set;
    }
    public override string ToString()
    {
        return To + ": " + Message;
    }
}

Upvotes: 1

Related Questions