Search code examples
c#asp.net-mvc-3nunitrhino-mocksmvcmailer

MvcMailer unit test with Rhino Mock, how to?


In a new project we use MvcMailer, it's great and I would like to know how I can test it using Rhino and NUnit? There's an other post on SO and a good Wiki page but it's not what I'm looking for. For my controllers I usualy test them with MvcContrib's Testhelper

  • I try first to mock the mailer class but if I do this I can't verify my ViewBag data, I'm having problem with the PopulateBody method and I have to build my own IMailerBase interface
  • I try after this to test the mailer as I do with controller using MvcContrib but it only accept Controller object in the InitializeController() so it did'nt work.
  • There's also a IsTestModeEnabled property in the MailerBase.cs class but when I test against it I get an error on empty URI.

Don't know what is the best way to do this and I'm looking for help, thanks everyone!


Solution

  • Here's the code how I did it :

    // arrange
        var passwordMailer = MockRepository.GeneratePartialMock<PasswordMailer>();
        passwordMailer.Stub(mailer => mailer.PopulateBody(Arg<MailMessage>.Is.Anything, Arg.Is("ForgotPassword"), Arg<string>.Is.Null, Arg<Dictionary<string, string>>.Is.Null));
    
        // act
        var mailMessage = passwordMailer.ForgotPassword("test@example.com", "4454-8838-73773");
    
        // assert
        Assert.AreEqual(string.Format(Login.mailBody, "4454-8838-73773"), passwordMailer.ViewBag.Body);
        Assert.AreEqual(Login.mailSubject, mailMessage.Subject);
        Assert.AreEqual("test@example.com", mailMessage.To.First().ToString());
    

    As you can see it, you can achieve it using partialMock functionnality from Rhino.