【问题标题】:How to return mock object as a null如何将模拟对象返回为空
【发布时间】:2014-08-16 11:45:20
【问题描述】:

正如主题所说,我不知道如何在我的 MVC 测试项目中将模拟对象返回为 null。我是单元测试的新手。

我有一个动作:

[HttpPost]
public ActionResult Edit(ClubToAddVM  clubToAddVm, HttpPostedFileBase imageFile)
{
    if (ModelState.IsValid)
    {
        if (imageFile!=null)
        {
            clubToAddVm.ImageMimeType = imageFile.ContentType;
            clubToAddVm.ImageData = new byte[imageFile.ContentLength];
            imageFile.InputStream.Read(clubToAddVm.ImageData, 0, imageFile.ContentLength);
        }
    }
    ...
}

我希望在我的测试中将 imageFile 对象作为 null 传递。不幸的是,我无法创建 HttpPostedFileBase 抽象类的实例,我想尝试这样的事情:

var mockImageFile = new Mock<HttpPostedFileBase>();

但是我不知道如何使它为空,因为 mockImageFile.Object 是只读的。 有任何想法吗?

【问题讨论】:

  • 直接设置你的对象为null,不需要mock。

标签: c# asp.net-mvc unit-testing moq httppostedfilebase


【解决方案1】:

如果你想创建null,你不必创建实例,只需这样做:

HttpPostedFileBase imageFile = null;

它是一个抽象类确实意味着您不能创建它的实例,但是声明该类型的变量并将其设置为null 是完全可以的。

【讨论】:

  • 我很惭愧。很明显。我一头雾水。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多