【问题标题】:Testing WCF Service that Uses Impersonation测试使用模拟的 WCF 服务
【发布时间】:2014-11-21 12:29:48
【问题描述】:

我正在将旧 WCF 服务的一些现有集成测试转换为通过 NUnit 自动化。当前测试调用 WCF 服务的已部署版本;我想做的是让测试直接/内部命中服务类(MyService.svc.cs)。

我遇到的问题是该服务使用模拟:

    //this is a method in MyService.svc.cs
    public SomeObject GetSomeObject()
    {
      using (GetWindowsIdentity().Impersonate())
      {
        //do some stuff
      }

      return null;
    }

    private WindowsIdentity GetWindowsIdentity()
      {
        var callerWinIdentity = ServiceSecurityContext.Current.WindowsIdentity;

        var cf = new ChannelFactory<IMyService>();
        cf.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

        return callerWinIdentity;
    }

问题在于,当我从单元测试中调用 ServiceSecurityContext.Current 时,它始终为空。

模拟在下游操作中很重要,所以我不能绕过这段代码而只调用using 块中的内容。可以将我的测试代码包装在 WindowsIdentity.GetCurrent().Impersonate() 中,然后 然后 调用 using 块中的内容(绕过 MyService.svc.cs 代码),但这并不理想,因为这不会是一个完整的端到端测试。

我不需要伪造不同的用户来模拟——我只需要在 ServiceSecurityContext.Current 中提供跑步者的用户上下文。

这可能吗?

【问题讨论】:

    标签: c# wcf unit-testing nunit impersonation


    【解决方案1】:

    我仍然对更好、侵入性更小的方法感兴趣,但这似乎目前可行。

    我为 MyService 创建了第二个构造函数以允许使用 WindowsIdentity.GetCurrent()

        private readonly bool _useLocalIdentity;
    
        public MyService(bool useLocalIdentity) :this()
        {
            _useLocalIdentity = useLocalIdentity;
        }
    
    
        private WindowsIdentity GetWindowsIdentity()
          {
            if (_useLocalIdentity)
            {
                return WindowsIdentity.GetCurrent();
            }
    
            var callerWinIdentity = ServiceSecurityContext.Current.WindowsIdentity;
            if (callerWinIdentity == null)
            {
                throw new InvalidOperationException("Caller not authenticated");
            }
    
            var cf = new ChannelFactory<IMyService>();
            cf.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
    
            return callerWinIdentity;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 2017-03-14
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多