gpt4 book ai didi

asp.net-mvc-3 - 当我对我的操作进行单元测试时,为什么 Controller.Url 为空?

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

我关注了this answer模拟 HttpContext、Request、Response 和 User 并设置 Controller.ControllerContextController.Url

在调用 controller.Index() 之前,

Controller.Url 绝对不为 null。但是,在 controller.Index() 内部,它为 null。看起来很奇怪。我错过了什么?

这是我的测试装置:

[TestFixture]
public class ControllerFixtureBase
{
private Mock<HttpContextBase> _httpContextMock;
private RouteCollection _routes;

[SetUp]
public void SetUp()
{
var requestMock = new Mock<HttpRequestBase>();
requestMock.SetupGet(x => x.ApplicationPath)
.Returns("/");
requestMock.SetupGet(x => x.Url)
.Returns(new Uri("http://localhost/a", UriKind.Absolute));
requestMock.SetupGet(x => x.ServerVariables)
.Returns(new NameValueCollection());

var responseMock = new Mock<HttpResponseBase>();
responseMock.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
.Returns((string url) => url);

var principalMock = new Mock<IPrincipal>();
principalMock.SetupGet(p => p.Identity)
.Returns(new GenericIdentity("testuser"));
principalMock.Setup(p => p.IsInRole(ApplicationRoles.DataAdmin))
.Returns(false);

_httpContextMock = new Mock<HttpContextBase>();
_httpContextMock.Setup(x => x.User)
.Returns(principalMock.Object);
_httpContextMock.Setup(x => x.Request)
.Returns(requestMock.Object);
_httpContextMock.SetupGet(x => x.Response)
.Returns(responseMock.Object);

_routes = new RouteCollection();
MvcApplication.RegisterRoutes(_routes);
}

protected void PrepareController(Controller controller)
{
var requestContext = new RequestContext(_httpContextMock.Object, new RouteData());

controller.ControllerContext = new ControllerContext(requestContext, controller);
controller.Url = new UrlHelper(requestContext, _routes);
}

[Test]
public void Index()
{
HomeController controller = new HomeController();
PrepareController(controller);

Assert.That(controller.Url, Is.Not.Null);
Assert.That(controller.ViewBag, Is.Not.Null);

ViewResult viewResult = controller.Index() as ViewResult;

Assert.That(viewResult, Is.Not.Null);
Assert.That(viewResult.ViewBag.IndexUrl, Is.EqualTo("/"));
}
}

这是我非常简单的操作:

[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

// System.NullReferenceException : Object reference not set to an instance of an object.
ViewBag.IndexUrl = Url.Action("Index");

return View();
}
}

最佳答案

看来答案与 mock 无关。我的 MVC 和测试项目都是使用 MVC 4 beta 创建的。我在使用 AuthorizeAttribute 时遇到了一些奇怪的问题,因此我通过创建新项目并移动文件将项目转换为 MVC 3。

我一定有一些不匹配的引用,因为当我从两个项目中手动删除所有 MVC 和 Web 引用并重新添加它们时,测试通过了。

关于asp.net-mvc-3 - 当我对我的操作进行单元测试时,为什么 Controller.Url 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828220/

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