Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct HttpPostedFileBase?

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)
        {
           // ...
        }
    }
like image 863
Martin Avatar asked Aug 06 '10 22:08

Martin


2 Answers

How about doing something like this:

public class MockHttpPostedFileBase : HttpPostedFileBase
{
    public MockHttpPostedFileBase()
    {

    }
}

then you can create a new one:

MockHttpPostedFileBase mockFile = new MockHttpPostedFileBase();
like image 142
Yngve B-Nilsen Avatar answered Sep 22 '22 13:09

Yngve B-Nilsen


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);
        }
    }
like image 40
Tomas Kubes Avatar answered Sep 22 '22 13:09

Tomas Kubes