Mock HttpRequest in ASP.NET C# Controller
当我们需要对如下的Index 方法写单元测试的时候,我们需要mock HttpRequest对象。
public class DefaultController : Controller
{ private IPlayer _player; public DefaultController (IPlayer player = null):base() { _player= player; } public PartialViewResult Index() { var viewModel = new PlayerViewModel(); var token = Request.Headers["token"]; if (token == null) { viewModel.ErrorMessage = "Please log in first." } else { viewModel.Player = _player.GetLoggedInPlayer(token);
}
return PartialView("Index", viewModel); }
}
通过如下方法,我们可以mock出ControllerContext。
public static ControllerContext GetControllerContext(ControllerBase controller)
{
var httpRequest = new HttpRequest("", "http://test.com", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContextMock = new HttpContext(httpRequest, httpResponse); // mock HttpContext
httpContextMock.Request.Headers["token"] = "fake_token_here";
return new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);
}
并且在写单元测试的时候,通过如下方式把mock的ControllerContext赋值给DefaultController。
_defaultController.ControllerContext = ControllerContextMocks.GetControllerContext(_defaultController);