C# 如何对返回PartialViewResult的MVC操作进行单元测试?
我有一个C# 如何对返回PartialViewResult的MVC操作进行单元测试?,c#,model-view-controller,action,C#,Model View Controller,Action,我有一个动作,如下所示: public PartialViewResult MyActionIWantToTest(string someParameter) { // ... A bunch of logic return PartialView("ViewName", viewModel); } 当我检查结果时,它有一些属性,但它们要么为null,要么为空。 唯一具有任何内容的属性是ViewEngineCollection,它不包含任何特定于我的方法的内容 是否有人有一些
动作
,如下所示:
public PartialViewResult MyActionIWantToTest(string someParameter)
{
// ... A bunch of logic
return PartialView("ViewName", viewModel);
}
当我检查结果时,它有一些属性,但它们要么为null,要么为空。
唯一具有任何内容的属性是ViewEngineCollection
,它不包含任何特定于我的方法的内容
是否有人有一些测试
PartialViewResult
的示例代码?假设您有一个类似以下内容的操作:
public PartialViewResult MyActionIWantToTest(string someParameter)
{
var viewModel = new MyPartialViewModel { SomeValue = someParameter };
return PartialView("MyPartialView", viewModel);
}
[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);
}
注意:MyPartialViewModel
是一个只有一个属性的简单类-SomeValue
NUnit示例可能如下所示:
public PartialViewResult MyActionIWantToTest(string someParameter)
{
var viewModel = new MyPartialViewModel { SomeValue = someParameter };
return PartialView("MyPartialView", viewModel);
}
[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);
}
[测试]
public void MyActionIwantToteStraterSpartialViewResult()公共无效
{
//安排
常量字符串myTestValue=“Some value”;
var ctrl=新的StringController();
//表演
var result=ctrl.MyActionIWantToTest(myTestValue);
//断言
AreEqual(“MyPartialView”,result.ViewName);
Assert.IsInstanceOf(result.ViewData.Model);
AreEqual(myTestValue,((MyPartialViewModel)result.ViewData.Model).SomeValue);
}
被接受的答案对我不起作用。我做了以下工作来解决我看到的测试失败
这是我的行动:
[Route("All")]
public ActionResult All()
{
return PartialView("_StatusFilter",MyAPI.Status.GetAllStatuses());
}
我必须给结果一个类型,这样它才能工作。我在返回部分视图的操作中使用了PartialViewResult,而其他操作则返回完整视图并使用视图结果。这是我的测试方法:
[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.");
}
Testhelper还有一个AssertPartialViewRendered()扩展方法。