2014-02-06 32 views
2

我正在寫一些單元測試,並且我有一個場景,如果條件爲真,控制器操作應返回HttpNotFoundResult,否則它應該返回ViewResult並在其中包含特定的模型。ActionResult as ViewResult返回null ..但我可以明確施放?

作爲測試之一(測試應該返回ViewResult的場景),我執行該操作,然後嘗試將結果轉換爲ViewResult。但是,當使用var result = myController.MyAction() as ViewResult(其中resultActionResult)時,result始終計算爲空......但是當我執行var result = (ViewResult)myController.MyAction()時,結果很好。

這是爲什麼?我不正確理解as的用法嗎?

相關代碼:

// My controller 
public class MyController 
{ 
    .. 
    public ActionResult MyAction(bool condition) 
    { 
     if(condition) 
     return HttpNotFound() 
     return View(new object()); 
    } 
} 

// My test 
public void MyTest() 
{ 
    .... 
    var controller = new MyController(); 
    var result = controller.MyAction(false) as ViewResult; 
    // result should be casted successfully by as, but it's not, instead it's unll 
    // however, this works 
    var result = (ViewResult) controller.MyAction(false); 
    // why is this? 
} 

編輯:與要點完整的示例。對不起,它似乎並不像語法突出顯示。 https://gist.github.com/DanPantry/dcd1d55651d220835899

+0

'as'運算符就像一個投射操作。但是,如果轉換不可行,返回'null'而不是引發異常。 – Satpal

+1

是的,但是,'ActionResult'到'ViewResult'之間的顯式轉換不會引發異常 - 事實上,它可以正常工作。那麼爲什麼'ActionResult as ViewResult'返回null? –

+0

'ViewResult'從'ActionResult'繼承,因此''應該始終能夠投射它。請您可以發佈您的*精確*代碼或您的問題的可編譯的演示(您發佈的代碼將不會編譯,所以不能這樣做)。 –

回答

2

由於沒有人回答 - 我更新了我的ASP MVC到ASP MVC 5,測試成功了。我有一個直覺,我的測試項目使用ASP MVC 5,但包含控制器的項目運行ASP MVC 4,並且因爲它們來自不同的二進制文件,控制器類可能會返回ActionResult陰影下的ViewResult,但測試項目無法從ViewResult轉換爲ActionResult,因爲它對ViewResult的理解是不同的。

雖然這看起來很愚蠢,因爲人們會認爲我會在這種情況下得到一個構建錯誤。

唉,升級固定它。

+0

我的兩個項目都使用mvc5仍在單元測試用例中得到null任何線索爲什麼? – Neo

相關問題