编程语言
首页 > 编程语言> > c# – 如何伪造Assembly.LoadFile和Assembly.GetTypes?

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

作者:互联网

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

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是一个抽象类吗?

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

解决方法:

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

@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,unit-testing,visual-studio-2013,microsoft-fakes
来源: https://codeday.me/bug/20190623/1275457.html