2

I'm trying to mock my MailController

_mockMailController = new Mock<IMailController>();
_mockMailController.Setup(x => x.ForgotPassword("test@email.com"));

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

mailController.ForgotPassword("test@email.com").Deliver();

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

Ideally, we'd stub EmailResult ?

Alex
  • 37,502
  • 51
  • 204
  • 332

2 Answers2

1

You have not created a setup for the mock return a value from ForgotPassword method. With default behavior this will return default value for the type, which is null in this case.

You can mock the return value like this:

_mockMailController.Setup(x => x.ForgotPassword("test@email.com"))
                   .Returns(new SomeType());
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • Yes, I realise this. I'm sorry, perhaps i should have been more specific in my question. The return type for this is a very complex (and itself has lots of dependencies) so i was looking for someone who'd used ActionMailer.net, and mocked it, to share their experience – Alex May 03 '13 at 11:28
  • Well if you are not going to do anything with the the return type, you could move ActionMailer.Net code to another class. This way you could skip testing and mocking 3rd party component code. – Ufuk Hacıoğulları May 03 '13 at 11:32
1

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("recipient@sdf.com");
        From = "sender@sdf.com";
        Subject = "Subject";
        return Email();
    }
}
hydr
  • 408
  • 3
  • 10