单元测试ASP.NET使用伪造的Web API控制器的HttpContext [英] Unit Test ASP.NET Web API controller with fake HTTPContext

查看:218
本文介绍了单元测试ASP.NET使用伪造的Web API控制器的HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的另一个方法通过的ASP.NET Web API控制器上传文件。

I'm using the next approach to upload files through the ASP.NET Web API controllers.

[System.Web.Http.HttpPost]
public HttpResponseMessage UploadFile()
{
    HttpResponseMessage response;

    try
    {
        int id = 0;
        int? qId = null;
        if (int.TryParse(HttpContext.Current.Request.Form["id"], out id))
        {
            qId = id;
        }

        var file = HttpContext.Current.Request.Files[0];

        int filePursuitId = bl.UploadFile(qId, file);
    }
    catch (Exception ex)
    {

    }

    return response;
}

在我的单元测试我创建HttpContext类调用UploadFile行动之前手动:

In my unit tests I've created HTTPContext class manually before calling UploadFile action:

var request = new HttpRequest("", "http://localhost", "");
var context = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current = context;

response = controller.UploadFile();

不幸的是,我没能自定义值添加到Form集合,因为它是只读的。此外,我无法改变的文件集合。

Unfortunately, I wasn't able to add custom values to the Form collection, since it's read-only. Also I couldn't change Files collection.

时它自定义值添加到窗体和请求的文件属性设置为单元测试过程中添加需要的数据(ID和文件内容)的方式?

Is it any ways to add custom values to the Form and Files properties of the Request to add needed data (id and file content) during the unit test?

感谢您!

推荐答案

使用像一些模拟框架起订量代替。创建一个模拟的Htt prequestBase和模拟HttpContextBase您所需要的任何数据,并将它们设置在控制器上。

Use some mocking framework like Moq instead. Create a mock HttpRequestBase and mock HttpContextBase with whatever data you need and set them on the controller.

using Moq;
using NUnit.Framework;
using SharpTestsEx;

namespace StackOverflowExample.Moq
{
    public class MyController : Controller
    {
        public string UploadFile()
        {
            return Request.Form["id"];
        }
    }

    [TestFixture]
    public class WebApiTests
    {
        [Test]
        public void Should_return_form_data()
        {
            //arrange
            var formData = new NameValueCollection {{"id", "test"}};
            var request = new Mock<HttpRequestBase>();
            request.SetupGet(r => r.Form).Returns(formData);
            var context = new Mock<HttpContextBase>();
            context.SetupGet(c => c.Request).Returns(request.Object);

            var myController = new MyController();
            myController.ControllerContext = new ControllerContext(context.Object, new RouteData(), myController);

            //act
            var result = myController.UploadFile();

            //assert
            result.Should().Be.EqualTo(formData["id"]);
        }
    }
}

这篇关于单元测试ASP.NET使用伪造的Web API控制器的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆