[英]Error in MVC unit test for controller
我的單元測試項目中有一個代碼塊,如下所示
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 ..
我該如何解決?
如果操作返回視圖,則將其強制轉換為ViewResult
((ViewResult)(IEnumerable<Product>)controller.List(2)).Model
@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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.