如何单元测试返回ContentResult类型一个ActionResult? [英] How to unit test an ActionResult that returns a ContentResult?
本文介绍了如何单元测试返回ContentResult类型一个ActionResult?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想单元测试下面的ASP.NET MVC控制器Index操作。我怎么替换下断言的实际参数(与存根?)。
使用System.Web.Mvc;
命名空间MvcApplication1.Controllers
{
公共StatusController类:控制器
{
公众的ActionResult指数()
{
返回内容(的Hello World!);
}
}
}
[测试方法]
公共无效TestMethod1()
{
//安排
VAR控制器= CreateStatusController(); //法案
VAR的结果= controller.Index(); //断言
Assert.AreEqual(的Hello World!,?);
}
解决方案
使用为运营商做一个为空的演员。然后,只需检查空结果
[TestMethod的]
公共无效TestMethod1()
{
//安排
VAR控制器= CreateStatusController(); //法案
VAR的结果= controller.Index()作为ContentResult类型; //断言
Assert.NotNull(结果);
Assert.AreEqual(的Hello World!,result.Content);
}
I want to unit test the following ASP.NET MVC controller Index action. What do I replace the actual parameter in the assert below (stubbed with ?).
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class StatusController : Controller
{
public ActionResult Index()
{
return Content("Hello World!");
}
}
}
[TestMethod]
public void TestMethod1()
{
// Arrange
var controller = CreateStatusController();
// Act
var result = controller.Index();
// Assert
Assert.AreEqual( "Hello World!.", ? );
}
解决方案
use the "as" operator to make a nullable cast. Then simply check for a null result
[TestMethod]
public void TestMethod1()
{
// Arrange
var controller = CreateStatusController();
// Act
var result = controller.Index() as ContentResult;
// Assert
Assert.NotNull(result);
Assert.AreEqual( "Hello World!.", result.Content);
}
这篇关于如何单元测试返回ContentResult类型一个ActionResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文