Reputation: 792
I've read the nunit documentation on actions attributes and I want to create an action attribute which can be used on a Test method or a Setup method (to avoid repeating the attribute on all tests methods).
I created the following class (very similar to the one from the docs, but where I try to allow everything) :
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Assembly,
AllowMultiple = true)]
public class CustomActionAttribute : Attribute, ITestAction
{
private string message;
public CustomActionAttribute(string message)
{
this.message = message;
}
public void BeforeTest(TestDetails details)
{
WriteToConsole("Before", details);
}
public void AfterTest(TestDetails details)
{
WriteToConsole("After", details);
}
public ActionTargets Targets
{
get { return ActionTargets.Default | ActionTargets.Suite | ActionTargets.Test; }
}
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}");
}
}
What works :
[Test, CustomAction("TEST")]
public void BasicAssert()
{
}
In the nunit Test Runner Text output pannel, I have
***** Test.CustomerT.BasicAssert
Inside Setup
Before Case: TEST, from CustomerT.BasicAssert.
After Case: TEST, from CustomerT.BasicAssert.
What doesn't works :
[SetUp, CustomAction("SETUP")]
public void CustomAttributeBeforeSetup()
{
System.Diagnostics.Debug.WriteLine("Inside Setup");
}
[Test]
public void BasicAssert()
{
}
In the nunit Test Runner Text output pannel, I have
***** Test.CustomerT.BasicAssert
Inside Setup
?
How to create a custom attribute that can be executed on Setup method ?
Upvotes: 1
Views: 2694
Reputation: 1484
I am assuming that what you really want is to have BeforeTest and AfterTest run before and after entire test fixture. If that is the case, then instead of putting it on the SetUp method put the attribute on the Fixture i.e. test class. In TestDetails you can see if the particular method (i.e. BeforeTest and AfterTest) is run for a test or fixture by checking TestDetails.IsSuite.
Upvotes: 0