I have a generic repository for several contexts. I can extend it and use it for services without problem. However, When I mock it, this.Entities
in the constructor is always null
.
GenericDataRepsository
public class GenericDataRepository<T, C> : IGenericDataRepository<T, C> where T : class where C : DbContext, new() {
protected C context;
protected IDbSet<T> Entities;
public GenericDataRepository() {
this.context = new C();
this.Entities = context.Set<T>();
}
public GenericDataRepository(C context) {
this.context = context;
this.Entities = context.Set<T>(); // Problem is here. Entities didn't get set when mocking
}
public virtual IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate) {
return Entities.Where(predicate).ToList();
}
// omitted Add, Update, Delte
}
Unit Test
[Test]
public void GetBIlloTo() {
var data = new List<BillTo> {
new BillTo { CONTACTID = 12, COUNTRY = "USA" }
}.AsQueryable();
var mockSet = Substitute.For<DbSet<BillTo>, IQueryable<BillTo>>();
((IQueryable<BillTo>)mockSet).Provider.Returns(data.Provider);
((IQueryable<BillTo>)mockSet).Expression.Returns(data.Expression);
((IQueryable<BillTo>)mockSet).ElementType.Returns(data.ElementType);
((IQueryable<BillTo>)mockSet).GetEnumerator().Returns(data.GetEnumerator());
var mockContext = Substitute.For<MyEntities>();
mockContext.BillToes.Returns(mockSet);
var repo = new GenericDataRepository<BillTo, MyEntities>(mockContext);
//// Act
var actual = repo.FindBy(r => r.CONTACTID == 12);
//// Assert
Assert.AreEqual(actual.Count(), 1);
}
MyEntities - generated by EF and I didn't change it.
public partial class MyEntities : DbContext
{
public MyEntities()
: base("name=MyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<BillTo> BillToes { get; set; }
}
I'm using EF database first, NUnit, and Nsubstitute. Tried Moq as well, same problem. So, Why didn't Entities
get set?
Aucun commentaire:
Enregistrer un commentaire