Search code examples
tddmoqactionmailer.net

Mocking MailController with ActionMailer.net using Moq


I'm trying to mock my MailController

_mockMailController = new Mock<IMailController>();
_mockMailController.Setup(x => x.ForgotPassword("[email protected]"));

My controller takes an IMailController as a dependancy, however when I call

mailController.ForgotPassword("[email protected]").Deliver();

I get a NullReferenceException (because ForgotPassword doesn't return anything, I guess)

Ideally, we'd stub EmailResult ?


Solution

  • I created a pull request for the ActionMailer.Net that intoduces an IEmailResult interface that makes mocking very easy. Have a look at this:

    https://bitbucket.org/swaj/actionmailer.net/pull-request/4/iemailresult-interface-for-better/

    Until the pull request is merged you could use a custom build from my frok of the project.

    https://bitbucket.org/hydr/xv-actionmailer.net

    Mocking get's as easy as writing (with FakeItEasy, Moq might be similar):

    //SetUp
    _myMailer = A.Fake<IMyMailer>();
    
    //Later on in Assert
    A.CallTo(() => _myMailer.MyTestEmail()).MustHaveHappened(Repeated.Exactly.Once);
    

    when the Mailer is defined like:

    public class MailController : MailerBase, IMyMailer
    {
        public IEmailResult MyTestEmail()
        {
            To.Add("[email protected]");
            From = "[email protected]";
            Subject = "Subject";
            return Email();
        }
    }