huysentruitw / entity-framework-core-mock

Easy Mock wrapper for mocking EFCore5 DbContext and DbSet using Moq or NSubstitute
MIT License
132 stars 24 forks source link
csharp dbcontext dbset dotnet-standard dotnetcore efcore efcore5 entity-framework-core mock moq net50 nsubstitute unit-testing

EntityFrameworkCoreMock

Build status

Easy Mock wrapper for mocking EntityFrameworkCore 5 (EFCore5) DbContext and DbSet in your unit-tests. Integrates with Moq or NSubstitute.

😢 Are you still stuck on EF Core 3.1? No worries, just visit this repository.

😮 Wait, did you say EF6? You really should get worried! Anyway, visit this repository.

Get it on NuGet

Moq integration

PM> Install-Package EntityFrameworkCoreMock.Moq

NSubstitute integration

PM> Install-Package EntityFrameworkCoreMock.NSubstitute

Supports

TODO

For the Moq version, you can use all known Moq features, since both DbSetMock and DbContextMock inherit from Mock<DbSet> and Mock<DbContext> respectively.

Example usage

public class User
{
    [Key, Column(Order = 0)]
    public Guid Id { get; set; }

    public string FullName { get; set; }
}

public class TestDbContext : DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<User> Users { get; set; }
}

public class MyTests
{
    [Fact]
    public void DbSetTest()
    {
        var initialEntities = new[]
            {
                new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" },
                new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" },
            };

        var dbContextMock = new DbContextMock<TestDbContext>(DummyOptions);
        var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, initialEntities);

        // Pass dbContextMock.Object to the class/method you want to test

        // Query dbContextMock.Object.Users to see if certain users were added or removed
        // or use Mock Verify functionality to verify if certain methods were called: usersDbSetMock.Verify(x => x.Add(...), Times.Once);
    }
}

public DbContextOptions<TestDbContext> DummyOptions { get; } = new DbContextOptionsBuilder<TestDbContext>().Options;