1 asp.net-mvc unit-testing viewresult
我正在尝试为 MVC 应用程序编写单元测试。我试图测试我的控制器是否返回正确的视图名称。
这是我测试的控制器操作:
public IActionResult Index(string reportcode)
{
if(string.IsNullOrEmpty(reportcode))
ReportCode = reportcode;
ViewBag.GridSource = GetReportData(reportcode);
return View("Index");
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
[Test]
public void Index_ReturnCorrectView()
{
var controller = new HomeController();
var result = controller.Index("COMD") as ViewResult;
Assert.AreEqual("Index", result.ViewName);
}
Run Code Online (Sandbox Code Playgroud)
我从单元测试中得到的错误预期为“Index”,但为空。我做了很多搜索,大多数答案都说 ViewName 属性应该在返回视图时声明它之后设置。我尝试了同样的方法,但仍然无法正常工作。
谢谢
View 类的此方法重载返回一个具有空 ViewName 属性的 ViewResult 对象。如果您正在为控制器操作编写单元测试,请考虑不采用字符串视图名称的单元测试的空 ViewName 属性。
在运行时,如果 ViewName 属性为空,则使用当前操作名称来代替 ViewName 属性。
因此,当期望视图与当前操作同名时,我们可以测试它是否是一个空字符串。
或者,Controller.View(ViewName, Model) 方法将设置 ViewName。
我的控制器方法
public ActionResult Index()
{
return View("Index");
}
Run Code Online (Sandbox Code Playgroud)
测试方法
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsTrue(result.ViewName == "Index");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1951 次 |
| 最近记录: |