2010-12-19 71 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."); 
    } 
相关问题