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

Unable to mock users when deriving from IdentityDbContext #15

Closed gopala000 closed 5 years ago

gopala000 commented 5 years ago

My db context is derived from EF Core's IdentityDbContext: public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>

When I tried to mock like in your sample:

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

I get the exception, System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: x => x.Users

Is there a workaround? (I understand that it is coming from Moq. IdentityDbContext is part of EF Core that I can't make Users as virtual)

huysentruitw commented 5 years ago

I'm afraid that is not possible. However, you probably shouldn't use those tables directly as the preferred way is to use the UserManager<T> and SignInManager<T>, in which case you can mock those instead. See https://samueleresca.net/2017/03/unit-testing-asp-net-core-identity/

gopala000 commented 5 years ago

Thanks for your response. That will work. I ended up using https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory. Need to do some refactoring to do like you suggested.