/// <summary>
/// 单元测试控制器基类。
/// </summary>
public class UnitTestBaseController : Controller
{
public UnitTestBaseController()
{
var httpContext = new Moq.Mock<HttpContextBase>();
var response = new Moq.Mock<HttpResponseBase>();
httpContext.Setup(ht => ht.Response).Returns(response.Object);
var request = new Moq.Mock<HttpRequestBase>();
var queryString = new System.Collections.Specialized.NameValueCollection();
request.Setup(r => r.QueryString).Returns(queryString);
var httpCookieCollection = new HttpCookieCollection();
httpCookieCollection.Add(new HttpCookie("token", "124"));
request.Setup(r => r.Cookies).Returns(httpCookieCollection);
httpContext.Setup(ht => ht.Request).Returns(request.Object);
var ctrlContext = new ControllerContext();
ctrlContext.HttpContext = httpContext.Object;
this.ControllerContext = ctrlContext;
//在这里执行了过滤器功能
this.OnActionExecuting(new ActionExecutingContext());
}
protected override void OnActionExecuting(ActionExecutingContext context)
{
//throw new Exception("过滤器说有问题,哈哈!");
}
}
public class TestController : UnitTestBaseController
{
public TestController()
{
}
public void Index()
{
var token = Request.Cookies["token"];
if (token != null)
{
Response.Write("已登录:" + token.Value);
Console.WriteLine("已登录:" + token.Value);
}
else
{
Response.Write("未登录!");
Console.WriteLine("未登录!");
}
}
}
转载于:https://www.cnblogs.com/ToughGuy/p/5457855.html