I have a Base class where i can find different generic methods like
public class EntityRepositoryBase<T> : IDisposable, IEntityRepository<T> where T : class
{
//Context is application DbContext class
public Context DataContext
{
get { return Context.GetContext(); }
}
public virtual IQueryable<T> GetAll()
{
return DataContext.Set<T>().AsQueryable();
}
public virtual bool Any(Expression<Func<T, bool>> predicate)
{
return DataContext.Set<T>().Any(predicate);
}
I want to mock this DataContext(which has connection with real database) by in-memory Database Context so i can write different tests for the following method.
public List<DtoTypeEntity> GetPlantData()
{
List<DtoTypeEntity> lstEntity = new List<DtoTypeEntity>();
using (var PlantTypeRepo = new EntityRepositoryBase<PlantType>())
{
// Some Logic here...
lstEntity = PlantTypeRepo.ToList();
}
return lstEntity;
}
I have added my custom DbContext class just to unit tests
public class MyTestDbContext : DbContext
{
public MyTestDbContext(DbContextOptions<MyTestDbContext> options) : base(options)
{
}
public DbSet<PlantType> PlantTypes { get; set; }
}
In test class something like this
public class MasterDataManagerTests
{
private readonly DbContextOptions<MyTestDbContext> _options;
public MasterDataManagerTests()
{
// Set up in-memory database options
_options = new DbContextOptionsBuilder<MyTestDbContext>()
.UseInMemoryDatabase(databaseName: "MyTestDb")
.Options;
}
[Theory]
[InlineData("PLANT_TYPE1")]
public void MasterDataManager_GetAllMasterData_ReturnPlantList(string screenCode)
{
// Arrange
var context = new MyTestDbContext(_options);
context.PlantTypes.Add(new PlantType { PlantType_ID = 123, Code = "Code1", Name = "ABC", ValidStartDate = DateTime.Now, ValidEndtDate = DateTime.Now});
context.PlantTypes.Add(new PlantType { PlantType_ID = 456, Code = "Code2", Name = "XYZ", ValidStartDate = DateTime.Now, ValidEndtDate = DateTime.Now});
context.SaveChanges();
var dbRepo = new EntityRepositoryBase<PlantType>() {};
dbRepo.DataContext = new GaiaTestDbContext(_options);
// Act
}
But i am unable to mock real dbcontext with in-memory dbcontext.It shows me unable to assign a value to dbRepo.DataContext