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

时间秒杀一切 提交于 2019-12-04 04:29:26

问题


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


来源:https://stackoverflow.com/questions/5575964/mvcmailer-cant-complete-nunit-tests-on-razor-views-which-use-url-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!