Test Secure Class Instantiation Helper Method

code, tdd 0 comments suggest edit

This is a quick follow-up to my last post. That seemed like such a common test situation I figured I’d write a quick generic method for encapsulating those two tests.

I’ll start with usage.

public void FileBrowserSecureCreationTests()
  AssertSecureCreation<FileBrowserConnector>(new string[] {"Admins"});

And here’s the method.

/// <summary> 
/// Helper method. Makes sure you can create an instance  
/// of a type if you have the correct role.</summary> 
/// <typeparam name="T"></typeparam> 
/// <param name="allowedRoles"></param> 
public static void AssertSecureCreation<T>(string[] allowedRoles
  , params object[] constructorArguments)
    Activator.CreateInstance(typeof (T), constructorArguments);
    Assert.Fail("Was able to create the instance with no security.");
  catch(TargetInvocationException e)
      , e.InnerException
      , "Expected a security exception, got something else.");

  MockRepository mocks = new MockRepository();

  IPrincipal principal;
  using (mocks.Record())
    IIdentity identity = mocks.CreateMock<IIdentity>();
    principal = mocks.CreateMock<IPrincipal>();
    Array.ForEach(allowedRoles, delegate(string role) 

  using (mocks.Playback())
    IPrincipal oldPrincipal = Thread.CurrentPrincipal;
      Thread.CurrentPrincipal = principal;       
      Activator.CreateInstance(typeof(T), constructorArguments);
      //Test passes if no exception is thrown.
      Thread.CurrentPrincipal = oldPrincipal;     

There are definite improvements we can make, but this is a nice quick way to test the basic permission level for a class.

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.



3 responses

  1. Avatar for Dan
    Dan September 22nd, 2007

    Nice helper method, it can be easily extended for Windows authentication or username checks

  2. Avatar for Nick Berardi
    Nick Berardi September 23rd, 2007

    This is actually a very common at least in the code I use. One other method that I use is to create instances of an object from non-public constructors. I wrote about this a while ago on my blog - How To: Unit Test Hidden Classes. It seems we both employee similar helper methods in our unit testing.

  3. Avatar for pollux
    pollux March 21st, 2008