How to reset Thread.CurrentPrincipal for an unauthenticated unit test

I have a library code that can be called from several types of clients, such as WinForms, Console, ASP.NET, etc ... and which should determine the current principal. In doing so, I perform a two-step verification 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 the console application Thread.CurrentPrincipal.Identity.IsAuthenticated is always a false howerver in MSTest, it always has a valid authenticated user.

Is there a Thread.CurrentPrincipal value in the unit test for reset for unauthorized to simulate a console application?

+6
source share
2 answers

All you have to do is:

 Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(""), new string[0]); 
+11
source

I would rather create a class that implements all of the CurrentPrincipal with its proper interface and gets that interface when you need it.

You can then make fun of it in unit tests, making them simpler.

0
source

Source: https://habr.com/ru/post/927235/


All Articles