Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvcMailer: Can't complete NUnit tests on Razor Views which use Url.Action

Here's my problem - I am using MvcMailer to create nicely formatted emails using Razor syntax, and it's a great tool to use for that!

The issue I'm running into is this - here's some syntax from my View for one of the emails i send:

<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, I get the following error message:

Can we send out email notifications for new comments?: System.ArgumentNullException : Value cannot be null. Parameter name: httpContext

Stacktrace - shortened for brevity, relevant sections only:

at System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext) at Mvc.Mailer.MailerBase.CreateControllerContext() at Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName) at Castle.Proxies.Invocations.MailerBase_ViewExists.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed()

The issue is that my HttpContext is null - is there a straightforward way to unit test this MvcMailer method without having to mock everything from the controller context all the way down the route results?

like image 788
Aaronontheweb Avatar asked Dec 21 '25 07:12

Aaronontheweb


2 Answers

You can take a look at the section titled Unit Test Your Mailers at the MvcMailer wiki All you need to do is, just mock out the PopulateBody method and then it will bypass the view rendering as a part of the testing. It should look something like the following:

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

Hope this helps!

like image 124
Sohan Avatar answered Dec 24 '25 07:12

Sohan


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 want to mock the other overload as well (if the above doesn't help or just to be sure):

userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<MailMessage>(), It.IsAny<string>(), It.IsAny<Dictionary<string,string>>()));
like image 33
Zar Shardan Avatar answered Dec 24 '25 07:12

Zar Shardan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!