【问题标题】:How fake System.Security.Principal.IIdentity using FakeItEasy?如何使用 FakeItEasy 伪造 System.Security.Principal.IIdentity?
【发布时间】:2012-06-02 21:52:26
【问题描述】:

在我的应用中,用户通过 WIF 登录。用户的凭据存储在System.Security.Principal.IIdentity 中。现在我想测试CreateUser() 方法。 我必须以某种方式伪造那个对象。我尝试做这样的事情: -返回该对象的提取方法:

public IIdentity GetIdentity()
{
    return Thread.CurrentPrincipal.Identity;
}

然后在测试文件中做这样的事情:

    var identity = new GenericIdentity("mymail@mydomain.com");
    A.CallTo(() => _userRepository.GetIdentity()).Returns(identity);

但它不起作用。任何想法如何以最好的方式做到这一点?

【问题讨论】:

    标签: asp.net asp.net-mvc-3 wif fakeiteasy


    【解决方案1】:

    看看 WIF 的 ClaimsPrincipalHttpModule。它将 Windows 身份转换为 IClaimsPrincipal 而无需 STS。

    还可以查看SelfSTS,这是一个非常有用的工具。

    【讨论】:

      【解决方案2】:

      创建一个假的 WindowsIdentity 类:

      public class FakeWindowsIdentity : WindowsIdentity
      {
          private readonly string _name;
      
          public FakeWindowsIdentity(string sUserPrincipalName) 
              : base(GetAnonymous())
          {
              _name = sUserPrincipalName;
          }
      
          public override string Name => _name;
      }
      

      我正在使用 FakeItEasy,所以我创建了一个假的 IPrincipal,如下所示:

      IPrincipal fakeUser = A.Fake<IPrincipal>();
      A.CallTo(() => fakeUser.Identity)
          .Returns(new FakeWindowsIdentity("domain\\username"));
      

      分配给线程:

      Thread.CurrentPrincipal = fakeUser;
      

      【讨论】: