This is the first time I'm testing .NET Core and see how Moq can be used in unit testing. Controllers are created out of the box, where ApplicationDbContext are constructor parameters, for example:
public class MoviesController : Controller { private readonly ApplicationDbContext _context; public MoviesController(ApplicationDbContext context) { _context = context; }
Here is the unit test that I started working with when testing the controller:
[TestClass] public class MvcMoviesControllerTests { [TestMethod] public async Task MoviesControllerIndex() { var mockContext = new Mock<ApplicationDbContext>(); var controller = new MoviesController(mockContext.Object);
But then I realized that ApplicationDbContext is a concrete class. And it does not have a constructor without parameters, so the test will not work. This gives me an error: I could not find a constructor without parameters.
It may be a question that is more Moq-focused rather than .NET Core related, but I'm also new to Moq, so I'm not sure how to do this. Here's how the ApplicationDbContext code was generated when the project was created:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder);
What do I need to change for my unit test to succeed?
UPDATE:
I found from https://msdn.microsoft.com/en-us/magazine/mt703433.aspx that you can configure EF Core to use the in-memory database for unit testing. So I changed my unit test as follows:
[TestMethod] public async Task MoviesControllerIndex() { var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>(); optionsBuilder.UseInMemoryDatabase(); var _dbContext = new ApplicationDbContext(optionsBuilder.Options); var controller = new MoviesController(_dbContext);
This test succeeds now. But is this the right way to do this? Obviously, I completely eliminated the mockery of ApplicationDbContext with Moq! Or is there another solution to this problem using Moq.