How to add unit tests with SQLite InMemory with IOptions<OperationalStoreOptions> operationalStoreOptions?

Viewed 54

I have a project which currently uses a generic repository.

I want to rewrite it and make it use the EF context directly.

For the unit tests I want to use SQLite. In the example here - I see how to provide the DbContextOptions. But how can I provide the second parameter - IOptions, through SQLite?

  public ApplicationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
    {
    }
 
public class SqliteInMemoryItemsControllerTest : ItemsControllerTest, IDisposable 
{
     private readonly DbConnection _connection;

     public SqliteInMemoryItemsControllerTest()
    : base(
        new DbContextOptionsBuilder<ItemsContext>()
            .UseSqlite(CreateInMemoryDatabase())
            .Options)
{
    _connection = RelationalOptionsExtension.Extract(ContextOptions).Connection;
}

private static DbConnection CreateInMemoryDatabase()
{
    var connection = new SqliteConnection("Filename=:memory:");

    connection.Open();

    return connection;
}

public void Dispose() => _connection.Dispose();

}

1 Answers

You need to create your own IOptions<OperationalStoreOptions> class implementation, then pass an instance to the constructor>

public class MyOperationalStoreOptions : IOptions<OperationalStoreOptions> {
    public OperationalStoreOptions Value => new OperationalStoreOptions() {
        DeviceFlowCodes = new TableConfiguration("DeviceCodes"),
        EnableTokenCleanup = false,
        PersistedGrants = new TableConfiguration("PersistedGrants"),
        TokenCleanupBatchSize = 100,
        TokenCleanupInterval = 3600,
    };
}

Once defined the above class, you can create your DbContext with something like (not exactly your code, but similar):

var options = SqliteInMemory.CreateOptions<ItemsContext>();
var context = new ItemsContext(options, new MyOperationalStoreOptions())
Related