NUnit’s new Action Attributes is AOP to your unit tests

With the new NUnit release (v2.6) introduce a new feature called Action Attributes which means that now NUnit has rolled out it’s own mini-AOP capabilities.

In the past SetUp and TearDown where used to perform actions before and/or after a test run, they worked well enough but were limited to running certain operation only on the tests on that test class – on all thee tests. Confronted with the need to perform the same operation for multiple test classes the test writer (you) needed to resort to inheritance which is not bad solution as long as you do not need to support multiple "pre/post behaviors on some of the tests.

And there was always the solution of writing the same code over and over in all of the tests either as duplicating the code or putting it inside a method and calling it from all the tests. Sounds familiar? To me it sounds just like a case of a simple cross-cutting concern.

How it works

All you have to to is implement the following interface:

public interface ITestAction
{
void BeforeTest(TestDetails details);

void AfterTest(TestDetails details);

ActionTargets Targets { get; }
}


and that’s it! For more details – head to NUnit’s site for full description.



Now adding Aspects is as simple as creating a class and then putting the attribute on a method, class or even assembly:



[TestFixture, ResetServiceLocator]
public class MyTests
{
[Test, CreateTestDatabase]
public void Test1() { /* ... */ }

[Test, CreateTestDatabase, AsAdministratorPrincipal]
public void Test2() { /* ... */ }

[Test, CreateTestDatabase, AsNamedPrincipal("charlie.poole")]
public void Test3() { /* ... */ }

[Test, AsGuestPrincipal]
public void Test4() { /* ... */ }
}


Any issues?



The only downside is the being a new feature it’s only supported by NUnit’s GUI and console runners. This means that if you’re using a 3rd party runner such as TesDriven.NET, R# or CodeRush you’ll have to wait until support is added in some future release.



Conclusion



In the past other testing frameworks such as MBUnit (and even MSTest) had similar features – but never this simple.



There you have it – simple unit testing AOP curtsy of NUnit. Now that I have it I don’t understand how I never felt that this functionality was missing. The new Action Attributes really shine in integration tests. Making database setup, running under specific permissions or just making sure a server is up before running the tests.



 


Happy Coding…

Labels: , , , ,