问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/35063399/all-unit-tests-throwing-badimageformatexception-with-moq