简体   繁体   中英

Add a custom attribute onto a method at runtime

What I was asked to develop, I don't think can be developed. Maybe someone can prove me wrong.

We have a custom Attribute that is used on hundreds of methods in our solution, and new methods are being added continously. We also use NUnit for Integration testing.

So a class may look like the following:

[SomeAttribute]
[Category("SlowTest")]
public class IAmClass()
{
   //yada yada yada
}

Wherever [SomeAttribute] is used, we'd also like an NUnit attribute to automatically add itself at runtime to each method that implements [SomeAttribute], so NUnit can pickup on this additional Category, without developers having to add two attributes to new classes.

Which at runtime would essentially result in:

[SomeAttribute]
[Category("SomeAttribute")]
[Category("SlowTest")]
public class IAmClass()
{
   //yada yada yada
}

So with a basic custom attribute, such as:

public class SomeAttribute : Attribute
{
    public SomeAttribute()
    {
    }
}

How can I achieve the desired solution by inserting the needed code into the custom Attribute?

NOTE: If there were a way of getting NUnit to recognize the [SomeAttribute] directly, instead of being in a Category attribute, I'd implement that solution

Your question seems to be saying that you want the source code to be changed, but I'm thinking you really mean you want NUnit to act as if the source code were changed. The two things are quite different and changing the source from inside a test sounds crazy so I'm going to assume you mean you want NUnit to treat your attribute as a category.

If so, that's pretty easy to do but exactly how to do it depends on how your existing custom attribute was implemented. If it's possible to inherit from CategoryAttribute as @Jonathan suggests that would be simplest. CategoryAttribute is designed for this. Its default constructor uses the name of the inherited class as the name of the category. Your tests will already have that attribute.

OTOH, if you cannot inherit from CategoryAttribute for some reason, you should simply look in the nunit source code at what CategoryAttribute does and do the same thing in your custom attribute.

Specifically, you would implement IApplyToTest interface...

using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;

...


public void ApplyToTest(Test test)
{
    test.Properties.Add("Category", "SomeAttribute");
}

Of course, either approach requires changing the implementation of your custom attribute, so if that's off limits I don't have any answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM