【问题标题】:How to test session.clear() in Mocking unit test如何在模拟单元测试中测试 session.clear()
【发布时间】:2017-06-14 07:13:36
【问题描述】:

如何测试清除会话和注销用户的方法。

我的控制器方法看起来像

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult LogOff()
  {
    SessionAdapter.Clear();
    SessionAdapter.Abandon();         
    AuthenticationManager.SignOut
                     (DefaultAuthenticationTypes.ApplicationCookie);
    return RedirectToAction("Index", "Home");
  }

这里的会话适配器是我的静态类

public static class SessionAdapter
  {
    private static string sessionKey = "sessionInfoKey";

    public static SessionInfo Instance
    {
      get
      {
        return HttpContext.Current.Session[sessionKey] == null ? null : (SessionInfo)HttpContext.Current.Session[sessionKey];
      }
      set
      {
        HttpContext.Current.Session[sessionKey] = value;
      }
    }

    public static bool DoesSessionExists { get { return HttpContext.Current.Session[sessionKey] == null ? false : true; } }

    public static void Clear()
    {
      HttpContext.Current.Session.Clear();
    }
}

请帮帮我

【问题讨论】:

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


    【解决方案1】:

    在单元测试中,您应该模拟会话,因为它是一个外部依赖项。您的单元测试应该测试您的代码,而不是 .net 框架。

    因此,有效的测试可能是验证对 Session.Clear 的调用是否发生,而不是实际测试 Session.Clear 清除会话。

    这可以通过设置一个假会话来完成。这是我用来设置控制器上下文以进行单元测试的扩展方法

    public static void SetControllerContext(这个Controller控制器) { var fakeContext = A.Fake(); var fakeRequest = A.Fake(); var fakeResponse = A.Fake(); var fakeSessionState = A.Fake();

            A.CallTo(() => fakeRequest.HttpMethod).Returns(HttpVerbs.Post.ToString());
            A.CallTo(() => fakeContext.Response).Returns(fakeResponse);
            A.CallTo(() => fakeContext.Request).Returns(fakeRequest);
            A.CallTo(() => fakeContext.Session).Returns(fakeSessionState);
    
            var fakeRequestContext = new RequestContext(fakeContext, new RouteData());
    
            controller.ControllerContext = new ControllerContext(fakeRequestContext, controller);
        }
    

    这是使用 FakeItEasy,但同样的事情可以用 Moq 来完成。

    来自MS“ASP.NET 会话状态使您能够在用户浏览 Web 应用程序中的 ASP.NET 页面时为用户存储和检索值。”

    将其包装在静态类中的价值是什么?

    【讨论】:

      猜你喜欢
      • 2019-12-13
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2017-02-09
      • 2018-11-27
      • 1970-01-01
      相关资源
      最近更新 更多