views:

59

answers:

2

Hi,

Is it possible to configure unit tests in Team System Test to run under a specific identity (similar to runas)?

Thanks much, Jon

A: 

While I'm not aware that it is (I don't think it is), you should seriously consider whether your code can be generalized to work against the IPrincipal interface instead of relying on the current WindowsIdentity.

This makes your code a whole lot more flexible, and also makes unit testing a lot simpler because then you can assign any IPrincipal implementation (such as GenericPrincipal) to Thread.CurrentPrincipal. Just remember to do proper Fixture Teardown after each test case. Here's a typical example from one of our test suites:

[TestClass]
public class AuditServiceTest
{
    private IPrincipal originalPrincipal;

    public AuditServiceTest()
    {
        this.originalPrincipal = Thread.CurrentPrincipal;
    }

    [TestCleanup]
    public void TeardownFixture()
    {
        Thread.CurrentPrincipal = this.originalPrincipal;
    }

    [TestMethod]
    public void SomeTest()
    {
        Thread.CurrentPrincipal = 
            new GenericPrincipal(
                new GenericIdentity("Jane Doe", null));
        // More test code
    }
}

That said, there are scenarios where impersonation in a "unit" test might be warranted. The ways I've seen this done in MSTest is by writing explict impersonation code in the test cases.

Mark Seemann
Hi Mark - Nice Response!For my particular scenario I am doing an Intranet site where I utilize Kerberos Authentication in IE, and ASP.Net uses impersonation to act on the user's behalf to access SQL. So I don't think a Generic Principle would work in my scenario.
Jon Kragh
That's right - that's why I included that little caveat in the end :)
Mark Seemann
A: 

It does not look like Team Test has this ability. I ended up coding my unit test to impersonate the user using this wrapper for calling the LogonUser Win32 API.

Now my unit test is like so:

[TestMethod]
public void Assert_Access_Denied()
{
    bool denied = false;

    using (new Impersonator("SomeValidUserWithNoAccess", "SomeTestDomain", "SomeTestPassword"))
    {                
        try
        {
            // access some method that performs windows auth
        }
        catch (UnauthorizedAccessException exc)
        {
            denied = true;
        }
    }

    Assert.IsTrue(denied);
}
Jon Kragh