gpt4 book ai didi

asp.net-mvc - 如何在 ASP.Net MVC 中模拟 Controller 上的请求?

转载 作者:行者123 更新时间:2023-12-03 04:17:19 25 4
gpt4 key购买 nike

我有一个使用 ASP.Net MVC 框架的 C# Controller

public class HomeController:Controller{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//do some ajaxy stuff
}
return View("Index");
}
}

我得到了一些关于模拟的技巧,并希望使用以下代码和 RhinoMocks 来测试代码

var mocks = new MockRepository();
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);

var controller = new HomeController();
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);

但是我不断收到此错误:

Exception System.ArgumentNullException: System.ArgumentNullException : Value cannot be null. Parameter name: request at System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase request)

因为 Controller 上的Request对象没有setter。我尝试使用下面答案中推荐的代码来使此测试正常工作。

这里使用 Moq 而不是 RhinoMocks,在使用 Moq 时我使用以下内容进行相同的测试:

var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers["X-Requested-With"]).Returns("XMLHttpRequest");

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
var controller = new HomeController(Repository, LoginInfoProvider);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
var result = controller.Index() as ViewResult;
Assert.AreEqual("About", result.ViewName);

但出现以下错误:

Exception System.ArgumentException: System.ArgumentException : Invalid setup on a non-overridable member: x => x.Headers["X-Requested-With"] at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo methodInfo)

同样,我似乎无法设置请求 header 。如何在 RhinoMocks 或 Moq 中设置此值?

最佳答案

使用Moq :

var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"}
});

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

var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);

更新:

模拟 Request.Headers["X-Requested-With"]Request["X-Requested-With"] 而不是 Request.IsAjaxRequest( )

关于asp.net-mvc - 如何在 ASP.Net MVC 中模拟 Controller 上的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/970198/

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