How to suppress InMemoryEventId.TransactionIgnoredWarning during unit testing with a database in memory with transactions?

I use the EF Core database in memory and try to run a unit test for a method that uses transactions:

    using (var transaction = await _context.Database.BeginTransactionAsync())
    {
        _context.Update(item);
        result = await _context.SaveChangesAsync();

        // some other stuff

        transaction.Commit();
    }

However, I get this error from a test runner:

System.InvalidOperationException: Warning as an error exception for warning "InMemoryEventId.TransactionIgnoredWarning": transactions are not supported by the storage in memory. See http://go.microsoft.com/fwlink/?LinkId=800142 To suppress this exception, use the DbContextOptionsBuilder.ConfigureWarnings API. ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or when using AddDbContext in the application service provider.

How do I suppress this error?

+17
source share
2 answers

, , , :

    public MyDbContext GetContextWithInMemoryDb()
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            // don't raise the error warning us that the in memory db doesn't support transactions
            .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
            .Options;

        return new MyDbContext(options); 
    }
+43

@tomRedox, startup.cs ASP.NET Core 2.0.

services.AddDbContext<MyDbContext>(options =>
                {
                options.UseInMemoryDatabase("TestDb");
                options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
                });
+3

Source: https://habr.com/ru/post/1017402/


All Articles