DllNotFoundException even though the dll exists

-3

I have a unit test which fails with this exception:

System.DllNotFoundException: Unable to load DLL 'sqlite3' or one of its dependencies: A dynamic link library (DLL) initialization routine failed. (0x8007045A)

My project has a lib folder containing sqlite-binaries and sqlite-net-extensions and the tests.csproj file contains:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="copy  $(SolutionDir)lib\sqlite-binaries\x64\sqlite3.dll $(OutDir)sqlite3.dll" />
</Target>

I see the tests run in C:\Users\me\Documents\git\My.API\My.Api.Tests\bin\Debug\netcoreapp3.1 and I can see sqlite3.dll has been copied to here. I did notice that my test references J:\dev\incision\VRNow\Debug-Files\vrnowapi-sync-pcl.db which doesn't exist. Is's used here:

var databasePathProvider = new StringDatabasePathProvider(@"J:\dev\incision\VRNow\Debug-Files\vrnowapi-sync-pcl.db");
using var api = new SyncingVRNowAPI(baseApi, dataSyncController, databasePathProvider);

The second line is the line that shows the error.

sqlite3.dll is in the referenced folder. Why would the test fail with this exception? Is it possible that the error is misleading and that the issue is the missing db?

c#
.net
visual-studio
sqlite
asked on Stack Overflow Feb 2, 2021 by runnerpaul • edited Feb 3, 2021 by runnerpaul

1 Answer

0

The problem is that tests might not always run in $(OutDir).

You can check that easily with Environment.CurrentDirectory from within a test, it may not match.

An example of such case would be with Live Unit Testing.

The fix is to ensure that your built project deploys its dependencies wherever it's build to.

Edit:

I've tried the following and it just works here:

The package: https://www.nuget.org/packages/System.Data.SQLite

Keep in mind that not all packages are created equal, this one just works in this case.

using System;
using System.Data.SQLite;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void TestMethod1()
        {
            TestContext.WriteLine(Environment.CurrentDirectory);

            var cs = "Data Source=:memory:";
            var stm = "SELECT SQLITE_VERSION()";

            using var con = new SQLiteConnection(cs);
            con.Open();

            using var cmd = new SQLiteCommand(stm, con);
            var version = cmd.ExecuteScalar().ToString();

            TestContext.WriteLine($"SQLite version: {version}");
        }
    }
}

enter image description here

answered on Stack Overflow Feb 3, 2021 by aybe • edited Feb 3, 2021 by aybe

User contributions licensed under CC BY-SA 3.0