I have a solution in which I have a Data project that contains an EF6 .edmx file, generated from an existing database. I split the entities into a separate Entities project, and have a Repositories project that references them both.
I have added a BaseRepository with some common methods, and want to unit test it. The top of the class looks like this...
public class BaseRepository<T> : BaseRepositoryInterface<T> where T : class {
private readonly MyEntities _ctx;
private readonly DbSet<T> _dbSet;
public BaseRepository(MyEntities ctx) {
_ctx = ctx;
_dbSet = _ctx.Set<T>();
}
public IEnumerable<T> GetAll() {
return _dbSet;
}
//...
}
Following the code I found at https://stackoverflow.com/a/21074664/706346, I tried the following...
[TestMethod]
public void BaseRepository_GetAll() {
IDbSet<Patient> mockDbSet = Substitute.For<IDbSet<Patient>>();
mockDbSet.Provider.Returns(GetPatients().Provider);
mockDbSet.Expression.Returns(GetPatients().Expression);
mockDbSet.ElementType.Returns(GetPatients().ElementType);
mockDbSet.GetEnumerator().Returns(GetPatients().GetEnumerator());
MyEntities mockContext = Substitute.For<MyEntities>();
mockContext.Patients.Returns(mockDbSet);
BaseRepositoryInterface<Patient> patientsRepository
= new BaseRepository<Patient>(mockContext);
List<Patient> patients = patientsRepository.GetAll().ToList();
Assert.AreEqual(GetPatients().Count(), patients.Count);
}
private IQueryable<Patient> GetPatients() {
return new List<Patient> {
new Patient {
ID = 1,
FirstName = "Fred",
Surname = "Ferret"
}
}
.AsQueryable();
}
Note that I changed the context TT file to use IDbSet, as suggested by Stuart Clement in his comment on Dec 4 '15 at 22:41
However, when I run this test, it gives a null reference exception, as the line in the base repository constructor that sets _dbSet
leaves it null...
_dbSet = _ctx.Set<T>();
I would guess I need to add another line when I set up my mock context, but I'm not sure what. I thought the code above should be enough to populate the DbSet.
Anyone able to explain what I've missed or done wrong?