创建一个用于单元测试的HttpPostedFileBase实例

17

我需要创建一个 HttpPostedFileBase 类的实例对象并将其传递给一个方法,但是我找不到任何实例化它的方法。我正在创建一个测试用例来测试我的文件上传方法。

这是我的方法,它接受一个 HttpPostedFileBase 对象。我需要从我的测试用例类中调用它。我没有使用任何模拟库。

有简单的方法可以做到这一点吗?

[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);
}
2个回答

27

HttpPostedFileBase 是一个抽象类,因此它不能直接实例化。

创建一个从 HttpPostedFileBase 派生的类,并返回您要查找的值。

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

我想认可这个答案(我知道这是一个旧帖子,但仍然 - 我在搜索)。这对于模拟HttpPostedFileBase非常有效。在下面添加我的2分钱 - 我正在寻找一种测试文件长度的方法。 - rwcorbett

3

我认为@BenjaminPaul的回答是最好的,但是如果还有其他人想测试MyTestPostedFileBase对象的内容长度,我想补充一下。

我按照上面的说明创建了这个类,然后传递一个流,该流填充了随机字节-这样可以使`MyTestPostedFileBase.ContentLength返回我所需的可测试值。

byte[] byteBuffer = new Byte[10];
Random rnd = new Random();
rnd.NextBytes(byteBuffer);
System.IO.MemoryStream testStream = new System.IO.MemoryStream(byteBuffer);

然后实例化它:

var TestImageFile = new MyTestPostedFileBase(testStream, "test/content", "test-file.png");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接