Reputation: 3969
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
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