模拟会话不适用于Controller操作的单元测试

时间:2017-03-04 18:32:52

标签: asp.net-mvc nunit moq

我创建了一个示例ASP.NET MVC应用程序.Visual Studio提供的默认应用程序。

我创建了名为Utilities的文件夹,并放置了以下4个类

  1. 连接
  2. ConnectionRepository
  3. 安全管理器
  4. SessionManger
  5. 以下是上述类的代码

    public class Connection
        {
            public string ConnectionString { get; set; }
            public Connection(string connectionStr)
            {
                this.ConnectionString = connectionStr;
            }
            public User GetUser(string userId)
            {
                return new User() { UserId="User1",Email="User1@company.com" };
            }
    
        }
    
    ******
    
    
    using LegacyHttpContext = System.Web.HttpContext;
    
    namespace SampleNunitApplication.Utilities
    {
        public class ConnectionRepository
        {
            public Connection ConnectionData
            {
                get
                {
                    Connection con;
                    if(Convert.ToBoolean(LegacyHttpContext.Current.Application["isSourceOffline"].ToString()))
                    {
                        con = this.RefreshConfigDataFromAppServer();
                    }
                    else
                    {
                        con = this.RefreshConfigDataFromDB();
                    }
                    return con;
                }
            }
    
            public Connection RefreshConfigDataFromDB()
            {
                Connection dbConnection = new Utilities.Connection("DataFromSqlServer");            
                LegacyHttpContext.Current.Application["_connData"] = dbConnection;
                return dbConnection;
            }
            public Connection RefreshConfigDataFromAppServer()
            {
                Connection appConnection = new Utilities.Connection("DataFromAppServer");           
                LegacyHttpContext.Current.Application["_connData"] = appConnection;
                return appConnection;
            }
    
        }
    }
    
    *******
    
    
    using LegacyHttpContext = System.Web.HttpContext;
    
    namespace SampleNunitApplication.Utilities
    {
        public class SecurityManager
        {
            public static SecurityManager GetFromCache()
            {           
                if(LegacyHttpContext.Current.Application["SecurityManager"]==null)
                {
                    SecurityManager securityManager = new SecurityManager();
                    LegacyHttpContext.Current.Application["SecurityManager"] = securityManager;
                    return securityManager;
                }
                else
                {
                    return LegacyHttpContext.Current.Application["SecurityManager"] as SecurityManager;
                }
    
            }
    
            public User GetAuthenticatedUser(string userId)
            {
                ConnectionRepository connRepository = new ConnectionRepository();
                Connection con = connRepository.ConnectionData;
                return con.GetUser(userId);
    
            }
        }
    }
    
    *****
    
    public class SessionManager
        {
            public string EmployeeId { get; set; }
    
            public string Email { get; set; }
    
            public static void SaveToSessionState(HttpSessionStateBase state,SessionManager sessionManager)
            {
                state["SessionManager"] = sessionManager;
            }
    
            public static SessionManager LoadFromSessionState(HttpSessionStateBase state)
            {
                if (state["SessionManager"] ==null)
                {
                    return new SessionManager();
                }
                return state["SessionManager"] as SessionManager;
            }
    
        }
    
    ****In the HomeController.cs***
    
     public ActionResult Index()
            {           
                SessionManager authenticateUser = SessionManager.LoadFromSessionState(this.HttpContext.Session);
                ValidationModel.Validate(authenticateUser.EmployeeId, this.HttpContext);           
                SessionManager.LoadFromSessionState(this.HttpContext.Session);
                return View();
            }
    
    *******************In the Global.asax***
    
     protected void Session_Start()
            {
                HttpSessionStateWrapper sessionWrapper = new HttpSessionStateWrapper(System.Web.HttpContext.Current.Session);
                System.Web.HttpContext.Current.Application["isSourceOffline"] = false;
                SessionManager authenticateUser = SessionManager.LoadFromSessionState(sessionWrapper);
                User user = SecurityManager.GetFromCache().GetAuthenticatedUser("User1");
                authenticateUser.EmployeeId = user.UserId;
                authenticateUser.Email = user.Email;
                SessionManager.SaveToSessionState(sessionWrapper, authenticateUser);
            }
    
    ******
    
    I created a class library project and created below mock code
    
    
     [TestClass]    public class UnitTest1
    
        {
            [TestMethod]
            public void TestMethod1()
            {
                var application = new Mock<HttpApplicationStateBase>();
                SecurityManager securityManager = new SecurityManager();
                application.SetupGet(s => s["isSourceOffline"]).Returns(true);
                application.SetupGet(s => s["SecurityManager"]).Returns(securityManager);           
                var context = new Mock<HttpContextBase>();
                var request = new Mock<HttpRequestBase>();
                var response = new Mock<HttpResponseBase>();
                var session = new Mock<HttpSessionStateBase>();
                var server = new Mock<HttpServerUtilityBase>();
                session.Setup(s => s.SessionID).Returns(Guid.NewGuid().ToString());
                context.Setup(c => c.Request).Returns(request.Object);
                context.Setup(c => c.Response).Returns(response.Object);
                context.Setup(c => c.Session).Returns(session.Object);
                context.Setup(c => c.Application).Returns(application.Object);
                context.Setup(c => c.Server).Returns(server.Object);
    
                SessionManager authenticatedUser = new SessionManager();
                authenticatedUser.EmployeeId = "TestUser";
                authenticatedUser.Email = "Test@testmail.com";
                SessionManager.SaveToSessionState(context.Object.Session, authenticatedUser);
                HomeController objController = new HomeController();
                objController.ControllerContext = new System.Web.Mvc.ControllerContext(context.Object, new RouteData(), objController);
                objController.Index();
    
            }
        }
    

    如果我运行ASP.NET MVC应用程序,它运行良好。但是当我运行测试用例时,它会命中HomeController的Index方法,但SessionManager authenticateUser = SessionManager.LoadFromSessionState(this.HttpContext.Session);不会从会话中填充。 authenticateUser中的属性为null。

    似乎模拟会话无法正常工作请帮助

0 个答案:

没有答案