我正在使用新的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;
}
第一个问题是这一行:
var provider = new MultipartFormDataStreamProvider(root);
首先,要对该代码进行单元测试,我需要能够注入(inject)这样的提供程序。在那个简单的构造函数调用中,它做得太多,以致于无法“在线更新”它。还有另一种方式。 (否则,WebAPI失败)
最佳答案
我提取了一个提供程序包装器,以便可以模拟那些运动部件,例如
public interface IMultiPartFormDataStreamProviderWrapper : IDependency
{
string LocalFileName { get; }
MultipartFormDataStreamProvider Provider { get; }
}
public class MultiPartFormDataStreamProviderWrapper : IMultiPartFormDataStreamProviderWrapper
{
public const string UploadPath = "~/Media/Default/Vocabulary/";
private MultipartFormDataStreamProvider provider;
public MultiPartFormDataStreamProviderWrapper(IHttpContextAccessor httpContextAccessor)
{
provider = new CustomMultipartFormDataStreamProvider(httpContextAccessor.Current().Server.MapPath(UploadPath));
}
public string LocalFileName
{
get { return provider.FileData[0].LocalFileName; }
}
public MultipartFormDataStreamProvider Provider
{
get { return provider; }
}
}
所以我可以做类似的事情
if (Request.Content.IsMimeMultipartContent())
{
return Request.Content.ReadAsMultipartAsync(provider.Provider).ContinueWith(t =>
{
if (t.IsCanceled || t.IsFaulted)
return (object)new { success = false };
不理想,但可以放心一些。你怎么认为?
关于c# - 是否存在将文件上传到ASP.NET WebAPI的可单元测试的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12064653/