EfCore.TestBed 1.0.1

dotnet add package EfCore.TestBed --version 1.0.1
                    
NuGet\Install-Package EfCore.TestBed -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="EfCore.TestBed" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EfCore.TestBed" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="EfCore.TestBed" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add EfCore.TestBed --version 1.0.1
                    
#r "nuget: EfCore.TestBed, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package EfCore.TestBed@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=EfCore.TestBed&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=EfCore.TestBed&version=1.0.1
                    
Install as a Cake Tool

EfCore.TestBed ๐Ÿงช

The ultimate EF Core testing toolkit. Write tests with real database behavior in milliseconds.

NuGet License: MIT

๐Ÿš€ Why EfCore.TestBed?

Standard InMemory EfCore.TestBed
โŒ No FK validation โœ… Real FK validation
โŒ No unique constraints โœ… Real unique constraints
โŒ No cascade delete โœ… Real cascade delete
โŒ No transactions โœ… Real transactions
โŒ No raw SQL โœ… Real SQL support

One line of code = real database testing ๐ŸŽฏ

๐Ÿ“Š Benchmarks

Database Setup

Method Mean Rank Allocated
EF Core InMemory 29 ฮผs 1 29 KB
EfCore.TestBed 1.1 ms 2 713 KB
SQLite Physical (File) 26 ms 3 734 KB

Insert Operations

Method 1 Entity 10 Entities 100 Entities 1000 Entities
EF Core InMemory 55 ฮผs 103 ฮผs 544 ฮผs 5 ms
EfCore.TestBed 1.3 ms 1.7 ms 4.7 ms 37 ms
SQLite Physical (File) 28 ms 27 ms 30 ms 63 ms

Key Insights

  • EfCore.TestBed is ~23x faster than SQLite Physical while providing real FK validation and transactions
  • For typical test scenarios (1-100 entities), EfCore.TestBed adds only 1-5ms overhead vs InMemory
  • The trade-off: ~8x slower than InMemory but with real database behavior

๐Ÿ“ฆ Installation

dotnet add package EfCore.TestBed

โšก Quick Start

using EfCore.TestBed.Core;

public class OrderTests : EfTestBase<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        context.Users.Add(new User { Id = 1, Name = "John" });
    }

    [Fact]
    public void CreateOrder_WithValidUser_Succeeds()
    {
        // Db is ready with seeded data!
        Db.Orders.Add(new Order { UserId = 1 });
        Db.SaveChanges();

        Assert.Equal(1, Db.Orders.Count());
    }

    [Fact]
    public void CreateOrder_WithInvalidUser_Fails()
    {
        Db.Orders.Add(new Order { UserId = 999 }); // User doesn't exist!

        Assert.Throws<DbUpdateException>(() => Db.SaveChanges()); // โœ… Real FK error!
    }
}

Option 2: Use Factory Method

using EfCore.TestBed.Factory;

[Fact]
public void QuickTest()
{
    using var db = TestDb.Create<MyDbContext>(ctx =>
    {
        ctx.Users.Add(new User { Name = "Test" });
    });

    Assert.Equal(1, db.Context.Users.Count());
}

Option 3: One-liner

[Fact]
public void SuperQuickTest()
{
    using var db = TestDb.Quick<MyDbContext>();
    db.Users.Add(new User { Name = "John" });
    db.SaveChanges();
}

๐Ÿ“š Features

๐Ÿงช Base Class for Tests

public class MyTests : EfTestBase<AppDbContext>
{
    // Fresh database for each test!
    
    protected override void Seed(AppDbContext context)
    {
        // Optional: seed test data
        context.Users.Add(new User { Name = "Test User" });
    }

    [Fact]
    public void MyTest()
    {
        // Db property is ready to use
        var user = Db.Users.First();
        Assert.Equal("Test User", user.Name);
    }
}

โœ… Fluent Assertions

using EfCore.TestBed.Extensions;

// Check existence
Db.ShouldHave<User>(u => u.Name == "John");
Db.ShouldNotHave<Order>(o => o.Status == "Cancelled");

// Check counts
Db.ShouldHaveCount<User>(5);
Db.ShouldHaveCount<Order>(3, o => o.Status == "Pending");

// Check save operations
Db.ShouldSaveSuccessfully();
Db.ShouldFailOnSave<DbUpdateException>();

๐Ÿ”„ Transaction Support

using EfCore.TestBed.Transactions;

// Auto-rollback after test
Db.InRollbackTransaction(ctx =>
{
    ctx.Users.Add(new User { Name = "Temp" });
    ctx.SaveChanges();
    // Rolled back automatically!
});

// Manual rollback scope
using var scope = Db.CreateRollbackScope();
Db.Users.Add(new User { Name = "Test" });
Db.SaveChanges();
scope.Rollback(); // Data is gone!

๐ŸŒฑ Easy Seeding

using EfCore.TestBed.Seeding;

// Seed single entity
var user = Db.SeedOne(new User { Name = "John" });

// Seed multiple
var users = Db.SeedMany(
    new User { Name = "John" },
    new User { Name = "Jane" }
);

// Seed with factory
var products = Db.SeedMany(10, i => new Product 
{ 
    Name = $"Product {i}",
    Price = 9.99m * i
});

// Fluent seeding
Db.Seed()
  .Add(new User { Name = "John" })
  .Add(5, i => new Order { Total = i * 10 })
  .Build();

๐Ÿ—๏ธ Shared Fixtures (xUnit)

// Define a shared fixture
public class MyDbFixture : SharedDbFixture<AppDbContext>
{
    protected override void SeedData(AppDbContext context)
    {
        context.Users.Add(new User { Name = "Shared User" });
    }
}

// Use in test class
public class MyTests : IClassFixture<MyDbFixture>
{
    private readonly AppDbContext _db;

    public MyTests(MyDbFixture fixture)
    {
        _db = fixture.CreateContext();
    }

    [Fact]
    public void Test1() => Assert.NotEmpty(_db.Users);
}

๐Ÿ“ธ Snapshots

using EfCore.TestBed.Transactions;

var snapshot = Db.CreateSnapshotManager();

// Take snapshot
snapshot.TakeSnapshot("before");

// Make changes
Db.Users.First().Name = "Changed";

// Restore
snapshot.RestoreSnapshot("before");

๐Ÿ”ง Configuration

// Custom options
public class MyTests : EfTestBase<AppDbContext>
{
    public MyTests() : base(new TestBedOptions
    {
        Provider = TestDbProvider.SqliteInMemory, // Default
        EnableSensitiveDataLogging = true,
        EnableDetailedErrors = true
    })
    {
    }
}

// Or via factory
using var db = TestDb.Create<AppDbContext>(configure: opts =>
{
    opts.Provider = TestDbProvider.SqliteInMemory;
    opts.EnableSensitiveDataLogging = true;
});

๐ŸŽฏ Complete Example

using EfCore.TestBed.Core;
using EfCore.TestBed.Extensions;
using EfCore.TestBed.Seeding;

public class OrderServiceTests : EfTestBase<AppDbContext>
{
    protected override void Seed(AppDbContext context)
    {
        // Seed test users
        context.SeedMany(
            new User { Id = 1, Name = "John", Email = "john@test.com" },
            new User { Id = 2, Name = "Jane", Email = "jane@test.com" }
        );

        // Seed products
        context.SeedMany(3, i => new Product
        {
            Id = i + 1,
            Name = $"Product {i + 1}",
            Price = 10.00m * (i + 1)
        });
    }

    [Fact]
    public void CreateOrder_WithValidData_CreatesOrderWithItems()
    {
        // Arrange
        var service = new OrderService(Db);
        
        // Act
        var order = service.CreateOrder(userId: 1, productIds: new[] { 1, 2 });
        
        // Assert
        Db.ShouldHave<Order>(o => o.UserId == 1);
        Db.ShouldHaveCount<OrderItem>(2, oi => oi.OrderId == order.Id);
        Assert.Equal(30.00m, order.Total); // 10 + 20
    }

    [Fact]
    public void CreateOrder_WithInvalidUser_ThrowsException()
    {
        var service = new OrderService(Db);

        Assert.Throws<DbUpdateException>(() => 
            service.CreateOrder(userId: 999, productIds: new[] { 1 }));
    }

    [Fact]
    public void DeleteUser_WithOrders_CascadeDeletes()
    {
        // Arrange
        var order = Db.SeedOne(new Order { UserId = 1, Total = 100 });
        
        // Act
        var user = Db.Users.Find(1)!;
        Db.Users.Remove(user);
        Db.SaveChanges();
        
        // Assert
        Db.ShouldNotHave<User>(u => u.Id == 1);
        Db.ShouldNotHave<Order>(o => o.Id == order.Id); // Cascade deleted!
    }

    [Fact]
    public async Task TransactionRollback_WorksCorrectly()
    {
        // Arrange
        var initialCount = Db.Orders.Count();

        // Act - Add order in transaction then rollback
        await Db.InRollbackTransactionAsync(async ctx =>
        {
            ctx.Orders.Add(new Order { UserId = 1, Total = 50 });
            await ctx.SaveChangesAsync();
        });

        // Assert - Count should be unchanged
        Assert.Equal(initialCount, Db.Orders.Count());
    }
}

๐Ÿ“‹ Requirements

  • .NET 8.0+
  • EF Core 8.0+

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

๐Ÿ“„ License

MIT License - feel free to use in your projects!


Made with โค๏ธ for the .NET community

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 83 2/1/2026
1.0.0 82 2/1/2026