HamedFathi
HamedFathi

Reputation: 3969

How to write unit test for an extension method that contains Assembly class?

I have an extension method as follows:

public static partial class Extensions
{
    public static T GetAttribute<T>(this Assembly @this) where T : Attribute
    {
        object[] configAttributes = Attribute.GetCustomAttributes(@this, typeof (T), false);

        if (configAttributes != null && configAttributes.Length > 0)
        {
            return (T) configAttributes[0];
        }

        return null;
    }
}

My question is how should I write a unit test for this scenario? Can anyone guide me?

Upvotes: 0

Views: 496

Answers (1)

JHBonarius
JHBonarius

Reputation: 11261

Assembly is just a class. A rather abstract one actually. You can derive from it.

class MockAssembly : Assembly {}

However, this is not enough, as Attribute.GetCustomAttributes(Assembly, Type, Boolean) will make a call to Assembly.GetCustomAttributes(Type, bool), which is a virtual method, so you need to override that. For example:

class MockAttribute : Attribute { }

class MockAssembly : Assembly
{
    public override object[] GetCustomAttributes(Type attributeType, bool inherit)
    {
        return new[] { new MockAttribute() };
    }
}

You can now test:

var assembly = new MockAssembly();
var att = Attribute.GetCustomAttributes(assembly, typeof(MockAttribute), false);
Console.WriteLine(att.Length);

will return: 1

Upvotes: 1

Related Questions