我在使用ASP.Net MVC框架的C#中有一个控制器
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);
但是我不断收到此错误:
异常System.ArgumentNullException:System.ArgumentNullException:值不能为null。参数名称:System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest上的请求(HttpRequestBase请求)
由于Request
控制器上的对象没有设置程序。我尝试通过使用以下答案中的推荐代码来使此测试正常运行。
这使用的是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);
但出现以下错误:
异常System.ArgumentException:System.ArgumentException:在不可重写成员上的无效设置:Moq.Mock.ThrowIfCantOverride(表达式设置,MethodInfo methodInfo)上的x => x.Headers [“ X-Requested-With”]
同样,似乎我无法设置请求标头。如何在RhinoMocks或Moq中设置此值?