繁体   English   中英

为单元测试创​​建HttpPostedFileBase的实例

[英]Creating an instance of HttpPostedFileBase for unit testing

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

这是我的方法,它采用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);
}

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

我认为@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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM