【问题标题】:Why does getting the mocked instance created with Moq throw a System.BadImageFormatException?为什么获取使用 Moq 创建的模拟实例会引发 System.BadImageFormatException?
【发布时间】:2010-10-26 19:29:24
【问题描述】:

这个问题可能与another 问题有关,它肯定会导致 System.BadImageFormatException。也许是一样的东西,但暴露的不同?

我有以下代码:

public interface IFoo<T> where T : class, new() {
  T FooMethod(object o);
}

public interface IFooRepo {
  F GetFoo<T, F>() where T : class, new() where F : IFoo<T>;
}

然后我有一个使用 Moq 模拟 IFooRepo 的测试,如下所示:

var instance = new Mock<IFooRepo>().Object;

除了使用 Visual Studio 2008 调试测试时,上述代码运行良好。当我越过上述行时,System.BadImageFormatException 通过 Castle.DynamicProxy 从 System.Reflection.Emit 引发。这可能类似于something Ayende Rahien 发布的内容吗?

现在的解决方法是为 IFooRepo 实现一个假的,但我很好奇为什么会为这种场景生成一个坏图像并且有解决办法吗? System.Reflection.Emit 有问题吗?还是我在自己的代码中遗漏了一些明显的东西?

编辑:为 GetFoo() 发布了不正确的签名。将签名更正为 GetFoo(),它正确地重现了问题。安装 GDR 后,此问题仍然存在。

编辑:似乎如果对 F 的约束包括类型参数 T BadImageFormatException 就会引发。但我将其更改为 where F : class, new(),然后一切正常。

【问题讨论】:

    标签: debugging moq reflection.emit castle-dynamicproxy


    【解决方案1】:

    FWIW,我同意 Ayende 的帖子解释了这种行为,并且只有当一个通用参数的约束引用另一个通用参数时才会发生这种情况。我在 GDR 中也遇到过这种情况,并且采用了与人工编码的伪造品相同的解决方法。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 我安装了 .NET 3.5 SP1。不知道是否安装了 GDR。我怎么知道?您是如何将 Ayende 的帖子与 GDR 下载页面联系起来的?在发布我的问题之前,我已经看过 Ayende 的帖子,但没有看到对 GDR 的提及。哦,谢谢你的链接顺便说一句,我很快就会检查出来。
      • Scott Hanselman 在页面底部附近找到如何确定是否安装了 GDR。 hanselman.com/blog/NET35SP1GDRIsAvailableToDownload.aspx
      • GDR 已在我的案例中应用。然后我发现我发布了错误的代码 sn-ps。我已经更正了问题中的 sn-ps。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 1970-01-01
      • 2013-07-18
      相关资源
      最近更新 更多