EntityFrameworkCore.AutoFixture

Using the In-Memory provider

Below is the most basic usage of the library using the In-Memory provider for EF Core.

[Fact]
public void CanAddCustomers()
{
    var fixture = new Fixture().Customize(new InMemoryCustomization());
    var context = fixture.Create<TestDbContext>();

    context.Customers.Add(new Customer("John Doe"));
    context.SaveChanges();

    context.Customers.Should().Contain(x => x.Name == "John Doe");
}

This test is equivalent to the following test written using the EF Core API.

[Fact]
public async Task CanAddCustomers()
{
    // Arrange
    var builder = new DbContextOptionsBuilder<TestDbContext>()
        .UseInMemory("TestDatabase");
    var options = builder.Options;
    var context = new TestDbContext(options);
    context.Database.EnsureCreated();

    // Act
    context.Customers.Add(new Customer("Jane Smith"));
    await context.SaveChangesAsync();

    // Assert
    context.Customers.Should().Contain(x => x.Name == "Jane Smith");
}

Cheat sheet

Using custom database names

In some scenarios it might be required to use a different database (store) name than the default TestDatabase. To change the database name used by the customization, simply set the DatabaseName property to the required value. The database name set in the customization, will be used by all database contexts created by AutoFixture.

[Fact]
public async Task CanAddCustomers()
{
    // Arrange
    var fixture = new Fixture().Customize(new InMemoryCustomization {
        DatabaseName = "MyDatabase",
        UseUniqueNames = false,
    });
    var context = fixture.Create<TestDbContext>();

    // Act
    context.Customers.Add(new Customer("Jane Smith"));
    await context.SaveChangesAsync();

    // Assert
    context.Customers.Should().Contain(x => x.Name == "Jane Smith");
}

Multiple connections to same instance

In order to create multiple contexts that all connect to the same instance, ensure that the UseUniqueNames property is set to false. This will remove the unique suffix generated by default for database names.

[Fact]
public async Task CanAddCustomers()
{
    // Arrange
    var fixture = new Fixture().Customize(new InMemoryCustomization { UseUniqueNames = false });
    var context1 = fixture.Create<TestDbContext>();
    var customer = fixture.Create<Customer>();
    context1.Customers.Add(customer);
    await context1.SaveChangesAsync();

    // Act
    var context2 = fixture.Create<TestDbContext>(); // Note that we're crating a new context

    // Assert
    context2.Customers.Include(x => x.Orders).Should().BeEquivalentTo(customer);
}