繁体   English   中英

如何为包含 Assembly 类的扩展方法编写单元测试?

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

我有一个扩展方法如下:

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;
    }
}

我的问题是我应该如何为这种情况编写单元测试? 谁能指导我?

Assembly只是一个类。 实际上是一个相当抽象的。 你可以从中得到。

class MockAssembly : Assembly {}

但是,这还不够,因为Attribute.GetCustomAttributes(Assembly, Type, Boolean)将调用Assembly.GetCustomAttributes(Type, bool) ,这是一个虚拟方法,因此您需要覆盖它。 例如:

class MockAttribute : Attribute { }

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

您现在可以测试:

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

将返回:1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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