Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getting the mocked instance created with Moq throw a System.BadImageFormatException?

This question may be related to another question and it certainly results with a System.BadImageFormatException. Maybe it's the same thing but exposed differently?

I have the following the code:

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>;
}

Then I have a test that mocks IFooRepo using Moq like so:

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

The above code runs fine except when debugging the test with Visual Studio 2008. When I step over the above line a System.BadImageFormatException is thrown from System.Reflection.Emit via Castle.DynamicProxy. Could this be similar to something Ayende Rahien posted?

Now the workaround is to implement a fake for IFooRepo but I'm curious as to why a bad image is generated for this kind of scenario and is there a fix? Is System.Reflection.Emit buggy? Or am I missing something obvious in my own code?

EDIT: Posted the incorrect signature for GetFoo(). Corrected the signature to GetFoo<T, F>(), which correctly reproduces the problem. With the GDR installed this problem persists.

EDIT: It seems that if the constraint on F includes type parameter T BadImageFormatException is raised. But I change it to, say where F : class, new(), then everything works as expected.

like image 284
Jonathon Watney Avatar asked Nov 05 '22 21:11

Jonathon Watney


1 Answers

FWIW, I agree that Ayende's post explains this behavior, and that it only happens when constraints on one generic parameter reference another. I encounter it, too, with the GDR, and have adopted the same workaround of hand-coded fakes.

like image 141
Mark Knell Avatar answered Nov 15 '22 09:11

Mark Knell