I am currently refactoring some code which performs Windows Impersonation for testability and have run into a bit of a roadblock. This is the bit of code that I am having trouble with:
...
if (LogonUserA(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) > 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate))
{
var tempWindowsIdentity = new System.Security.Principal.WindowsIdentity(tokenDuplicate);
var impersonationContext = tempWindowsIdentity.Impersonate();
...
}
...
}
How do I mock the behaviour of instantiating a WindowsIdentity object out? I have thought of various alternatives:
- Pass in a factory class that would create the instance and mock the behaviour of that
- Pass in a delegate that handles the creation of the instance (i.e. like a C++ function pointer)
None of these alternatives seem particularly good to me because I'm afraid they would blur the intent of the method as the method signature would look something like the following:
public bool Impersonate(string user, string password, string domain, Factory factory)
or
public bool Impersonate(string user, string password, string domain, delegate WinIDCreator)
Because the intent of the method is to impersonate a particular user, it doesn't make sense to me that either a Factory class or Delegate should be provided to it. I do want to isolate and mock this behaviour out however as I am uncomfortable with the thought of a new WindowsIdentity instance being created every time I run a bunch of unit tests.
Any ideas or comments?