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

标签 c# .net asp.net-mvc-4 unit-testing

我需要创建一个 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/

相关文章:

c# - C# 中的停靠面板套件不会触发 mousedown 事件

c# - 使用线程正确处理类

c# - 报告查看器显示 mysql 时间戳的 #Error

jquery - 用ajax上传图片,HttpPostedFileBase为null Mvc Asp

c# - 如何使用 C# 为 Crystal 报表动态设置数据库名称?

c# - 灯光遮天蔽日

c# - 在 Tumblr 上创建博客帖子时 OAuth 失败(不断收到 401/未授权)

c# - System.Text.Json - DefaultValueHandling = DefaultValueHandling.忽略替代方案

c# - 使用 mvc 4 中的模型根据出生日期验证年龄

c# - 在 C# 项目中使用 MediaInfo.dll