为什么我会对这个控制器的动作进行单元测试?

mrb*_*lah 1 tdd asp.net-mvc nunit moq

我有一个ArticleController,根据类别显示文章列表.

public ActionResult List(string categoryname)
{
       MyStronglyTypedViewData vd = new MyStronglyTypedViewData();

       DBFactory factory = new DBFactory();

       categoryDao = factory.GetCategoryDao();
       articleDao = factory.GetArticleDao();


       vd.Category = categoryDao.GetByName(categoryname);
       vd.Articles = articleDao.GetByCategoryId(vd.Category.Id);


       return View(vd);
}
Run Code Online (Sandbox Code Playgroud)

如果我要对这个动作进行单元测试,究竟是什么目的呢?要确保正在打开正确的视图?

Dar*_*rov 8

  1. 确保返回ViewResult
  2. 确保视图结果具有模型
  3. 确保此模型不为null且属于类型 MyStronglyTypedViewData
  4. 断言模型上的属性

这一行DBFactory factory = new DBFactory();让我觉得编写单元测试很困难,因为你没有使用可以模拟的接口,而是依赖于可能击中实际数据库的具体类.