Most of the time using NUnit is very straight forward. Recently however I needed to add some functionality that will make life a little bit easier. In this post I'll show how to add some setup code that will be executed once at the start of the test run.
Why is this useful? actually I don't have a clear answer. Here are some reasons I came up with :
- Run some special set up code which is just to costly to run at every setup (even if only for class setup).
- Transparently enforce some logic on all tests (i.e. without the need for other programmer to explicitly add that logic)
- you want to add some special behavior to the test runner
NUnit Event Listeners
NUnit has several extension points that will adding almost any kind of logic to the framework. Ben Hall has posted some time back a great article describing the various possibilities For my needs (which are described here) I have been using the Event Listener extension point. Here's the class implementing the event listener:
[NUnitAddinAttribute(Type=ExtensionType.Core,Name = "My Add In",Description="A Demo for Run Setup Code")]
public class CTestingAddin : IAddin, EventListener
#region IAddin Members
public bool Install(IExtensionHost host)
IExtensionPoint listeners = host.GetExtensionPoint("EventListeners");
if (listeners == null)
#region EventListener Members
public void RunStarted(
string name, int testCount)
//Do Set up logic Here
public void RunFinished(Exception exception)
public void RunFinished(TestResult result)
public void SuiteFinished(TestSuiteResult result)
public void SuiteStarted(TestName testName)
public void TestFinished(TestCaseResult result)
public void TestOutput(TestOutput testOutput)
public void TestStarted(TestName testName)
public void UnhandledException(Exception exception)
Deployment and execution
That's all the code needed and it can be wrapped as a simple class library (dll). The dll created will need to reference the nunit.core and nunit.core.interfaces. To deploy just copy the dll to the NUnit bin\addin directory. To verify it was properly deployed open the NUnit GUI and check the tools menu under add-in to see that the add-in is there.
I will finish with two tips that will make life easier to run and debug the code.
- Its worth while to add a post build event that will deploy the add-in in into NUnit directory at the end of a successful build. In order to do that open the add-in project property and the following to Post build Event Command Line: copy $(TargetPath) <NUnit Directory>\bin\addins.
- A convenient way to debug the add-in is to put the NUnit GUI as the "Start action" of the Add-in project. This will enable putting break points normally in the code. (another option is to use the Attach To Process mechanism Ben has suggested).