Fixing SQLite errors in Xunit tests

This quick reference post shows how to fix the following error:

   System.TypeInitializationException : The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
---- System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
-------- System.Exception : Library e_sqlite3 not found

The scenario where this happens is something like:

The solution is to add a file named xunit.runner.json to your test project:

{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"shadowCopy": false
}

Be sure to set the file properties to Content and Copy if newer so that it actually ends up in the output folder along with the binaries for your test project.

I had this issue and it took a while to find the solution, so I thought I'd share it here with you.

In my situation, I had a test project that targeted:

  <PropertyGroup>
<TargetFrameworks>net461;netcoreapp2.1;netcoreapp3.1;net5.0;net6.0</TargetFrameworks>

and I was referencing Entity Framework:

  <ItemGroup Condition=" '$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0-*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0-*" />
<PackageReference Include="System.Text.Json" Version="6.0.0-*" />

</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.0" />
<PackageReference Include="System.Text.Json" Version="4.7.2" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' != 'net5.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.17" />
<PackageReference Include="System.Text.Json" Version="4.7.2" />
</ItemGroup>

When running my tests in Visual Studio, everything ran fine. However, when running from the command line, I see the dreaded Library e_sqlite3 not found.

I found quite a few hits when searching, but it was the advice above which came from this thread that fixed it.

Hope this helps!

🙏🙏🙏

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please 🦋 ping me on Bluesky! 🦋

Leave a comment

Comments are moderated, so there may be a short delays before you see it.

Published