Question

I'm trying to Mock the IUnityContainer using Moq 3.0

I'm getting a BadImageFormatException, but not when debugging. From the looks of it I'm not the only one that's ran into this problem.

here

And its a registered issue for Moq

here

I'm just curious if anyone has found a solution... closest I've found is a nice solution that uses RhinoMock by Roy Osherove

here

but I really like Moq! So I don't really want to have to switch to Rhino Mock but I will if I must

Thanks in advance!

Was it helpful?

Solution

You don't.

The only reason to mock the container is if you're passing it around. That's an anti-pattern.

Instead you want to compose the entire object graph at the application's entry point, or Composition Root.

If you need to create instances on the fly, use Automatic Factories.

For your tests, you can either construct the object under test and pass mock objects to the constructor or create a new container in the test and register mock objects with it.

OTHER TIPS

Have you tried mocking UnityBaseContainer or UnityContainer instead of IUnityContainer, ala this post by Rory Primrose? He is dealing with RhinoMocks but because I think the issue is related to Moq's internal use of Castle, you may be able to solve the problem this way.

Do you need a full-blown mock object? Could you get by with simply implementing a Fake? I.e., implementing a test instantiation of the IUnityContainer interface and overriding the method that you need to interact with?

I've fallen into the trap more than once in thinking that since I have a mock object library, I should use it for isolating every dependency in my system. More often than not, doing something simpler gets me the results I want with much lower frustration levels.

Because of this problem I don't mock IUnityContainer, I use a real instance of UnityContainer instead. It's not ideal but I can test registration by checking that the container can resolve types as appropriate.

You can mock and use IServiceLocator when you're using it to resolve types in your classes, or even better, use register a factory with the container and use that instead.

Are you running this on Win x64 ? Have a look at this page. It clearly suggests.

This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) does not conform to the format that is expected by the common language runtime.

Also, found this blog entry which suggests changing the compilation flag from Any CPU to x86 might help the cause. http://filips.net/archives/2008/01/17/getting-badimageformatexception-in-64-bit-windows/

Edit:

Also have a look at this SO thread. Have a look within your Build Configuration Manager as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top