【问题标题】:How to Unit test a method using Moqs which create session如何使用创建会话的 Moq 对方法进行单元测试
【发布时间】:2023-04-04 19:51:02
【问题描述】:

如何测试在方法内部创建会话的方法。我用来做单元测试。当我使用测试用例调用方法时,它无法在方法内创建会话。谁能帮我为下面的代码创建单元测试

public ActionResult InviteUser(string Id)
    {
      if (!string.IsNullOrEmpty(Id))
      {
        Session["verification_uid"] = Id; 
        return RedirectToAction("Login", "Account"); 
      }
      return View();
    }

我也尝试过以下代码,但它不起作用

  [TestMethod]
        public void InviteUser_ExpectRedirectActionResultReturned()
        {
            //Arrange
            controller = new AccountController();

            var mockControllerContext = new Mock<ControllerContext>();
            var mockSession = new Mock<HttpSessionStateBase>();
            mockSession.SetupGet(s => s["verification_uid"]).Returns("123"); //somevalue
            mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);
            controller.ControllerContext = mockControllerContext.Object;

            var id = "1";
            System.Web.HttpContext.Current.Session["verification_uid‌​ID"] = "12";

            //Act
            var result = (RedirectToRouteResult)controller.InviteUser(id);

            //Assert
            result.RouteValues["action"].Equals("Index");
            result.RouteValues["controller"].Equals("Home");

            Assert.AreEqual("Index", result.RouteValues["action"]);
            Assert.AreEqual("Home", result.RouteValues["controller"]);
        }

【问题讨论】:

    标签: c# .net asp.net-mvc unit-testing nunit


    【解决方案1】:

    您可以将会话变量的设置放入帮助程序类中,实现一个接口,该接口可以传递到您可以在单元测试中模拟的类中。

    public MyClass 
    {
        private readonly ISessionHelper _helper;
    
        public MyClass(ISessionHelper helper)
        {
            this._helper = helper;
        }
    
        public ActionResult InviteUser(string Id)
        {
          if (!string.IsNullOrEmpty(Id))
          {
            this._helper.SetSessionVariable("verification_uid", Id);
            return RedirectToAction("Login", "Account"); 
          }
          return View();
        }
    }
    

    您的助手将包含进行设置的 SetSessionVariable。

    然后,在你的单元测试中,你模拟ISessionHelper

    【讨论】:

    • 我们可以不使用基于服务的架构,因为我们没有在应用程序中使用服务。这是一个简单的基于网络的应用程序
    • @CharanTejaKuta 我不确定您为什么认为这与服务有关。这只是将帮助器传递给类的构造函数,以便对其进行模拟。
    猜你喜欢
    • 2012-06-01
    • 2021-10-15
    • 1970-01-01
    • 2020-09-06
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多