但是在内容中,发现没有添加POST和GET参数的方法,不太符合我自己的需求,所以自己在helper类中又添加了一个方法
1 /// <summary>
2         /// 创建HttpContextBase
3         /// </summary>
4         /// <returns></returns>
5         public static HttpContextBase CreateHttpContext(NameValueCollection PostParameter, NameValueCollection GetParameter)
6         {
7             var context = new Mock<HttpContextBase>();
8             var request = new Mock<HttpRequestBase>();
9             var response = new Mock<HttpResponseBase>();
10             var session = new Mock<HttpSessionStateBase>();
11             var server = new Mock<HttpServerUtilityBase>();
12
13             request.Setup(u => u.QueryString).Returns(GetParameter);
14
15             request.Setup(u => u.Form).Returns(PostParameter);
16             response
17                 .Setup(rsp => rsp.ApplyAppPathModifier(Moq.It.IsAny<string>()))
18                 .Returns((string s) => s);
19
20             context.Setup(ctx => ctx.Request).Returns(request.Object);
21             context.Setup(ctx => ctx.Response).Returns(response.Object);
22             context.Setup(ctx => ctx.Session).Returns(session.Object);
23             context.Setup(ctx => ctx.Server).Returns(server.Object);
24
25             return context.Object;
26         }
  调用代码
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using BLL;
using COMMON;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using UI.Controllers;
namespace UiTest.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
try
{
var homeController = new HomeController();
NameValueCollection post = new NameValueCollection();
post.Add("Version", "10");
NameValueCollection get = new NameValueCollection();
get.Add("bbb", "222");
HttpContextBase hcb = Common.MvcContextMockFactory.CreateHttpContext(post, get);
homeController.ControllerContext = Common.MvcContextMockFactory.CreateControllerContext(homeController,
hcb,
"~/Home/Index",
"get",
"DefaultRoute",
"{controller}/{action}",
null);
ViewResult result = (ViewResult) homeController.Index();
Assert.AreEqual("Index", result.ViewName);
}
catch (Exception ex)
{
Assert.IsFalse(true, ex.Message);
}
}
}
}