【问题标题】:Using .Net Core 2 and Moq, how do you setup a HTTP Context to fake authentication?使用 .Net Core 2 和 Moq,如何设置 HTTP 上下文来伪造身份验证?
【发布时间】:2019-01-08 09:32:39
【问题描述】:

我正在使用 Moq 在我的 .net core 2 应用程序中进行自动化测试。我们使用不记名身份验证,需要能够从 HttpContext 对象中提取名称以确保我们拥有正确的用户:

var userName = HttpContext.User.Identity.Name;

我找到了大量使用 System.Web 的示例,但没有一个可以让我模拟 Core 2 设置。

【问题讨论】:

    标签: c# unit-testing authentication moq .net-core-2.0


    【解决方案1】:

    好的,所以在将一些旧链接(即Setting HttpContext.Current.Session in a unit test)的帮助拼凑在一起后,我能够得到这个工作,我想我会把它贴在这里以供后代使用:

    public class ContextHelper
    {
        public static HttpContext GetMockedHttpContext()
        {
            var context = new Mock<HttpContext>();
            var identity = new Mock<IIdentity>();
            var contextUser = new Mock<ClaimsPrincipal>();
            contextUser.Setup(ctx => ctx.Identity).Returns(identity.Object);
            identity.Setup(id => id.IsAuthenticated).Returns(true);
            identity.Setup(id => id.Name).Returns("validemail@test.com");
            context.Setup(x => x.User).Returns(contextUser.Object);
    
            return context.Object;
        }
    }
    

    这允许我的单元测试轻松提取我的假用户的用户名。

    我这样称呼它:

    var uc = new UserController();
    uc.ControllerContext.HttpContext = ContextHelper.GetMockedHttpContext();
    uc.WhateverMethodGoesHere();
    

    【讨论】:

      【解决方案2】:

      您无需模拟任何东西并使用框架提供的现有类即可实现相同的目标。

      public class ContextHelper {
          public static HttpContext GetHttpContext(string name = "validemail@test.com") {
              var identity = new GenericIdentity(name, "test");
              var contextUser = new ClaimsPrincipal(identity);
              var httpContext = new DefaultHttpContext() {
                  User = contextUser
              };
              return httpContext;
          }
      }
      

      仅仅因为我们有能力模拟某些事情并不意味着我们必须模拟大部分时间。

      【讨论】:

      • 我喜欢这里的清洁度。我相信,我的回答将允许您模拟 Context 对象的其他部分,但对于我的需要,这是完美的。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 2020-04-06
      • 2020-10-15
      • 1970-01-01
      • 2018-11-24
      • 2020-01-26
      • 1970-01-01
      • 2013-08-13
      相关资源
      最近更新 更多