Creating an instance of HttpPostedFileBase for unit testing

.net, asp.net-mvc-4, c#, unit-testing

Solution

HttpPostedFileBase is an abstract class so therefore it cannot be directly instantiated.

Create a class that derives from HttpPostedFileBase and returns the values you are looking for.

    class MyTestPostedFileBase : HttpPostedFileBase
{
Stream stream;
string contentType;
string fileName;

public MyTestPostedFileBase(Stream stream, string contentType, string fileName)
{
    this.stream = stream;
    this.contentType = contentType;
    this.fileName = fileName;
}

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

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

public override string FileName
{
    get { return fileName; }
}

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

public override void SaveAs(string filename)
{
    throw new NotImplementedException();
}
}

Problem

I need to create an instance of `HttpPostedFileBase` class object and pass it to a method, but I cannot find any way to instantiate it. I am creating a test case to test my fileupload method. This is my method which takes an `HttpPostedFileBase` object. I need to call it from my test case class. I am not using any mock library. Is there a simple way to do this? ``` [HttpPost] public JsonResult AddVariation(HttpPostedFileBase file, string name, string comment, string description, decimal amount, string accountLineTypeID) { var accountLineType = _fileService.GetAccountLineType(AccountLineType.Debit); if (Guid.Parse(accountLineTypeID) == _fileService.GetAccountLineType(AccountLineType.Credit).AccountLineTypeID) { amount = 0 - amount; } var info = new File() { FileID = Guid.NewGuid(), Name = name, Description = description, FileName = file.FileName, BuildID = Guid.Parse(SelectedBuildID), MimeType = file.ContentType, CreatedUserID = CurrentUser.UserID, UpdatedUserID = CurrentUser.UserID, Amount = amount, }; var cmmnt = new Comment() { CommentDate = DateTime.Now, CommentText = comment, FileID = info.FileID, UserID = CurrentUser.UserID }; _variationService.AddVariation(info, file.InputStream); _variationService.AddComment(cmmnt); return Json("Variation Added Sucessfully", JsonRequestBehavior.AllowGet); } ```

Original source