I have added a test project for my core 1.0 application. Inside of which I have repositories that use dbContext in constructor.
How can I get access to this dbContext inside of test project and inject it properly?
This is my ApplicationDbContext class:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
and this is my unit test method:
[Fact]
public void ProductsGetAll()
{
//here i need to get acces to dbContext and inject it below
ProductRepository productRepository = new ProductRepository(dbContext);
CategoryRepository categoryRepository = new CategoryRepository(dbContext);
ProductController productController = new ProductController(productRepository, categoryRepository);
}
UPDATE
I have added context in the test constructor:
ApplicationDbContext dbContext;
public UnitTest1()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "FakeDatabase")
.Options;
dbContext = new ApplicationDbContext(options);
}
and my test method:
[Fact]
public void ProductsGetAll()
{
IProductRepository productRepository = new ProductRepository(dbContext);
ICategoryRepository categoryRepository = new CategoryRepository(dbContext);
ProductController productController = new ProductController(productRepository, categoryRepository);
var result = productController.List("Pizza");
var contentResult = result as ViewResult;
var final = contentResult != null;
Assert.False(final, "Shouldnt be null");
but now I have an error:
Message: System.NullReferenceException : Object reference not set to an instance of an object.
ProductController
then you should mock the repositories for unit test. On the other hand if you're doing an integration test then you'll have to point at an actually DB and if you want that to work on local machines and build servers you'll likely want to write code to generate a temp db to use. The alternative is to keep connection string info in your config to point at the location of local and build server DBs to test against. But then you'll have to be careful about tests mutating the DB and what that means when the tests are run multiple times. – juharrDbContext
). That is an internal aspect and does not pertain to logic. It is your repositories that should be mocked and that can be done with interfaces. – JuanR