2013-07-11 76 views
2

MVC单元测试我在我的单元测试项目中的代码块如下错误在控制器

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 .. 

我该如何解决这个问题?

回答

0

如果操作返回查看,将其转换为ViewResult

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

无需投它,只是改变了行动,公众的ViewResult列表(INT PARAM) – Stacked

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;