我在 C # 中有一个控制器,它使用的是 ASP.NET MVC Framework
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: 值 参数名称: 请求 IsAjaxRequest (HttpRequestBase) 要求)
因为控制器上的 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);
但得到以下错误:
例外: System.ArgumentException: 无效 在不可重写的成员上设置: x = > x. Header [“ X-Request-With”] at Moq. Mock. ThrowIfCantOverride (Expression MethodInfo methodInfo)
同样,看起来我不能设置请求头。 如何在 RhinoMocks 或 Moq 中设置这个值?