Is there a unit-testable way to upload files to ASP.NET WebAPI?

99封情书 提交于 2019-12-04 22:51:56

I abstracted out a provider wrapper so I could mock those moving parts, something like

    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; }
        }
    }

So I could then do something like

    if (Request.Content.IsMimeMultipartContent())
    {
        return Request.Content.ReadAsMultipartAsync(provider.Provider).ContinueWith(t => 
                    {
                        if (t.IsCanceled || t.IsFaulted)
                            return (object)new { success = false };

Not ideal, but gives some piece of mind. What do you think?

If you use the self-hosting capability, you can write a unit test that:

  • Starts up the controllers (and various other formatters/filters/etc.)
  • Uses an HttpClient (or personally, I would use RestSharp) to submit a file to that controller (with RestSharp, you can use the AddFile function to do this)
  • Validates the input stream however you would like (e.g. by overriding the provider or just inspecting the value that is passed to a test controller or something)

If you haven't thrown in the towel on Web API yet, you might try System.Net.Http.TestableMultipartStreamProviders, which are a drop-in rewrite of the Microsoft stream providers. Their benefit is that they rely on SystemWrapper for file operations, which means the file operations can be mocked in unit tests. The wiki gives some ideas about leveraging DI to make testing controllers less of a pain.

The answer is "no". ASP.NET is an inheritance-based framework. If you're trying to write composition-based applications, you will, at some point, find friction and road-blocks. Time to switch to something like Nancy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!