控制器的MVC单元测试出错

时间:2013-07-11 14:41:15

标签: asp.net-mvc unit-testing

我的单元测试项目中有一个代码块,如下所示

IEnumerable<Product> result = (IEnumerable<Product>)controller.List(2).Model;

它产生错误

Error   1   'System.Web.Mvc.ActionResult' does not contain a definition for 'Model' and no extension method 'Model' accepting a first argument of type 'System.Web.Mvc.ActionResult' could be found ..

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果操作返回视图,请将其强制转换为ViewResult

((ViewResult)(IEnumerable<Product>)controller.List(2)).Model

答案 1 :(得分:0)

@archil的答案将在运行时抛出异常:

Unable to cast object of type 'System.Web.Mvc.ViewResult' to type 'System.Collections.Generic.IEnumerable`1[Product]'.

正确的演员是:

IEnumerable<Product> result = (IEnumerable<Product>)((ViewResult)controller.List(2)).Model;

或者简单地说,将操作的返回类型更改为ViewResult而不是ActionResult

public ViewResult List(int param)

在单元测试中使用:

IEnumerable<Product> result = (IEnumerable<Product>)controller.List(2).Model;