我正在尝试模拟我的 MailController
_mockMailController = new Mock<IMailController>();
_mockMailController.Setup(x => x.ForgotPassword("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deaabbadaa9ebbb3bfb7b2f0bdb1b3" rel="noreferrer noopener nofollow">[email protected]</a>"));
我的 Controller 将 IMailController
作为依赖项,但是当我调用时
mailController.ForgotPassword("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b2a3b5b286a3aba7afaae8a5a9ab" rel="noreferrer noopener nofollow">[email protected]</a>").Deliver();
我收到 NullReferenceException(我猜是因为 ForgotPassword
没有返回任何内容)
理想情况下,我们会 stub EmailResult
?
最佳答案
我为 ActionMailer.Net 创建了一个拉取请求,该请求引入了 IEmailResult 接口(interface),使模拟变得非常容易。看看这个:
https://bitbucket.org/swaj/actionmailer.net/pull-request/4/iemailresult-interface-for-better/
在合并拉取请求之前,您可以使用我项目中的自定义构建。
https://bitbucket.org/hydr/xv-actionmailer.net
模拟 get 就像写作一样简单(使用 FakeItEasy,Moq 可能类似):
//SetUp
_myMailer = A.Fake<IMyMailer>();
//Later on in Assert
A.CallTo(() => _myMailer.MyTestEmail()).MustHaveHappened(Repeated.Exactly.Once);
当 Mailer 定义如下时:
public class MailController : MailerBase, IMyMailer
{
public IEmailResult MyTestEmail()
{
To.Add("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f5e2e4eef7eee2e9f3c7f4e3e1a9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>");
From = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6211070c060710221106044c010d0f" rel="noreferrer noopener nofollow">[email protected]</a>";
Subject = "Subject";
return Email();
}
}
关于tdd - 使用 Moq 使用 ActionMailer.net 模拟 MailController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16348886/