是否有可单元测试的方法将文件上载到ASP.NET WebAPI?

Byr*_*ahl 17 c# tdd file-upload asp.net-web-api

我正在使用新的ASP.NET WebAPI的项目中工作.我目前的任务是接受上传的文件.到目前为止,我已经使用TDD来驱逐WebAPI代码,但我已经上传了一个墙.我目前正在遵循http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2上的建议,但似乎没有完全可以推动单元测试.为了获取文件和表单数据,我必须使用MultipartFormDataStreamProvider,这是不可能模拟和/或覆盖.如果没有放弃我的TDD方法,我该怎么办?

这是示例中的代码:

public Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    // Read the form data and return an async task.
    var task = Request.Content.ReadAsMultipartAsync(provider).
        ContinueWith<HttpResponseMessage>(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
            }

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        });

    return task;
}
Run Code Online (Sandbox Code Playgroud)

第一个问题是这一行:

var provider = new MultipartFormDataStreamProvider(root);
Run Code Online (Sandbox Code Playgroud)

对于初学者来说,要对这段代码进行单元测试,我需要能够注入这样的提供者.在那个简单的构造函数调用中,它在"新增它"中排除了太多.还有另一种方式.(如果没有,WebAPI失败)

Byr*_*ahl -2

答案是不”。ASP.NET 是一个基于继承的框架。如果您尝试编写基于组合的应用程序,那么在某些时候您会发现摩擦和障碍。是时候换成像南希这样的人了。