gpt4 book ai didi

asp.net-mvc - 单元测试 Url.Action

转载 作者:行者123 更新时间:2023-12-02 02:34:30 25 4
gpt4 key购买 nike

我正在尝试对从 DotNetOpenAuth 示例中获得的代码进行单元测试,但我很难让 UrlHelper 在我的测试中工作。

在我的 Controller 上的 LogOn ActionResult 的某处,它调用了以下 UrlHelper。以下示例是该 ActionResult 的简化版本。

public ActionResult TestUrlHelper()
{
var test = Url.ActionFull("LogOnReturnTo");
return View();
}

我的测试看起来像这样:

[Test]
public void TestTest()
{
AccountController controller = GetAccountController();
var result = controller.TestUrlHelper();
}

这是 UrlHelper 的扩展方法:

internal static Uri ActionFull(this UrlHelper urlHelper, string actionName)
{
return new Uri(urlHelper.RequestContext.HttpContext.Request.Url,
urlHelper.Action(actionName));

}

我从下面的question得到的GetAccountController方法.我尝试根据自己的需要稍微调整设置,但我不得不承认我并不完全理解。

private static AccountController GetAccountController()
{
var MockIFormsAuthentication = new Mock<IFormsAuthentication>();
var MockIOpenIdRelyingParty = new Mock<IOpenIdRelyingParty>();
var MockRealm = new Realm("http://www.google.be");

var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);

var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Account/LogOnReturnTo", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier("/Account/LogOnReturnTo")).Returns("http://localhost/Account/LogOnReturnTo");

var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);

var Controller = new AccountController(MockIFormsAuthentication.Object, MockIOpenIdRelyingParty.Object, MockRealm);
Controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), Controller);
Controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

return Controller;
}

我得到的错误是:

HttpResponseBase.ApplyAppPathModifier("/Home/LogOnReturnTo") invocation failed with mock behavior Strict.

非常感谢任何朝着正确方向的帮助或插入

最佳答案

MockBehavior.Strict

Make mock behave like a "true Mock", raising exceptions for anything that doesn't have a corresponding expectation.

(来自 Moq wiki)

因此,如果您将 MockBehavior 设置为 Loose,它:

never throws and returns default values or empty arrays, enumerables, etc. if no expectation is set for a member

关于asp.net-mvc - 单元测试 Url.Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2387155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com