Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at
Switching to a Different User Inside a Unit Test

Update: Re-published from old blog 

I found a need yesterday to test some code in particular security contexts. After some (as always) prompt guidance from the altdotnet mailing list, I had the (as it turns out) all too simple solution. xUnit includes an attribute for this, but as I'm using NUnit and just wanted a clean way to do this without writing an extension, I figured I would just play around with it a bit.

One quick bit of refactoring later, and we have a class to handle this for us:

 1:  public class SecurityContextSwitcher : IDisposable
 2:  {
 3:  private readonly IPrincipal originalPrincipal;
 5:  public SecurityContextSwitcher(string username, string[] roles)
 6:  {
 7:  originalPrincipal = Thread.CurrentPrincipal;
 8:  var identity = new GenericIdentity(username);
 9:  var principal = new GenericPrincipal(identity, roles);
 10:  Thread.CurrentPrincipal = principal;
 11:  }
 13:  public void Dispose()
 14:  {
 15:  Thread.CurrentPrincipal = originalPrincipal;
 16:  }
 17:  }

This class allows us to test quite simply with the following syntax:

 1:  [Test]
 2:  public void Handler_will_allow_access_to_anyone_who_is_in_Users_role()
 3:  {
 4:  using (new SecurityContextSwitcher("Test", new[] {"Users"}))
 5:  {
 6:  var request = new GetRequest {Id = new Guid()};
 7:  handlerUnderTest.Handle(request);
 8:  }
 9:  }
 11:  [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Users")]
 12:  public override void Handle(GetRequest message)
 13:  {
 14:  ...
 15:  }

Posted 04-15-2008 6:51 PM by Jak Charlton
Filed under: , , ,


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)