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?
All you need to do is:
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(""), new string[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With