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:

public static class TestInfo
    public static void InitializeTesting( TestContext testContext )
             System.Security.Principal.PrincipalPolicy.WindowsPrincipal );
             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.

Visual Studio Product Team

At least the workaround is simple enough.

1 Comment »

  1. If you want to make this more dynamic and want to use the current user, you could use the following:
    var identity = new GenericIdentity(Environment.UserDomainName + “\\” + Environment.UserName);
    var principal = new GenericPrincipal(identity, null);
    Thread.CurrentPrincipal = principal;

    Comment by René Titulaer — February 28, 2011 @ 8:15 am

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: