MvcMailer: Can't complete NUnit tests on Razor

2019-02-25 07:56发布

问题:

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?

回答1:

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!



回答2:

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>>()));