Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset Thread.CurrentPrincipal to unauthenticated in a Unit Test

Tags:

c#

.net

mstest

I have library code that may be called from multiple client types such as WinForms, Console, ASP.NET etc... and which needs to determine the current principal. In doing so I am performing a two step check of Thread.CurrentPrincipal and then Environment.UserName as follows:

var currentUser = !System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated ? null : System.Threading.Thread.CurrentPrincipal.Identity.Name;
if (string.IsNullOrWhiteSpace(currentUser))
{
    currentUser = Environment.UserName;
}

In a Console app Thread.CurrentPrincipal.Identity.IsAuthenticated is always false howerver in MSTest it always has a valid authenticated user.

Is there anyway to reset the value of Thread.CurrentPrincipal in the unit test to unauthenticated to mimick the Console app?

like image 319
Slugart Avatar asked Oct 09 '12 08:10

Slugart


1 Answers

All you need to do is:

Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(""), new string[0]);
like image 116
Joe Avatar answered Oct 18 '22 10:10

Joe