I found it most convenient to create a one-time class that handles the installation and reset of Thread.CurrentPrincipal.
public class TemporaryPrincipal : IDisposable { private readonly IPrincipal _cache; public TemporaryPrincipal(IPrincipal tempPrincipal) { _cache = Thread.CurrentPrincipal; Thread.CurrentPrincipal = tempPrincipal; } public void Dispose() { Thread.CurrentPrincipal = _cache; } }
In the test method, you simply transfer your call using the using statement:
using (new TemporaryPrincipal(new AnonymousUserPrincipal())) { ClassUnderTest.MethodUnderTest(); }
user31934
source share