我有一个使用 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:值不能为空。参数名称:System.Web.Mvc.AjaxRequestExtensions.IsAjaxRequest(HttpRequestBase request)处的请求
由于控制器上的 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:不可覆盖成员上的无效设置:x => x.Headers["X-Requested-With"] at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo methodInfo)
同样,似乎我无法设置请求标头。如何在 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()
。
对于使用 NSubstitute 的任何人,我都可以修改上述答案并执行类似的操作...(其中 Details 是控制器上的 Action 方法名称)
var fakeRequest = Substitute.For<HttpRequestBase>();
var fakeContext = Substitute.For<HttpContextBase>();
fakeRequest.Headers.Returns(new WebHeaderCollection { {"X-Requested-With", "XMLHttpRequest"}});
fakeContext.Request.Returns(fakeRequest);
controller.ControllerContext = new ControllerContext(fakeContext, new RouteData(), controller);
var model = new EntityTypeMaintenanceModel();
var result = controller.Details(model) as PartialViewResult;
Assert.IsNotNull(result);
Assert.AreEqual("EntityType", result.ViewName);
这是一个使用 RhinoMocks 的工作解决方案。我基于在 http://thegrayzone.co.uk/blog/2010/03/mocking-request-isajaxrequest/ 找到的 Moq 解决方案
public static void MakeAjaxRequest(this Controller controller)
{
MockRepository mocks = new MockRepository();
// Create mocks
var mockedhttpContext = mocks.DynamicMock<HttpContextBase>();
var mockedHttpRequest = mocks.DynamicMock<HttpRequestBase>();
// Set headers to pretend it's an Ajax request
SetupResult.For(mockedHttpRequest.Headers)
.Return(new WebHeaderCollection() {
{"X-Requested-With", "XMLHttpRequest"}
});
// Tell the mocked context to return the mocked request
SetupResult.For(mockedhttpContext.Request).Return(mockedHttpRequest);
mocks.ReplayAll();
// Set controllerContext
controller.ControllerContext = new ControllerContext(mockedhttpContext, new RouteData(), controller);
}
是 AjaxRequest 是一种扩展方法。因此,您可以使用 Rhino 执行以下操作:
protected HttpContextBase BuildHttpContextStub(bool isAjaxRequest)
{
var httpRequestBase = MockRepository.GenerateStub<HttpRequestBase>();
if (isAjaxRequest)
{
httpRequestBase.Stub(r => r["X-Requested-With"]).Return("XMLHttpRequest");
}
var httpContextBase = MockRepository.GenerateStub<HttpContextBase>();
httpContextBase.Stub(c => c.Request).Return(httpRequestBase);
return httpContextBase;
}
// Build controller
....
controller.ControllerContext = new ControllerContext(BuildHttpContextStub(true), new RouteData(), controller);
看起来你正在寻找这个,
var requestMock = new Mock<HttpRequestBase>();
requestMock.SetupGet(rq => rq["Age"]).Returns("2001");
控制器中的用法:
public ActionResult Index()
{
var age = Request["Age"]; //This will return 2001
}
您需要模拟 HttpContextBase 并将其放入您的 ControllerContext 属性中,如下所示:
controller.ControllerContext =
new ControllerContext(mockedHttpContext, new RouteData(), controller);
在当前的 .NET (v 5) 中:
var controller = new SomeController(); // SomeController that inherits Microsoft.AspNetCore.Mvc.ControllerBase
var httpContext = new DefaultHttpContext(); // DefaultHttpContext class is part of Microsoft.AspNetCore.Http namespace
httpContext.Request.Headers.Add("origin", "0.0.0.1"); // Add your custom headers to request
controller.ControllerContext.HttpContext = httpContext;
Microsoft.AspNetCore.Mvc.Core
3.1
要使 IsAjaxRequest()
在单元测试期间返回 false,您需要在测试方法中设置请求标头以及请求集合值,如下所示:
_request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection { { "X-Requested-With", "NotAjaxRequest" } });
_request.SetupGet(x=>x["X-Requested-With"]).Returns("NotAjaxRequest");
设置两者的原因隐藏在 IsAjaxRequest() 的实现中,如下所示:
public static bool IsAjaxRequest(this HttpRequestBase request)<br/>
{
if (request == null)
{
throw new ArgumentNullException("request");
}
return ((request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest")));
}
它同时使用请求集合和标头,这就是我们需要为标头和请求集合创建设置的原因。
这将使请求在不是 ajax 请求时返回 false。要使其返回 true,您可以执行以下操作:
_httpContext.SetupGet(x => x.Request["X-Requested-With"]).Returns("XMLHttpRequest");
我找到了在 Web API 期间将 HttpRequestMessage 对象添加到您的请求中的其他方法,如下所示
[Test]
public void TestMethod()
{
var controllerContext = new HttpControllerContext();
var request = new HttpRequestMessage();
request.Headers.Add("TestHeader", "TestHeader");
controllerContext.Request = request;
_controller.ControllerContext = controllerContext;
var result = _controller.YourAPIMethod();
//Your assertion
}
(派对有点晚了,但我走了一条不同的路线,所以我想分享一下)
为了在不为 Http 类创建模拟的情况下采用纯代码/模拟方式进行测试,我实现了一个 IControllerHelper,它有一个 Initialise 方法,该方法将请求作为参数,然后公开我想要的属性,例如:
public interface IControllerHelper
{
void Initialise(HttpRequest request);
string HostAddress { get; }
}
public class ControllerHelper : IControllerHelper
{
private HttpRequest _request;
public void Initialise(HttpRequest request)
{
_request = request;
}
public string HostAddress => _request.GetUri().GetLeftPart(UriPartial.Authority);
}
然后在我的控制器中,我在方法开始时调用初始化:
_controllerHelper.Initialise(Request);
然后我的代码只依赖于可模拟的依赖项。
return Created(new Uri($"{_controllerHelper.HostName}/api/MyEndpoint/{result.id}"), result);
对于功能测试,我只需覆盖组合中的 iControllerHelper 即可。