Second Stanza

February 26, 2009

SetPrincipalPolicy in Unit Tests

Filed under: .NET Development, Testing — Tags: — dfbaskin @ 9:42 pm

A while back, I noticed that this test always fails in Visual Studio 2008 w/SP1:


[TestClass]
public static class TestInfo
{
    [AssemblyInitialize]
    public static void InitializeTesting( TestContext testContext )
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(
             System.Security.Principal.PrincipalPolicy.WindowsPrincipal );
        Assert.IsInstanceOfType(
             System.Threading.Thread.CurrentPrincipal,
             typeof(System.Security.Principal.WindowsPrincipal) );
    }
}

According to the documentation:

Setting this value will only be effective if you set it before using the Thread.CurrentPrincipal property. For example, if you set Thread.CurrentPrincipal to a given principal (for example, a generic principal) and then use the SetPrincipalPolicy method to set the PrincipalPolicy to WindowsPrincipal, the current principal will remain the generic principal.

So it’s apparent that MS Test is doing just that and causing the test to fail. This was confirmed in the Microsoft Connect item I posted about it:

This is by design. We noticed this when doing testing of the fix for SP1 and made a trade off. The tradeoff is a performance hit that we would take each time we invoke a method in the test assembly verses using a simple workaround. The workaround is to explicitly set the “System.Threading.Thread.CurrentPrincipal”.

We use the Thread.CurrentPrincipal policy prior to invoking any test method to make a backup of its value. We do this so we can restore it to the original policy after the test finishes executing. This was done to solve the issues with custom principals being serialized back into the main AppDomain and failing to deseralize.

Thanks
Visual Studio Product Team

At least the workaround is simple enough.

Create a free website or blog at WordPress.com.