为什么我要对该控制器的操作进行单元测试?
我有一个 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);
}
如果我要对这个操作进行单元测试,目的到底是什么? 确保打开正确的视图?
I have a ArticleController that displays a list of articles according to a category.
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);
}
If I was to unit test this action, what exactly would be the purpose?
TO make sure the correct view is being opened?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
MyStronglyTypedViewData
此行
DBFactoryfactory = new DBFactory( );
让我觉得编写单元测试会很困难,因为您不使用可以模拟的接口,而是依赖于可能会影响实际数据库的具体类。MyStronglyTypedViewData
This line
DBFactory factory = new DBFactory();
makes me think that it would be difficult to write a unit test because you don't use an interface that could be mocked, but rather rely on a concrete class which might hit the actual database.还要考虑错误情况:
categoryname
是来自网络的字符串。如果用户传递了一个“坏”的操作,该操作应该如何表现?在我看来,您可能会遇到空引用错误?测试错误案例与测试功能案例同样重要。
Consider also error cases:
categoryname
is a string from the web. How should the action behave if the user passed a "bad" one? Looks to me like you might get a null reference error?It's as important to test error cases as functional cases.
测试
categoryDao.GetByName(categoryname);
和articleDao.GetByCategoryId(vd.Category.Id);
返回的对象中的各种边缘情况,测试它们抛出异常时会发生什么情况,如果您认为如果遵循依赖倒置原则 (我只是说“如果”;您是否应该相信这是一个单独的问题),然后尝试为您的方法编写一个隔离良好的单元测试并打破依赖关系可能是一个有用的练习,可以改进设计你的程序的。
Test various edge cases in the objects returned by
categoryDao.GetByName(categoryname);
andarticleDao.GetByCategoryId(vd.Category.Id);
Test what happens when they throw exceptionsAlso, if you believe your design could be better if it adhered to the Dependency Inversion Principle (I'm just saying "if"; whether you should believe that is a separate question), then trying to write a well-isolated unit test for your method and to break the dependencies could be a useful exercise leading to an improved design of your program.
这就是我们团队得出的结论,即每个控制器必须验证(我们使用 BDD):
This is what our team concluded as what must be verified (we use BDD) for each controller: