gpt4 book ai didi

c# - 为单元测试创​​建 HttpPostedFileBase 实例

转载 作者:可可西里 更新时间:2023-11-01 08:58:09 25 4
gpt4 key购买 nike

我需要创建一个 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);
}

最佳答案

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

关于c# - 为单元测试创​​建 HttpPostedFileBase 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com