2014-09-26 92 views
2

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

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

//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中可用。

这可能吗?

回答

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; 
    }