Unit Testing Custom Attributes

I did a quick search on Google and found nothing.

I have a custom attribute at the class level, that I would like to Unit Test. But I am running into a road block on what I need to do to get this happening.

Is anyone able to shed some light on this?

What aspects of your custom attribute do you want to test exactly?

Well, 100% coverage would be a start!

It is a start - a bad one. Focus on the purpose and outcomes of your testing, not on turning lines of code green. Use coverage as a tool to help you realise when you overlooked a property of your system (e.g. ‘oh, I forgot to write tests that capture how the code should behave when given invalid inputs’), don’t use it as a goal or an indicator of quality.

Try these questions:

  • What are the situations in which your custom attribute will be used, that you want to verify are working as designed?
  • What properties of the way the attribute works are most at risk of being broken by future evolution of the system?
  • Does the attribute itself have significant functionality, or is most of the functionality actually in the code which uses the attribute?

Ultimately an attribute is like any other class - you can do new MyCustomAttribute() and access members on it - and if necessary you can also create dedicated classes in your tests which you apply the attribute to.

I don’t subscribe to the 100 Code coverage is bad.

Right now, I need to know how to know how to get started, so rather than a lecture on this or that, how about how do I get started!

I am not new to TDD or BDD, and have used them in other languages as well as C# to some degree. All I want/need is right now a starting point on how I do this in Unity!

Can you or can you not provide examples?

And how would I go about testing how many arguments where used?

class MyCustomAttributeAttribute : System.Attribute
{
    public int Value { get; }
    public MyCustomAttributeAttribute(int value)
    {
        Value = value;
    }
}

class TestClass
{
    [Test]
    public void TestMyCustomAttribute()
    {
        var attr = new MyCustomAttributeAttribute(5);
        Assert.That(attr.Value, Is.EqualTo(5));
    }
}

And how does that check that it is used?

You never said anything about wanting to check that it was used. You said you wanted 100% code coverage, which my example provides.

Which brings us back to “focus on the purpose and outcomes of your testing,” and the questions I originally asked you:

  • What are the situations in which your custom attribute will be used, that you want to verify are working as designed?
  • What properties of the way the attribute works are most at risk of being broken by future evolution of the system?
  • Does the attribute itself have significant functionality, or is most of the functionality actually in the code which uses the attribute?

Neither I nor anyone else is going to be able to effectively help you if you do not explain what you are trying to accomplish. “Unit test a custom attribute” is too vague to be meaningful.

EDIT: To put it another way: you said that you’re familiar with BDD. So what are the BDD testcases that you are trying to encode?

Well please DO NOT take offence to this, but code coverage includes if the Usage is Valid on say the class, property, field etc. And I guess this is why the Unity Editor is continuously getting broken! I refer to the latest bug that has been around a few months now, 5 updates and still not fix to it, in the Animator. I guess testing the number of transitions would not constitute making sure you could have more than 1 transition and it still works.

I am very well aware how to test a class, but Attributes go beyond testing a class, it goes into how it is used and what Testing is also about. Making sure that what is intended is indeed intended use!

That doesn’t sound like any definition of code coverage I’ve ever seen, but never mind, let’s focus on the problem you’re actually trying to solve here.

What I think you’re saying is: you want to create unit tests that verify that your custom attribute is only applicable to the intended types of target - i.e. that you can put the attribute on a class, but that you can’t put it on e.g. a property.

Is that accurate?

That would be 100% correct, and why would would you not consider this a definition of code coverage?

If the Attribute intention is changed, I need to cover it has changed, that is what Code Coverage is for! The same if I expect a string to contain a certain value, and it has changed. By your definition you would not consider that for code coverage!

In that case, I think the only unit test that makes sense is one that retrieves the AttributeUsageAttribute from your attribute class and checks that its ValidOn property has the value you expect. Testing anything more than that is testing ‘does the compiler work correctly’, and there’s no point in you writing tests for the compiler.

Code coverage is about measuring how much executable code has been exercised (whether it’s counting lines of code, functions, branches, etc). There’s nothing executable about your declaration that the attribute only applies to certain program elements - it’s just marking up the type for the compiler - so code coverage is not a relevant concept.

Correct. Measuring “did the code that returns the string get executed” is code coverage, but testing “did the string have the expected value” is simple data testing.

Thanks, but I eventually found that sample elsewhere and have finished my Unit Test.

Is it really, I have been programming for 30 years professionally. And companies that I have worked for have even done test coverages on websites using selenium, no code there, except the code we write to make sure that what is meant to be, is!

And I will say it again. If Unity spent more time writing proper Tests, maybe the current bug with Animation Transitions would not exist! Unity obviously made a significant change that broke something else, and there was no tests to discover it is now broken!

Who said anything about a string being returned?

There are such things as

private const string _invokeTestName = “TestInvoke”;

For anyone else wanting to know how to do this here is what I came up with, feel free to improve upon it.

public class MyAttributeTest
{
    private IList<AttributeUsageAttribute> attributes;

    [SetUp]
    public void Setup()
    {
        attributes = (IList<AttributeUsageAttribute>)typeof(MyAttribute).GetCustomAttributes(typeof(AttributeUsageAttribute), false);
    }

    [UnityTest]
    public IEnumerator CheckAttributeCount()
    {
        Assert.AreEqual(1, attributes.Count, "Incorrect attributes used.");
        yield return null;
    }

    [UnityTest]
    public IEnumerator CheckNoMultiple()
    {
        var attribute = attributes[0];
        Assert.IsFalse(attribute.AllowMultiple, "Allow multiple is not allowed.");
        yield return null;
    }

    [UnityTest]
    public IEnumerator InheritedIsTrue()
    {
        var attribute = attributes[0];
        Assert.IsTrue(attribute.Inherited, "Attribute must be inherited.");
        yield return null;
    }

    [UnityTest]
    public IEnumerator AttributeIsClass()
    {
        var attribute = attributes[0];
        Assert.AreEqual(AttributeTargets.Class, attribute.ValidOn, "Attribute Target can only be used on a Class.");
        yield return null;
    }

    [TearDown]
    public void TearDown()
    {
        attributes = null;
    }
}

Test coverage is not the same thing as code coverage. There are many different kinds of test coverage; code coverage is only one of them. There’s also - for example - state space coverage, environment coverage, data coverage, etc.

Anyway, I simplified your tests. There is no point having the CheckAttributeCount test because the compiler will prevent you from having multiple AttributeUsage attributes on a single attribute class. You also do not need to use UnityTest because your tests do not need to be executed across multiple frames.

public class MyAttributeTest
{
    private AttributeUsageAttribute attribute;

    [SetUp]
    public void Setup()
    {
        attribute = Attribute.GetCustomAttribute(typeof(MyAttribute), typeof(AttributeUsageAttribute), false);
    }

    [Test]
    public void CheckNoMultiple()
    {
        Assert.IsFalse(attribute.AllowMultiple, "Allow multiple is not allowed.");
    }

    [Test]
    public void InheritedIsTrue()
    {
        Assert.IsTrue(attribute.Inherited, "Attribute must be inherited.");
    }

    [Test]
    public void AttributeIsClass()
    {
        Assert.AreEqual(AttributeTargets.Class, attribute.ValidOn, "Attribute Target can only be used on a Class.");
    }
}

Are you saying that this is not a valid use case to test?

    private const string _TestInvokeMethod = "TestMethod";

    private void Awake()
    {
        Invoke(_TestInvokeMethod, 0);
    }

You could certainly write a test for “Does _TestInvokeMethod have the expected value” (though I think it’s not likely to be a very valuable test, especially given that in modern C# you’d use the nameof operator to set the constant value instead of writing a string like that). But tooling which measures ‘code coverage’ (such as Visual Studio, or JetBrains dotCover) will completely ignore your declaration of _TestInvokeMethod when calculating a coverage percentage, because there’s no executable code on that line.

That is correct you could do that, but not everyone is up to that level of expertise when they write their code.

Even though I prefer to not use Invoke, it was shown to only make a point. As CONST in this example is only one way to skin the cat, and could be use elsewhere where the change could have consequences.

But that is neither here nor there, I needed and got what I needed to test for.