I'm new to unit testing and wish to write an application that is N-tier, so my ORM is abstracted away from BLL with a repository-pattern inbetween. How would I go about unit testing a repository-pattern method that has coupling to EF (DbContext)?
My SUT method is here:
public IList<Volunteer> GetAllVolunteers() {
return dbctx.Volunteer.ToList();
}
My unit test so far:
[Fact]
public void GetAllVolunteersMethodWorks() {
// Arrange
var fakeVolunteer = new Volunteer { Id = 0, Name = "Dummy" };
var expected = new List<Volunteer>(new Volunteer[] { fakeVolunteer });
var mockedCtxVolunteer = new Mock<DbSet<Volunteer>>();
mockedCtxVolunteer.Setup(m => m.ToList()).Returns(expected);
var mockedctx = new Mock<RSMContext>();
mockedctx.Setup(m => m.Volunteer).Returns(mockedCtxVolunteer.Object);
// Act
var volunteerRepo = new VolunteerRepository(mockedctx.Object);
var result = volunteerRepo.GetAllVolunteers();
// Assert
Assert.Equal(expected, result);
}
I get an error that System.NotSupportedException: 'Expression references a method that does not belong to the mocked object: m => m.ToList() So how do I properly mock the DbSet so my fake data resides there to properly test my VolunteerRepository.GetAllVolunteers() method works?
edit (solution):
var mockedDbCtxVolunteer = new Mock<DbSet<Volunteer>>();
mockedDbCtxVolunteer.As<IQueryable<Volunteer>>().Setup(m => m.GetEnumerator()).Returns(expected.GetEnumerator());