c# - 我如何伪造 Assembly.LoadFile 和 Assembly.GetTypes?

标签 c# unit-testing visual-studio-2013 microsoft-fakes

我正在努力伪造这两行代码:

Assembly asm = Assembly.LoadFile(fileName);
Type[] asmTypes = loggerAssembly.GetTypes();

当我键入 System.Reflection.ShimAssembly 时,没有 ShimAssembly 这样的类型,例如 System.IO.ShimFile 但只有一个 StubAssembly

我可以重构代码并使用像 LoadAssemblyAndGetTypes 这样的静态辅助方法来完成它,但这似乎是一个不必要的解决方法。我更喜欢官方解决方案。

如果它只是这样工作:

var shimAsm = System.Reflection.Fakes.ShimAssembly.LoadFile = (fileName) => 
{ 
   return ???
}; 

var types = shimAsm.GetTypes = () => 
{ 
   return new Type[] { new object() };
};

为什么它适用于 System.IO.File 而不适用于 System.Reflection.Assembly。这是因为 Assembly 是一个抽象类吗?


在我的单元测试中,我想检查我的程序集加载器是否正确检查加载的程序集是否包含实现某些接口(interface)的类型,以便稍后实例化它们。

最佳答案

我想我找到了答案,但看起来不太好:

@Patrick Tseng - Visual Studio 团队 - 写在Shim mscorlib and system limitations :

...we DO have a list of type we purposely not allowing them to be shimmed. Reason being that it could potentially cause recurisvely calling into your detour delegate from CLR runtime itself. E.g If CLR runtime uses a type in System.Reflection during runtime and you happen to detour functions in this type. You might end up causing expected behavior since runtime behavior will totally be changed.

In short, we don't shim value type, System.Reflection., System.Runtime., XamlGeneratedNamespace, and a few other types which we deem is important and will not shim them.

所以毕竟我似乎需要保留静态辅助方法。

关于c# - 我如何伪造 Assembly.LoadFile 和 Assembly.GetTypes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626228/

相关文章:

C# ffmpeg 无法加载 dll avcodec

c# - 根据 Item 长度拆分 List<T>

azure - 无法注册 Azure - "We were unable to verify your account"

visual-studio - 在解决方案中的新项目中安装 nuget 包,其中包已用于现有项目

c# - 如何通过 C# 在 Excel 中将公式值解析为文本

c# - Page.FindControl 为 DIV 返回 null

java - 参数化 JUnit+JUnitParams 测试不适用于具有

c# - 在单元测试中进行多次调用而不使用 for 循环

perl - 如何使用 Test::DBIx::Class 正确加载测试套件的装置?

visual-studio - 将项目(在源代码控制下)移动到不同的文件夹