我似乎无法使用Moq来模拟HttpContext.Request.Url.Authority
,因为它是一种非虚拟方法。我得到以下异常:
{"Invalid setup on a non-virtual (overridable in VB) member: p => p.HttpContext.Request.Url.Authority"}
我该如何克服呢?以下是我的测试方法:
[TestMethod]
public void ForgottenPasswordPost_Requested_CaptchaCorrectEmailExists()
{
_testModel.ControllerContext.SetupGet(p => p.HttpContext.Session["Captcha"]).Returns("HelloWorld");
_testModel.ControllerContext.SetupGet(p => p.HttpContext.Request.Url.Authority).Returns("www.localhost.com");
_testModel.QMember.Setup(m => m.MemberExistsWithEmail(It.IsAny<string>())).Returns(true);
var controllerUnderTest = _testModel.ReturnController();
ForgottenPasswordModel model = new ForgottenPasswordModel() { Captcha = "HelloWorld" };
//Act
var actionResult = (RedirectToRouteResult)controllerUnderTest.ForgottenPassword(model);
Assert.AreEqual("ForgottenPasswordConfirm", actionResult.RouteValues["action"]);
Assert.AreEqual("a", actionResult.RouteValues["controller"]);
}
public class TestModel
{
public UnregisteredController Controller { get; set; }
public Mock<ControllerContext> ControllerContext { get; set; }
public Mock<IQ_Member> QMember { get; set; }
public TestModel()
{
ControllerContext = new Mock<ControllerContext>();
QMember = new Mock<IQ_Member>();
}
public UnregisteredController ReturnController()
{
Controller = new UnregisteredController(QMember.Object);
Controller.ControllerContext = ControllerContext.Object;
return Controller;
}
}