Action Attributes are a feature of NUnit designed to better enable composability of test logic. Often when writing unit tests we have logic that we want to run upon certain events in the test cycle (e.g. SetUp, TearDown, FixtureSetUp, FixtureTearDown, etc.). NUnit has had the ability to execute code upon these events by decorating fixture classes and methods with the appropriate NUnit- provided attributes. Action Attributes allow the user to create custom attributes to encapsulate specific actions for use before or after any test is run.
Suppose we have some tests in multiple fixtures that need the same in-memory test database to be created and destroyed on each test run. We could create a base fixture class and derive each fixture that depends on the test from that class. Alternatively, we could create a SetUpFixture class at the level of a common namespace shared by each fixture.
This works fine, until we need some other reusable functionality, say the ability to configure or reset a ServiceLocator. We could put that functionality in the base fixture class or setup fixture, but now we're mixing two different responsibilities into the base class. In the case of a setup fixture, this only works if all classes requiring both features are located in a common namespace. In some cases we may *not* want the test database, but we do want ServiceLocator configuration; and sometimes we want the opposite. Still other times we'll want both - so we'd have to make the base class configurable.
If we now discover a third piece of functionality we need to reuse, like configuring the Thread's CurrentPrincipal in arbitrary ways, the complexity of the solution very quickly. We've violated the Single Responsibility Principle and are suffering for it. What we really want is the ability to separate the different pieces of resuable test logic and compose them together as our tests need them.
Action Attributes get us out of our bind. Consider this example:
[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() { /* ... */ } }
Here we have used user-defined attributes to identify five different actions that we want to compose together in different ways for different tests:
Action attributes are defined by the programmer. They implement the ITestAction interface, which is defined as follows:
public interface ITestAction { void BeforeTest(TestDetails details); void AfterTest(TestDetails details); ActionTargets Targets { get; } }
For convenience, you may derive your own action attribute from NUnit's TestActionAttribute, an abstract class with virtual implementations of each member of the interface. Alternatively, you may derive from System.Attribute and implement the interface directly.
[Flags] public enum ActionTargets { Default = 0, Test = 1, Suite = 2 }
The value returned from the Targets property determines when the BeforeTest and AfterTest methods will be called. The ActionTargets enum is defined as follows:
When an attribute that returns ActionTargets.Suite is applied to either a class or a parameterized method, NUnit will execute the attribute's BeforeTest method prior to executing the test suite and then execute the AfterTest method after the test suite has finished executing. This is similar to how the TestFixtureSetUp and TestFixtureTearDown attributes work.
On the other hand, when an attribute that returns ActionTargets.Test is used in the same situations, NUnit will execute the attribute's BeforeTest method prior to each contained test case and the AfterTest method after each test case. This is similar to how the SetUp and TearDown attributes work.
Action attributes that return ActionTargets.Default target the particular code item to which they are attached. When attached to a method, they behave as if ActionTargets.Test had been specified. When attached to a class or assembly, they behave as if ActionTargets.Suite was returned.
The examples that follow all use the following sample Action Attribute:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Assembly, AllowMultiple = true)] public class ConsoleActionAttribute : Attribute, ITestAction { private string _Message; public ConsoleActionAttribute(string message) { _Message = message; } public void BeforeTest(TestDetails details) { WriteToConsole("Before", details); } public void AfterTest(TestDetails details) { WriteToConsole("After", details); } public ActionTargets Targets { get { return ActionTargets.Test | ActionTargets.Suite; } } private void WriteToConsole(string eventMessage, TestDetails details) { Console.WriteLine("{0} {1}: {2}, from {3}.{4}.", eventMessage, details.IsSuite ? "Suite" : "Case", _Message, details.Fixture != null ? details.Fixture.GetType().Name : "{no fixture}", details.Method != null ? details.Method.Name : "{no method}"); } }
Note that the above Action Attribute returns the union of ActionTargets.Test and ActionTargets.Suite. This is permitted, but will probably not be the normal case. It is done here so we can reuse the attribute in multiple examples. The attribute takes a single constructor argument, a message, that will be used to write output to the console. All of the Before and After methods write output via the WriteToConsole method.
[TestFixture] public class ActionAttributeSampleTests { [Test][ConsoleAction("Hello")] public void SimpleTest() { Console.WriteLine("Test ran."); } }
Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test ran. After Case: Hello, from ActionAttributeSampleTests.SimpleTest.
[TestFixture] public class ActionAttributeSampleTests { [Test] [ConsoleAction("Hello")] [ConsoleAction("Greetings")] public void SimpleTest() { Console.WriteLine("Test run."); } }
Before Case: Greetings, from ActionAttributeSampleTests.SimpleTest. Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test run. After Case: Hello, from ActionAttributeSampleTests.SimpleTest. After Case: Greetings, from ActionAttributeSampleTests.SimpleTest.
[TestFixture] public class ActionAttributeSampleTests { [Test] [ConsoleAction("Hello")] [TestCase("02")] [TestCase("01")] public void SimpleTest(string number) { Console.WriteLine("Test run {0}.", number); } }
Before Suite: Hello, from ActionAttributeSampleTests.SimpleTest. Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test run 01. After Case: Hello, from ActionAttributeSampleTests.SimpleTest. Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test run 02. After Case: Hello, from ActionAttributeSampleTests.SimpleTest. After Suite: Hello, from ActionAttributeSampleTests.SimpleTest.
[TestFixture] [ConsoleAction("Hello")] public class ActionAttributeSampleTests { [Test] public void SimpleTestOne() { Console.WriteLine("Test One."); } [Test] public void SimpleTestTwo() { Console.WriteLine("Test Two."); } }
Before Suite: Hello, from ActionAttributeSampleTests.{no method}. Before Case: Hello, from ActionAttributeSampleTests.SimpleTestOne. Test ran. After Case: Hello, from ActionAttributeSampleTests.SimpleTestOne. Before Case: Hello, from ActionAttributeSampleTests.SimpleTestTwo. Test ran. After Case: Hello, from ActionAttributeSampleTests.SimpleTestTwo. After Suite: Hello, from ActionAttributeSampleTests.{no method}.
[ConsoleAction("Hello")] public interface IHaveAnAction { } [TestFixture] public class ActionAttributeSampleTests : IHaveAnAction { [Test] public void SimpleTest() { Console.WriteLine("Test run."); } }
Before Suite: Hello, from ActionAttributeSampleTests.{no method}. Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test run. After Case: Hello, from ActionAttributeSampleTests.SimpleTest. After Suite: Hello, from ActionAttributeSampleTests.{no method}.
[AttributeUsage(AttributeTargets.Interface)] public class InterfaceAwareActionAttribute : TestActionAttribute { private readonly string _Message; public InterfaceAwareActionAttribute(string message) { _Message = message; } public override void BeforeTest(TestDetails details) { IHaveAnAction obj = details.Fixture as IHaveAnAction; if(obj != null) obj.Message = _Message; } public override ActionTargets Target { get { return ActionTargets.Test; } } } [InterfaceAwareAction("Hello")] public interface IHaveAnAction { string Message { get; set; } } [TestFixture] public class ActionAttributeSampleTests : IHaveAnAction { [Test] public void SimpleTest() { Console.WriteLine("{0}, World!", Message); } public string Message { get; set; } }
Hello, World!
Here we see a new action attribute, [InterfaceAwareAction]. This attribute uses the Fixture property of the TestDetails passed into BeforeTest and casts it to an interface, IHaveAnAction. If the fixture implements the IHaveAnAction interface, the attribute sets the Message property to the string passed into the constructor of the attribute. Since the attribute is applied to the interface, any class that implements this interface gets it's Message property set to the string provided to the constructor of the attribute. This is useful when the action attribute provides some data or service to the tests.
Note that this attribute inherits from TestActionAttribute. It uses the default (do-nothing) implementation of AfterTest and overrides both BeforeTest and Target.
[assembly: ConsoleAction("Hello")] [TestFixture] public class ActionAttributeSampleTests { [Test] public void SimpleTest() { Console.WriteLine("Test run."); } }
Before Suite: Hello, from {no fixture}.{no method}. Before Case: Hello, from ActionAttributeSampleTests.SimpleTest. Test run. After Case: Hello, from ActionAttributeSampleTests.SimpleTest. After Suite: Hello, from {no fixture}.{no method}.