开发者

Does Team System Test support running tests under a specific identity?

开发者 https://www.devze.com 2022-12-12 04:33 出处:网络
Is it possible t开发者_JAVA技巧o configure unit tests in Team System Test to run under a specific identity (similar to runas)?While I\'m not aware that it is (I don\'t think it is), you should serious

Is it possible t开发者_JAVA技巧o configure unit tests in Team System Test to run under a specific identity (similar to runas)?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号