【问题标题】:Simulate ReflectionTypeLoadException being thrown during domain types collection模拟在域类型收集期间抛出的 ReflectionTypeLoadException
【发布时间】:2016-02-13 23:02:29
【问题描述】:

我能够从当前域中收集所有类型调用这个:

var types = AppDomain.CurrentDomain
    .GetAssemblies()
    .SelectMany(x => x.GetTypes())
    .ToList();

假设没有抛出异常。不过,我想模拟ReflectionTypeLoadException 在该过程中被抛出。

如何破坏我的代码中的任何现有类型以使此异常发生?

或者,如果无法实现上述目标,我如何动态创建具有某些损坏类型的人工程序集来感染域(当前或新)?特别是,我正在寻找有关以下Infect() 方法实施的一些线索:

Infect(AppDomain.CurrentDomain); // inject corrupted type
try
{
    var types = AppDomain.CurrentDomain
        .GetAssemblies()
        .SelectMany(x => x.GetTypes())
        .ToList();
}
catch (ReflectionTypeLoadException e)
{
    // done
}

【问题讨论】:

  • 是为了单元测试吗?

标签: c# .net reflection .net-assembly appdomain


【解决方案1】:

这是用于单元测试的目的,就像你在 cmets 中回答我的问题时所说的那样。

那么为什么不将获取当前 AppDomain 程序集中所有类型的逻辑移动到一个实现如下代码的接口的类:

public interface ITypeProvider
{
    ICollection<Type> GetTypes();
}

public class AppDomainTypeProvider : ITypeProvider
{
    public ICollection<Type> GetTypes()
    {
        return AppDomain.CurrentDomain
            .GetAssemblies()
            .SelectMany(x => x.GetTypes())
            .ToList();
    }
}

public class MyAwesomeClassThatUseMyTypeProvider
{
    private readonly ITypeProvider _typeProvider;

    public MyAwesomeClassThatUseMyTypeProvider(ITypeProvider typeProvider)
    {
        _typeProvider = typeProvider;
    }

    public void DoSomething()
    {
        var types = _typeProvider.GetTypes();
    }
}

在调用逻辑的代码中使用此接口。

然后为您的单元测试模拟异常 ReflectionTypeLoadException,只需使用 Moq 或任何等效项,如下所示(我使用 Nunit 进行断言):

var typeProviderMoq = new Mock<ITypeProvider>();
typeProviderMoq.Setup(p => p.GetTypes()).Throws(new ReflectionTypeLoadException(new [] { typeof(string)}, new[] { new Exception("test purpose") }));
var myAwesomeClass = new MyAwesomeClassThatUseMyTypeProvider(typeProviderMoq.Object);

Assert.Throws<ReflectionTypeLoadException>(() => myAwesomeClass.DoSomething());

【讨论】:

  • 谢谢(+1),我很欣赏您的解决方案非常正确,我很可能会改用这种方法,但是我仍然想知道我问的技巧是否大约是可能的。
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-22
相关资源
最近更新 更多