Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All unit tests throwing BadImageFormatException with Moq?

I'm currently in the process of increasing code coverage on our software products and have ran into an issue; all of my unit tests (when compiled using 'Any CPU') are failing due to throwing a 'BadImageFormatException'.

This exception can be circumvented by building the solution using 'x86' instead of 'Any CPU', however the requirements are such that we need to be able to run them using Any CPU/x64 bit.

All unit tests involving Moq follow pretty much the same format:

[TestMethod]
public void GetProduct_ValidId_ProductReturned()
{
    //Setting up the object
    Product prod = new Product();
    prod.ID = 7;
    prod.Name = "Test";

    //Create the mocks
    var mockProductRepo = new Mock<IRepository<Product>>();
    var testDb = new Mock<IUnitOfWork>();

    //Setup what the repo needs to return, in this case it's a Product
    mockProductRepo.Setup(m => m.getByID(7)).Returns(prod); 

    //Setup what the database needs to return, in this case it's our repo which we've already setup
    testDb.SetupGet(m => m.ProductRepo).Returns(mockProductRepo.Object);

    //Run the test
    Product returnedProd = ProductHelper.getProduct(testDb.Object, 7);
    Assert.IsNotNull(returnedProd);
}

I can confirm that this test is successful when it is built using x86. Does anyone have any ideas on how I can get Moq to play nice when built using 'Any CPU'?

As an aside I can also confirm that all my projects in the solution are build using the same value ('Any CPU'). I'm using Moq v4.0.

EDIT: Here is the full exception: Test method [ProductName and the method called] threw exception: System.BadImageFormatException: Could not load file or assembly '[Product name], Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

like image 426
Novastorm Avatar asked Jan 28 '16 13:01

Novastorm


2 Answers

Ok so after some digging I finally found out what the issue was. Even if you select 'Build' and then 'Configuration Manager' from the toolbar and see that Platform is set to 'Any CPU' (as was my case), what I hadn't done was check the Target Platform in the project.

To check the Target Platform you need to do the following:

  • Right-click your project and select 'Properties'
  • Select the 'Build' tab on the left
  • Ensure that the Target Platform of your test project matches that of the project you are testing

In my case my test was targeting 'Any CPU' but my live project was targeting 'x64'. This is what was causing the issue.

like image 195
Novastorm Avatar answered Sep 28 '22 05:09

Novastorm


This can be caused by missing project or other assembly references. Try making sure you have project references for all the projects in your solution.

This post has a further example.

like image 40
chief7 Avatar answered Sep 28 '22 04:09

chief7