zoukankan      html  css  js  c++  java
  • MVC Controller进行单元测试

    /// <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("未登录!");
                }
            }
        }
    

      

  • 相关阅读:
    应用图标大小
    AndroidStudio使用笔记
    shell 三剑客之 sed 命令详解
    shell 三剑客之 sed pattern 详解
    shell 文本处理三剑客之 grep 和 egrep
    Shell 编程中的常用工具
    shell 函数的高级用法
    shell 数学运算
    shell 变量的高级用法
    nginx 之 https 证书配置
  • 原文地址:https://www.cnblogs.com/ToughGuy/p/5457855.html
Copyright © 2011-2022 走看看