Brad Wilson - The .NET Guy

Technologist. Agile Evangelist. Poker Player. Amateur Neologist. Metalhead.

My Links

Post Categories

Article Categories

Archives

Blog Stats

Stuff

Weaving with xUnit.net

One of the more interesting features we added to xUnit.net was support for "before/after test" code in the form of an attribute. It feels a bit like method weaving in AOP. Our first example of this was the [AutoRollback] attribute that we shipped in xunit.extensions.dll.

Another one we'll do for CodePlex is one I call [FreezeClock], which uses our internal Clock class (a testable replacement for DateTime) which supports the concept of freezing the clock at a moment in time, and then unfreezing when the test is over. This is useful to ensure, for example, that some code under test is calling "Clock.Now", so that you can actually test the value they pushed in some arbitrary amount of time later by simply calling "Clock.Now" again. When we get around to doing that one, I'll make a blog post which shows the Clock class as well as our attribute.

This morning I woke up to find Casper had blogged a third one: [AssumeIdentity]. This little gem will override the principal on the current thread with a generic identity with the name you give it. Sweet and simple.

public class AssumeIdentityAttribute : BeforeAfterTestAttribute
{
    public AssumeIdentityAttribute(string name)
    {
        this.name = name;
    }

    public override void Before(MethodInfo methodUnderTest)
    {
        originalPrincipal = Thread.CurrentPrincipal;
        GenericIdentity identity = new GenericIdentity("boo");
        GenericPrincipal principal =
                new GenericPrincipal(identity, new string[] { name });
        Thread.CurrentPrincipal = principal;
    }

    public override void After(MethodInfo methodUnderTest)
    {
        Thread.CurrentPrincipal = originalPrincipal;
    }

    readonly string name;
    IPrincipal originalPrincipal;
}

I suspect there are a lot of these little cross-cutting concern attributes waiting to be written (and shared). :)

posted on Thursday, September 27, 2007 7:09 AM