In ASP.NET Core 2.x the DbSets defined in the abstract classes IdentityDbContext and IdentityUserContext are all non-virtual making it much harder to effectively mock my database context that is built on them. It looks like they were virtual in ASP.NET Core 1.x, although the library was arranged differently then, so I am not 100% sure on that.
Is there a reason that they cannot just be made virtual to facilitate unit testing? I really don't like having to resort to something drastic like Fakes when I could just use Moq etc.
If there is a reason they can't be made virtual I would really appreciate it if any one has any ideas on how I can proceed with mocking my db context that implements IdentityDbContext!
I don't believe there's anything preventing us from making them virtual, @ajcvickers can confirm.
This is something cheap we can do for 2.2
Thanks @HaoK! In case anyone else is interested I found a work around that feels a little hacky but works fine. Simply declare a new DbSet foreach of the identity classes in your context along side any others you may have:
public class MyContext
: IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
// Identity entities
public new virtual DbSet<User> Users { get; set; }
public new virtual DbSet<Role> Roles { get; set; }
public new virtual DbSet<RoleClaim> RoleClaims { get; set; }
public new virtual DbSet<UserClaim> UserClaims { get; set; }
public new virtual DbSet<UserLogin> UserLogins { get; set; }
public new virtual DbSet<UserRole> UserRoles { get; set; }
public new virtual DbSet<UserToken> UserTokens { get; set; }
// Your other entities
public virtual DbSet<Foo> Foos { get; set; }
public virtual DbSet<Bar> Bars { get; set; }
}
You can then quite happily mock them using Moq or whatever without issue.
Yep that should work in the mean time, glad you aren't blocked!
No real reason not to do this, but keep in mind that mocking DbSet and in particular IQueryable can be painful. We usually recommend creating a repository abstraction if you are going to create test doubles.
Per https://github.com/aspnet/Identity/issues/1883#issuecomment-406412328 looks like these are considered breaking changes now, so lets move this to 3.0
Just goes to show how little us end users know about everything that goes in making the tools we use! Just glad I was able to work around it! Thanks for letting me know @HoaK