Asp.NET MVC中的单元测试ViewResult

suj*_*ala 9 c# asp.net asp.net-mvc unit-testing asp.net-mvc-4

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

这是我在Controller中的ActionResult:

public ActionResult Index()
{
    return View(db.Products.ToList());
}
Run Code Online (Sandbox Code Playgroud)

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

private CartEntity db = new CartEntity();

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

    ViewResult = prodController.Index();


}
Run Code Online (Sandbox Code Playgroud)

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

Igo*_*gor 11

查看ViewResult类,它可以显示您还可以测试的其他内容.您需要做的是嘲笑您DbContext并在Products属性(DbSet<>)中提供数据,因为这是在控制器的操作中调用的.然后你可以测试

  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");
}
Run Code Online (Sandbox Code Playgroud)

如果您需要帮助模拟DbContext,则有关于此主题的现有框架和文章.这是一个来自微软的名为Testing with a mocking framework的文章.理想情况下,您应该Controller使用DI框架(如AutoFac或Unity或NInject )将依赖项(包括DbContext实例)注入到实例的构造函数中(列表继续).这也使单元测试更容易.