Follow @RoyOsherove on Twitter

Extending NUnit *easily* with version 2.2.1 (finally!)

I finally got some time so I sat down with the latest version of NUnit - 2.2.1 and tried using its extensibility features like the ability to create new custom test attributes that change test behavior, hopefully ridding myself of more complex projects that I had to do in the past (such as using interception or create a whole new binary version of Nunit just so that this could be done) .
I'm glad to say that it worked out great! NUnit 2.2.1 finally allows one to (no so)easily add custom attributes such as Rollback to NUnit without resorting to violence. Yey!
Unfortunately, the process is still too bureaucratic (for me at least), requiring the developer to add 3 new classes for each test attribute. I took it upon myself to check and see if this process could be made easier and it does :)
 
I basically created a base class you inherit from and does all the nasty work for you. Here's how easy it is to create a new attribute that does tracing on your unit tests:
 

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]

[TestBuilder(typeof(CustomTestAttributeBase.CustomTestBuilder))]

public class SimpleTraceAttribute:CustomTestAttributeBase

{

   public override void BeforeTestRun (TestCaseResult testResult,

                                       TemplateTestCase testCase)

            {

                  Console.WriteLine("START: "+ testCase.Name);

            }

 

   public override void AfterTestRun (TestCaseResult testResult,

                                    TemplateTestCase testCase)

            {

                  Console.WriteLine("END: "+ testCase.Name);

            }

}

 
Simple and quick, no fuss.
 

Blogger dinner with Johanna Rothman - Rescheduled

Creating custom test attributes easily with NUnit 2.2.1