如何将 HttpRequest 接收到 MVC 3 控制器操作中?

Sea*_*ean 6 c# asp.net unit-testing c#-4.0 asp.net-mvc-3

目前的解决方案

所以我有一些非常相似的东西

[HttpPost]
    public ActionResult Upload()
    {
        var length = Request.ContentLength;
        var bytes = new byte[length];

        if (Request.Files != null )
        {
            if (Request.Files.Count > 0)
            {
                var successJson1 = new {success = true};
                return Json(successJson1, "text/html");
            }
        }
...
        return Json(successJson2,"text/html");
    }
Run Code Online (Sandbox Code Playgroud)

可单元测试的解决方案?

我想要这样的东西:

[HttpPost]
public ActionResult Upload(HttpRequestBase request)
{
    var length = request.ContentLength;
    var bytes = new byte[length];

    if (request.Files != null )
    {
        if (request.Files.Count > 0)
        {
            var successJson1 = new {success = true};
            return Json(successJson1);
        }
    }

    return Json(failJson1);
}
Run Code Online (Sandbox Code Playgroud)

然而这失败了,这很烦人,因为我可以从基类中进行模拟并使用它。

笔记

  • 我知道这不是解析表单/上传的好方法,并且想说这里发生了其他事情(即此上传可以是表单或 xmlhttprequest - 该操作不知道是哪一个)。
  • 使“请求”单元可测试的其他方法也很棒。

Dar*_*rov 7

您的控制器上已经有一个Request属性 => 您不需要将其作为操作参数传递。

[HttpPost]
public ActionResult Upload()
{
    var length = Request.ContentLength;
    var bytes = new byte[length];

    if (Request.Files != null)
    {
        if (Request.Files.Count > 0)
        {
            var successJson1 = new { success = true };
            return Json(successJson1);
        }
    }

    return Json(failJson1);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在单元测试中模拟Request,更具体地说是具有 Request 属性的 HttpContext:

// arrange
var sut = new SomeController();
HttpContextBase httpContextMock = ... mock the HttpContext and more specifically the Request property which is used in the controller action
ControllerContext controllerContext = new ControllerContext(httpContextMock, new RouteData(), sut);
sut.ControllerContext = controllerContext;

// act
var actual = sut.Upload();

// assert
... assert that actual is JsonResult and that it contains the expected Data
Run Code Online (Sandbox Code Playgroud)