简体   繁体   English

控制器的MVC单元测试中的错误

[英]Error in MVC unit test for controller

I have a code block in my unit test project as below 我的单元测试项目中有一个代码块,如下所示

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

it produce error 它产生错误

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

How can I solve this? 我该如何解决?

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

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

The answer of @archil will throw an exception at run time: @archil的答案将在运行时引发异常:

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

The correct cast is: 正确的演员表是:

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

Or simply, change the return type of the action to a ViewResult instead of an ActionResult : 或者简单地,将操作的返回类型更改为ViewResult而不是ActionResult

public ViewResult List(int param)

And in the unit test use: 并在单元测试中使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM