R – Does Team System Test support running tests under a specific identity

Securitytestingunit testing

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

Best Answer

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.