How to construct HttpPostedFileBase?

我与影子孤独终老i 提交于 2019-12-12 10:55:49

问题


I have to write a Unit test for this method but I am unable to construct HttpPostedFileBase... When I run the method from the browser, it works well but I really need an autoamted unit test for that. So my question is: how do I construct HttpPosterFileBase in order to pass a file to HttpPostedFileBase.

Thanks.

    public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files)
    {
        foreach (var file in files)
        {
           // ...
        }
    }

回答1:


How about doing something like this:

public class MockHttpPostedFileBase : HttpPostedFileBase
{
    public MockHttpPostedFileBase()
    {

    }
}

then you can create a new one:

MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase();



回答2:


In my case, I use core registration core via asp.net MVC web interface and via RPC webservice and via unittest. In this case, it is useful define custom wrapper for HttpPostedFileBase:

public class HttpPostedFileStreamWrapper : HttpPostedFileBase
{
    string _contentType;
    string _filename;
    Stream _inputStream;

    public HttpPostedFileStreamWrapper(Stream inputStream, string contentType = null, string filename = null)
    {
        _inputStream = inputStream;
        _contentType = contentType;
        _filename = filename;
    }

    public override int ContentLength { get { return (int)_inputStream.Length; } }

    public override string ContentType { get { return _contentType; } }

    /// <summary>
    ///  Summary:
    ///     Gets the fully qualified name of the file on the client.
    ///  Returns:
    ///      The name of the file on the client, which includes the directory path. 
    /// </summary>     
    public override string FileName { get { return _filename; } }

    public override Stream InputStream { get { return _inputStream; } }


    public override void SaveAs(string filename)
    {
        using (var stream = File.OpenWrite(filename))
        {
            InputStream.CopyTo(stream);
        }
    }


来源:https://stackoverflow.com/questions/3428276/how-to-construct-httppostedfilebase

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