Reputation: 3442
I was wondering if it is possible to create custom NUnit attribute that will behave as CategoryAttribute and at the same time as TestAttribute.
NUnit documentation - Test Attribute NUnit documentation - Category Attribute
What I am trying to achieve is something like this:
public class UnitTestAttribute : TestAttribute, CategoryAttribute, ITestAction
{
public UnitTestAttribute() : base("UnitTest")
public void BeforeTest(ITest test) { /*some logic*/ }
public void AfterTest(ITest test) { /*some logic*/ }
public ActionTargets Targets => ActionTargets.Test;
}
Unfortunately, this will not work as you can not have 2 base classes for a single class. What I am trying to achieve is pretty much to minimalize the amount of code I have to write in order to mark some test as (in this case) unit test yet at the same time to be able to filter the tests based on their category. So my current code
[Test, UnitTest]
public void SomeTest() { /*doing some stuff*/ }
will change to
[UnitTest]
public void SomeTest() { /*doing some stuff*/ }
And I will still be able to run the tests using the following command
nunit3-console mytest.dll --where "cat == UnitTest"
and also VS Test explorer will find the categories etc.
Upvotes: 0
Views: 1207
Reputation: 13681
Since a CategoryAttribute doesn't do anything but set a property on the test, I would suggest you inherit from TestAttribute and implement the category behavior yourself.
You will have to implement the IApplyToTest interface. In the call to IApplyToTest, you should add (not set) the category property of the test to the value you want. That's important because your test could theoretically have additional category annotations.
See the code for CategoryAttribute
and PropertyAttribute
for details. PropertyAttribute
actually does most of the work. Use the constant value for category that you find in PropertyNames.cs
Upvotes: 1