Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

c# - Unit Test ASP.NET Web API controller with fake HTTPContext

I'm using the following approach to upload files through 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;
}

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

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

response = controller.UploadFile();

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

Is there any way 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"]);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...