Testing Security Code with Moles

I am by far no (unit) testing expert. But I always found it odd that I sometimes have to re-structure code to make it explicitly unit-testable.

One typical example is code that relies on some sort of context – e.g. Thread.CurrentPrincipal. I personally like this pattern in the .NET Framework – but it is not ideal for testing.

Recently I ran across Moles which is a mocking and stubs framework from Microsoft Research which has some features that can help here. Inspired by this video – I gave it a try.

The following code allows “faking” Thread.CurrentPrincipal:

using System.Security.Principal;
using System.Threading.Moles;
using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[assembly: MoledType(typeof(System.Threading.Thread))]

namespace SecurityTest
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        [HostType(“Moles”)]
        public void TestSecurityCode()
        {
            MThread.CurrentPrincipalGet = () =>
                new GenericPrincipal(new GenericIdentity(“dominick”), null);

            var security = new SecurityCode();
            var user = security.SomeMethod();

            Assert.AreEqual(“dominick”, user);
        }
    }

    public class SecurityCode
    {
        public string SomeMethod()
        {
            // simulates context
            Thread.CurrentPrincipal = new GenericPrincipal(
              new GenericIdentity(“bob”), null);

            return Thread.CurrentPrincipal.Identity.Name;
        }
    }
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s