c# - 在单元测试项目中获取具有属性的程序集

标签 c# unit-testing reflection

是否可以获取应用了自定义属性的所有引用程序集(在单元测试项目中)。我在成功运行的应用程序中使用了以下代码:

var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(a => a.GetCustomAttributes(false).OfType<AssemblyCategoryAttribute>().Any()).ToList();

但是 System.Web.Compilation.BuildManager 在我的测试项目中不起作用,所以我尝试了:

Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Where(a => a.GetCustomAttributes(false).OfType<AssemblyCategoryAttribute>().Any()).ToList();

但这引发了错误:

It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.

如果有人能告诉我如何做到这一点,我将不胜感激。谢谢

最佳答案

由于您正在获取当前正在执行的程序集的引用程序集,因此没有理由进行仅反射加载。 ReflectionOnlyLoad 适用于您想要查看程序集但不实际执行它们的情况。由于这些程序集正在被当前正在执行的程序集引用,因此很可能无论如何都将加载到执行上下文中。

试着做:

Assembly
    .GetExecutingAssembly()
    .GetReferencedAssemblies()
    .Select(a => Assembly.Load(a.FullName))
    .Where(a => a.
            .GetCustomAttributes(false)
            .OfType<AssemblyCategoryAttribute>()
            .Any())
    .ToList();

或者更好的是:

Assembly
    .GetExecutingAssembly()
    .GetReferencedAssemblies()
    .Select(Assembly.Load)
    .Where(a => a.IsDefined(typeof(AssemblyCategoryAttribute), false))
    .ToList();

关于c# - 在单元测试项目中获取具有属性的程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734724/

相关文章:

c# - 订阅其他项目中的 Controller 引发的事件

angularjs - 您的一些测试进行了整页重新加载 - 运行 Jasmine 测试时出错

c++ - 如何对(任意)POD C++ 结构施加词典顺序?

ruby-on-rails - Rails 4 测试用户初始化总是空白

c# - 如何在程序之前运行测试?

C# 反射 : How to get class reference from string?

reflection - Kotlin 反射 - 检查属性是否具有类型

c# - 适当类的技巧

C# 在构造期间通过 Ref 参数推断分配的成员的可空性

c# - LINQ to SQL - 在测试和开发数据库之间切换的最佳方式