单元测试Url.Action

时间:2010-03-05 13:55:05

标签: asp.net-mvc moq dotnetopenauth

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

在我的控制器上的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”)调用因模拟行为严格而失败。

非常感谢任何帮助或推动正确的方向

1 个答案:

答案 0 :(得分:2)

MockBehavior.Strict

  

让模拟行为像“真正的模拟”,为任何没有相应期望的事物提出例外。

(来自de Moq wiki

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

  如果没有为成员设置期望,

永远不会抛出并返回默认值或空数组,枚举等。