SQLite is frequently used in .NET applications that need a local database without a separate database server. It is a practical choice for desktop software, command-line tools, background services, and applications that work offline.

A common testing approach is to use an in-memory SQLite database. It is fast, easy to create, and does not require managing database files. For many repository and service tests, this is sufficient.

However, an in-memory database does not behave exactly like a file-based database. It does not reproduce every condition involving file paths, file permissions, multiple connections, WAL files, process restarts, or database replacement.

When an application uses SQLite as persistent local storage, testing only against an in-memory database can leave important problems undiscovered.

This article explains how to test SQLite-based .NET applications with temporary database files and realistic file-system scenarios.

Why In-Memory Tests Are Not Always Enough

Consider a repository that opens a SQLite connection for every operation.

An in-memory database created with the following connection string belongs to the connection that opened it:

Code
var connectionString =
    "Data Source=:memory:";

If the connection closes, the database disappears. A new connection normally creates a different in-memory database.

This behavior can hide problems in applications that rely on a persistent file.

A file-based database supports scenarios that are difficult to reproduce with a simple in-memory connection:

  • Closing and reopening the database.

  • Sharing the database between independent connections.

  • Testing WAL mode and checkpoint behavior.

  • Testing database creation in application-specific directories.

  • Testing file permissions and access failures.

  • Verifying backups and restore operations.

  • Testing migrations against older database files.

In-memory databases remain useful, but they should not be the only test environment for an application that uses file-based SQLite in production.

Creating a Temporary Database for Each Test

A good starting point is to create a unique temporary directory for each test.

C#
public sealed class TemporarySqliteDatabase : IDisposable
{
    public string DirectoryPath { get; }
    public string DatabasePath { get; }
    public string ConnectionString { get; }

    public TemporarySqliteDatabase()
    {
        DirectoryPath = Path.Combine(
            Path.GetTempPath(),
            $"sqlite-tests-{Guid.NewGuid():N}");

        Directory.CreateDirectory(DirectoryPath);

        DatabasePath =
            Path.Combine(DirectoryPath, "test.db");

        ConnectionString =
            $"Data Source={DatabasePath}";
    }

    public void Dispose()
    {
        try
        {
            if (Directory.Exists(DirectoryPath))
            {
                Directory.Delete(
                    DirectoryPath,
                    recursive: true);
            }
        }
        catch (IOException)
        {
            // Record cleanup failure in the test infrastructure.
            throw;
        }
    }
}

Each test receives a separate database file, which prevents data from one test from affecting another.

The cleanup code removes the temporary directory after the test completes. All connections must be closed before cleanup. Otherwise, file locks or operating-system file sharing rules may prevent deletion.

For asynchronous test frameworks, implement IAsyncDisposable if the test setup or cleanup performs asynchronous work.

Testing Repository Operations

Suppose an application has a TaskRepository that stores task records.

A test can create a temporary database, initialize the schema, insert a record, close the connection, and then open a new connection to verify persistence.

C#
[Fact]
public void TaskIsAvailableAfterReopeningDatabase()
{
    using var database =
        new TemporarySqliteDatabase();

    using (var connection =
        new SqliteConnection(database.ConnectionString))
    {
        connection.Open();

        using var createCommand = connection.CreateCommand();

        createCommand.CommandText =
            """
            CREATE TABLE Tasks
            (
                Id INTEGER PRIMARY KEY,
                Title TEXT NOT NULL
            );
            """;

        createCommand.ExecuteNonQuery();

        using var insertCommand = connection.CreateCommand();

        insertCommand.CommandText =
            """
            INSERT INTO Tasks (Id, Title)
            VALUES (1, 'Review deployment plan');
            """;

        insertCommand.ExecuteNonQuery();
    }

    using var reopenedConnection =
        new SqliteConnection(database.ConnectionString);

    reopenedConnection.Open();

    using var queryCommand =
        reopenedConnection.CreateCommand();

    queryCommand.CommandText =
        "SELECT Title FROM Tasks WHERE Id = 1;";

    string? title =
        queryCommand.ExecuteScalar()?.ToString();

    Assert.Equal("Review deployment plan", title);
}

This test verifies that the record remains available after the original connection closes.

In a real application, schema creation should be performed through the same migration or initialization service used by the application. Tests should avoid creating a separate schema that differs from production.

Testing Database Migrations

Migration tests should begin with a database that represents an older application version.

For example, create a version-one database with a Tasks table containing only the original columns. Insert representative records, set user_version to one, and execute the current migration runner.

After the migration completes, verify that:

  • The new columns exist.

  • Existing records are preserved.

  • Default values are correct.

  • Required indexes exist.

  • The database version matches the latest migration.

  • Running the migration runner again does not change the result.

Testing only a new database is not enough. A fresh database follows a different path from an existing installation that needs an upgrade.

Also test a migration that fails. Confirm that its transaction is rolled back and that the database version does not incorrectly advance.

Testing WAL Mode With Multiple Connections

WAL mode is often used when an application has several readers and occasional writers.

A file-based database allows tests to open multiple independent connections to the same database.

The following example enables WAL mode:

C#
using var connection =
    new SqliteConnection(connectionString);

connection.Open();

using var command = connection.CreateCommand();

command.CommandText =
    "PRAGMA journal_mode=WAL;";

string? mode =
    command.ExecuteScalar()?.ToString();

Assert.Equal(
    "wal",
    mode,
    ignoreCase: true);

A separate test can open one connection for reading and another for writing. It can verify the application's expected behavior when a reader has an active transaction while another connection commits a change.

Do not assume that WAL mode allows multiple simultaneous writers. SQLite still serializes write transactions. Tests should verify how the application handles busy or locked conditions rather than expecting all writes to proceed concurrently.

Testing Busy and Locked Database Conditions

Database locking is one of the most important scenarios to test in an application that uses multiple connections or processes.

A test can hold a write transaction open on one connection and attempt another write through a separate connection.

PowerShell
using var first =
    new SqliteConnection(connectionString);

using var second =
    new SqliteConnection(connectionString);

first.Open();
second.Open();

using var create = first.CreateCommand();

create.CommandText =
    """
    CREATE TABLE IF NOT EXISTS Items
    (
        Id INTEGER PRIMARY KEY,
        Name TEXT NOT NULL
    );
    """;

create.ExecuteNonQuery();

using var transaction =
    first.BeginTransaction();

using var insertFirst = first.CreateCommand();

insertFirst.Transaction = transaction;
insertFirst.CommandText =
    "INSERT INTO Items (Name) VALUES ('First');";

insertFirst.ExecuteNonQuery();

At this point, the first connection has an uncommitted write transaction. A second connection attempting to write may wait or fail depending on its timeout and the database configuration.

A complete test should configure a short timeout and assert the expected behavior. It should also roll back or dispose the first transaction so the database is not left locked for later tests.

Avoid tests that depend on arbitrary sleeps. Use explicit transaction control and bounded timeouts so the result is repeatable.

Testing Database Backups and Restores

Backup functionality should be tested using a real database file.

A useful test sequence is:

  1. Create a temporary database.

  2. Insert several records.

  3. Create a backup using the application's backup service.

  4. Validate the backup.

  5. Open the backup using a new connection.

  6. Verify that expected records are present.

For example, the backup can be created with Microsoft.Data.Sqlite's BackupDatabase method:

C#
using var source =
    new SqliteConnection(sourceConnectionString);

using var destination =
    new SqliteConnection(backupConnectionString);

source.Open();
destination.Open();

source.BackupDatabase(destination);

The test should then open the backup in read-only mode and query its contents.

Also test failure scenarios, such as an invalid destination directory or a backup file that cannot be opened. The application should report the failure and preserve the original database.

Testing File Permissions and Invalid Paths

An application may work correctly on a developer's machine but fail when installed in a restricted directory.

For example, a database stored under a protected application installation directory may be readable but not writable by a standard user.

Tests should verify that the application uses an appropriate writable data directory and handles access failures clearly.

Useful scenarios include:

  • A database directory that does not exist.

  • A path that points to a directory instead of a file.

  • A destination directory without write permission.

  • A database file opened in read-only mode.

  • A temporary directory that is removed before the operation completes.

  • A database file that is unavailable because another process holds an incompatible lock.

Permission tests can behave differently across Windows, Linux, and macOS. Avoid relying on one operating system's permission model when the application supports several platforms.

Testing Multiple Processes

Multiple connections inside one test process are useful, but they do not reproduce every multi-process scenario.

If the application supports more than one process accessing the same database, consider a separate integration test that starts two instances of a small test executable.

Each process should open the same database file and perform a controlled operation. The test can verify that:

  • Both processes can read committed data.

  • Write operations follow the expected locking behavior.

  • Busy timeouts are handled.

  • Processes close their connections correctly.

  • The database can be reopened after both processes exit.

This kind of test is slower than an ordinary repository test, so it should be used for important concurrency and lifecycle scenarios rather than every individual query.

SQLite WAL mode also has deployment limitations. In particular, WAL relies on shared memory coordination and is not suitable for every network file-system arrangement. Test the actual storage environment used by the application.

Keeping File-Based Tests Reliable

File-based tests introduce cleanup and isolation concerns. A test suite should follow a consistent set of rules.

  • Give each test a unique temporary directory.

  • Keep database files outside the source and installation directories.

  • Close every connection before deleting the database.

  • Avoid sharing one writable database between unrelated tests.

  • Use bounded timeouts for locking tests.

  • Keep test data small but representative.

  • Use the application's actual migrations and repository code.

  • Run important file-system tests on every supported operating system.

  • Preserve diagnostic information when cleanup or database operations fail.

If a test fails, its temporary database can be useful for investigation. Some test environments can preserve the temporary directory when a failure occurs and delete it only after successful execution.

Common Testing Mistakes

One common mistake is using a single in-memory connection for every test. This makes tests fast but does not verify persistence, file access, or database lifecycle behavior.

Another mistake is sharing one database file between parallel tests. Even if the tests use different tables, schema changes and write transactions can interfere with each other.

Tests can also become unreliable when they use fixed delays to wait for database locks or background operations. Prefer explicit synchronization, transaction control, and bounded timeouts.

Finally, a test that verifies only successful queries does not provide enough confidence in a persistent storage component. Failure handling, migrations, backups, locking, and cleanup are all part of the database behavior that users depend on.

Summary

In-memory SQLite databases are useful for fast unit tests, but they do not reproduce every condition that a file-based application encounters. Temporary database files make it possible to test persistence, migrations, WAL behavior, backup and restore operations, file permissions, and multiple connections.

A reliable test suite should use isolated database files, close connections carefully, and verify both normal operations and failure scenarios. Applications that support multiple processes should also test the behavior of independent processes against the same database.

These tests take more time than simple in-memory tests, but they reveal problems that might otherwise appear only after deployment. For applications that depend on local SQLite storage, realistic file-system testing is an important part of production readiness.