Test Secure Class Instantiation Helper Method

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.

[Test]
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)
{
  try   
  {     
    Activator.CreateInstance(typeof (T), constructorArguments);
    Assert.Fail("Was able to create the instance with no security.");
  }
  catch(TargetInvocationException e)
  {
    Assert.IsInstanceOfType(typeof(SecurityException)
      , e.InnerException
      , "Expected a security exception, got something else.");
  }

  MockRepository mocks = new MockRepository();

  IPrincipal principal;
  using (mocks.Record())
  {
    IIdentity identity = mocks.CreateMock<IIdentity>();
    SetupResult.For(identity.IsAuthenticated).Return(true);
    principal = mocks.CreateMock<IPrincipal>();
    SetupResult.For(principal.Identity).Return(identity);
    Array.ForEach(allowedRoles, delegate(string role) 
    {
      SetupResult.For(principal.IsInRole(role)).Return(true);
    });
  }

  using (mocks.Playback())
  {
    IPrincipal oldPrincipal = Thread.CurrentPrincipal;
    try
    {       
      Thread.CurrentPrincipal = principal;       
      Activator.CreateInstance(typeof(T), constructorArguments);
      //Test passes if no exception is thrown.
    }     
    finally
    {       
      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.

Technorati tags: , ,

What others have said

Requesting Gravatar... Dan Sep 23, 2007 1:51 AM
# re: Test Secure Class Instantiation Helper Method
Nice helper method, it can be easily extended for Windows authentication or username checks
Requesting Gravatar... Nick Berardi Sep 23, 2007 6:01 PM
# re: Test Secure Class Instantiation Helper Method
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.
Requesting Gravatar... pollux Mar 22, 2008 8:16 AM
# re: Test Secure Class Instantiation Helper Method
super

What do you have to say?

(will show your gravatar)
Please add 7 and 3 and type the answer here: