2010-12-19 65 views
4

我有一個Action如下:我該如何測試返回PartialViewResult的MVC Action?

public PartialViewResult MyActionIWantToTest(string someParameter) 
{ 
    // ... A bunch of logic 
    return PartialView("ViewName", viewModel); 
} 

當我檢查的結果,它有幾個屬性,但它們要麼是空,或空。 有任何東西的唯一財產是ViewEngineCollection它不包含任何特定於我的方法。

有沒有人有一些示例代碼,測試PartialViewResult

回答

8

假設你有一個Action,看起來是這樣的:

public PartialViewResult MyActionIWantToTest(string someParameter) 
{ 
    var viewModel = new MyPartialViewModel { SomeValue = someParameter }; 
    return PartialView("MyPartialView", viewModel); 
} 

注:MyPartialViewModel是一個簡單的類,只有一個屬性 - SomeValue

一個NUnit的例子可能是這樣的:

[Test] 
public void MyActionIWantToTestReturnsPartialViewResult() 
{ 
    // Arrange 
    const string myTestValue = "Some value"; 
    var ctrl = new StringController(); 

    // Act 
    var result = ctrl.MyActionIWantToTest(myTestValue); 

    // Assert 
    Assert.AreEqual("MyPartialView", result.ViewName); 
    Assert.IsInstanceOf<MyPartialViewModel>(result.ViewData.Model); 
    Assert.AreEqual(myTestValue, ((MyPartialViewModel)result.ViewData.Model).SomeValue); 
} 
+0

另外MvcContrib.Testhelper有一個AssertPartialViewRendered()擴展方法。 – mxmissile 2010-12-20 21:49:16

+0

哇 - 謝謝,我不能相信我錯過了! – Robert 2010-12-21 19:53:40

1

接受的答案並沒有爲我工作。我做了以下解決我看到的測試失敗。

這是我的行動:

[Route("All")] 
    public ActionResult All() 
    { 
     return PartialView("_StatusFilter",MyAPI.Status.GetAllStatuses()); 
    } 

我不得不放棄結果的類型,以便爲它工作。我使用PartialViewResult作爲返回Partial View的操作,而不是其他操作返回完整視圖並使用View Result。這是我的測試方法:

[TestMethod] 
public void All_ShouldReturnPartialViewCalledStatusFilter() 
{ 
    // Arrange 
    var controller = new StatusController(); 
    // Act 
    var result = controller.StatusFilter() as PartialViewResult; 
    // Assert 
    Assert.AreEqual("_StatusFilter", result.ViewName, "All action on Status Filter controller did not return a partial view called _StatusFilter."); 
    } 
相關問題