ASP.NET MVC单元测试Controller时添加上下文的方式

在ASP.NET MVC中测试Controller时,常常需要在Controller中访问上下文,比方说查询字符串或者form中的内容,而我们测试的时候一般不是在web运行环境下的,所以我们需要做些工作去模拟上下文。

Controller中代码如下

  
    
public ActionResult Index()
{
ViewData[
" Message " ] = Request.QueryString[ " lfm " ];

return View();
}

测试写法如下:

代码
   
     
[TestMethod]
public void Index()
{
HomeController controller
= new HomeController();

var httpContext
= new Mock < HttpContextBase > ();
var request
= new Mock < HttpRequestBase > ();
NameValueCollection queryString
= new NameValueCollection();
queryString.Add(
" lfm " , " lfm " );
request.Setup(r
=> r.QueryString).Returns(queryString);
httpContext.Setup(ht
=> ht.Request).Returns(request.Object);

ControllerContext controllerContext
= new ControllerContext();
controllerContext.HttpContext
= httpContext.Object;
controller.ControllerContext
= controllerContext;

ViewResult result
= controller.Index() as ViewResult;

ViewDataDictionary viewData
= result.ViewData;
Assert.AreEqual(
" lfm " , viewData[ " Message " ]);
}

这里用到了Mock可以参考:

MoQ(基于.net3.5,c#3.0的mock框架)简单介绍

如果是form稍作修改即可:

  
    
public ActionResult About()
{
ViewData[
" Message " ] = Request.Form[ " lfm " ];
return View();
}

测试代码:

代码
   
     
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
var httpContext
= new Mock < HttpContextBase > ();
var request
= new Mock < HttpRequestBase > ();
NameValueCollection queryString
= new NameValueCollection();
queryString.Add(
" lfm " , " lfm " );
request.Setup(r
=> r.Form).Returns(queryString);
httpContext.Setup(ht
=> ht.Request).Returns(request.Object);

ControllerContext controllerContext
= new ControllerContext();
controllerContext.HttpContext
= httpContext.Object;
controller.ControllerContext
= controllerContext;
// Act
ViewResult result = controller.About() as ViewResult;

// Assert
ViewDataDictionary viewData = result.ViewData;
Assert.AreEqual(
" lfm " , viewData[ " Message " ]);
}

你可能感兴趣的:(controller)