MvcMailer: Unable to run NUnit tests in Razor Views that use Url.Action

Here is my problem - I use MvcMailer to create beautifully formatted emails using Razor syntax, and this is a great tool to use for this

The problem I'm encountering is some sort of syntax from my view for one of the emails I am sending:

<p>Click here to return to <a href="@Url.Abs(Url.Action("Details", "Home", new{ Id=ViewBag.IdeaId}))">@ViewBag.IdeaName</a></p> 

Whenever I try to run my unit tests, the following error message appears:

Can we send email notifications for new comments ?: System.ArgumentNullException: value cannot be null. Parameter Name: httpContext

Stacktrace - abbreviated for brevity, only for the relevant sections:

in System.Web.Routing.RouteCollection.GetRouteData (HttpContextBase httpContext) in Mvc.Mailer.MailerBase.CreateControllerContext () in Mvc.Mailer.MailerBase.ViewExists (String viewName, String masterName) in Castle.OnMetes.Omementses ) in Castle.DynamicProxy.AbstractInvocation.Proceed ()

The problem is that my HttpContext is null - is there a simple way to unit test the MvcMailer method without having to mock the entire controller context up to the route results?

+3
nunit moq asp.net-mvc-3 razor mvcmailer
source share
2 answers

You can take a look at the section called Unit Test Your Mailers in the MvcMailer wiki. All you need to do is just mock the PopulateBody method and then it bypasses the visualization of the view as part of the testing. It should look something like this:

 _userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<MailMessage>(), "Welcome", null)); 

Hope this helps!

+4
source share

This syntax worked for me:

 var userMailerMock = new Mock<UserMailer> {CallBase = true}; userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<MailMessage>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>>())); 

You might also want to make fun of another overload (if that doesn't help or just be sure):

 userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<MailMessage>(), It.IsAny<string>(), It.IsAny<Dictionary<string,string>>())); 
+1
source share

All Articles