huysentruitw / entity-framework-core-mock

Easy Mock wrapper for mocking EFCore5 DbContext and DbSet using Moq or NSubstitute

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to create DbSetMock by generic class

outworkAnton opened this issue · comments

I've an base abstract generic class that implements initial logic and configuration of inherited test classes. But can't create DbSetMock with runtime error when test runs "System.InvalidCastException : Unable to cast object of type System.Linq.Expressions.InstanceMethodCallExpression0 to type System.Linq.Expressions.MemberExpression."

public abstract class BaseServiceTests<TEntity, TService, TRepository> where TEntity : class
    {
        protected readonly TService Service;

        protected BaseServiceTests()
        {
            var config = new MapperConfiguration(mc => mc.AddMaps(Assembly.GetAssembly(typeof(TService))));
            var mapper = config.CreateMapper();
            
            var contextOptions  = new DbContextOptionsBuilder<FakeDbContext>().Options;
            var fakeDbContext = new DbContextMock<FakeDbContext>(contextOptions);
            var entities = fakeDbContext.Object.GetType()
                .GetProperties()
                .Where(info => info.PropertyType == typeof(IEnumerable<TEntity>))
                .Select(info => info.GetValue(fakeDbContext.Object) as IEnumerable<TEntity>)
                .FirstOrDefault();
            fakeDbContext.CreateDbSetMock(x => x.Set<TEntity>(), entities); // Error

            var repository = (TRepository)Activator.CreateInstance(typeof(TRepository), fakeDbContext.Object);
            Service = (TService)Activator.CreateInstance(typeof(TService), repository, mapper);
        }
    }

We no longer support EF Core 2.x as this library is now targeting EF Core 5. Closing this issue.

commented

I think the issue can be opened again.
I have an identical problem with EF Core 5 and there is probably no way to create DbSets generically.

@huysentruitw Do you know of any workaround to achieve this?

Version 2.3 of the NuGet package (currently building) should fix this issue.

Also, don't forget to star this repository 🤩