I have an Entity Framework DB Context file. I am trying to setup a Moq framework in NUnit. Currently receiving error below for Moq Nunit test. How would I setup the DBContex
You don't need to mock the context in unit tests. You should use the DbContextOptions
class to specify you want to use an in memory database to run your tests against.
[TestMethod]
public void TestProducts()
{
var options = new DbContextOptionsBuilder<ElectronicsContext>()
.UseInMemoryDatabase(databaseName: "Products Test")
.Options;
using(var context = new ElectronicsContext(options))
{
context.Products.Add(new Product {ProductId = 1, ProductName = "TV", ProductDescription = "TV testing",ImageLocation = "test"});
context.SaveChanges();
}
using(var context = new ElectronicsContext(options))
{
// run your test here
}
}
This runs against the in-memory representation of your database instead of relying on the physical server. The connection string you provided in the startup.cs
is not used as part of the tests.
More info can be found here