I have 3 projects in my solution (ASP.NET MVC, Unit Test, Class library). I want to unit test a method in a class of the class library. This class uses system.data.sqlclient
.
When I try to run the unit test this error shows:
System.BadImageFormatException: Could not load file or assembly 'System.Data.SqlClient, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) ---> System.BadImageFormatException: Cannot load a reference assembly for execution."
I have checked the build tab for all three projects: they are all set to Any CPU
. I have tried reinstalling the NuGet package in the Class Library. I have checked all .csproj
Class library .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MySql.Data" Version="8.0.18" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Data.SqlClient">
<HintPath>..\..\..\..\..\..\..\..\..\..\Program Files\dotnet\sdk\NuGetFallbackFolder\system.data.sqlclient\4.5.1\ref\netcoreapp2.1\System.Data.SqlClient.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
I had the same issue. My solution consisted of:
Upon adding a test method to the Unit Test which would use the Database, I received the error:
Test method UnitTests.DatabaseTests.TestFileStorage threw exception: System.BadImageFormatException: Could not load file or assembly 'System.Data.SqlClient, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Reference assemblies should not be loaded for execution. They can only be loaded in the Reflection-only loader context. (Exception from HRESULT: 0x80131058) ---> System.BadImageFormatException: Cannot load a reference assembly for execution.
I resolved this by using NuGet to add System.Data.SqlClient directly to my Unit Test project:
I think the root of my issue is that the version of SqlClient used by my Database project differed from the default one expected by the Unit Test project, which could not be found. Explicitly installing SqlClient into the Unit Test project worked around that issue. I'm not sure what determines which version my Unit Test project would look for.
User contributions licensed under CC BY-SA 3.0