c# - Asp.NET MVC 中的单元测试 ViewResult

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

尽管 StackOverflow 上有几篇关于 MVC 中的单元测试操作结果的帖子,但我有一个具体的问题....

这是我在 Controller 中的 ActionResult:

public ActionResult Index()
{
    return View(db.Products.ToList());
}

产品中的每个项目都有不同的属性,如名称、照片、数量等。 我为这个方法写了一个测试方法。它看起来如下:

private CartEntity db = new CartEntity();

[TestMethod]
public void Test_Index()
{
    //Arrange
    ProductsController prodController = new ProductsController();

    ViewResult = prodController.Index();


}

在这种情况下,我应该比较什么,因为没有参数被传递到索引操作中

最佳答案

查看 ViewResult类,这可以告诉你你还可以测试什么。 你需要做的是模拟你的 DbContext并在 Products 中提供数据属性 ( DbSet<> ),因为它在您的 Controller 的操作中被调用。 然后你可以测试

  1. 返回的类型
  2. ViewResult 上的模型
  3. 应为空或索引的 ViewName

示例代码

[TestMethod]
public void Test_Index()
{
    //Arrange
    ProductsController prodController = new ProductsController(); // you should mock your DbContext and pass that in

    // Act
    var result = prodController.Index() as ViewResult;

    // Assert
    Assert.IsNotNull(result);
    Assert.IsNotNull(result.Model); // add additional checks on the Model
    Assert.IsTrue(string.IsNullOrEmpty(result.ViewName) || result.ViewName == "Index");
}

如果您在模拟 DbContext 方面需要帮助,可以找到有关此主题的现有框架和文章。这是来自 Microsoft 的一个标题为 Testing with a mocking framework .理想情况下,您应该将依赖项(包括 DbContext 实例)注入(inject) Controller 的构造函数中使用 DI 框架的实例,如 AutoFac 或 Unity 或 NInject(不胜枚举)。这也使单元测试更加容易。

关于c# - Asp.NET MVC 中的单元测试 ViewResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897046/

相关文章:

c# - 操作数类型冲突 : varchar is incompatible

c# - 转换 DateTime 时不支持系统 - DotNetHighChart

c# - ASP.NET (MVC) session 超时 - 重置超时 - 我对此的理解是否正确?

asp.net-mvc - MVC Razor RC 1 : Can the @section be defined with a string constant?

c# - 需要在 HttpWebResponse 中访问 HttpOnly cookie

asp.net - 将 WCF 服务迁移到 ASP.NET Web API - 重用 ServiceAuthorizationManager?

asp.net - 缓存特定的 Javascript 和 CSS 文件

c# - 使用表单例份验证获取当前用户 ID(不是名称)?

c# - 使用 ASP.NET MVC 将创建和编辑 ActionResults 合并为一个

c# - 如何在 Asp.Net 中获取 Visible 属性的 set/real 值