title: How do I properly unit test a repository-pattern method, that has coupling to Entity Framework / DbContext?
body: <p>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)?</p>
  
  <p><strong>My SUT method is here:</strong></p>
  
  <pre><code>public IList&lt;Volunteer&gt; GetAllVolunteers() {
      return dbctx.Volunteer.ToList();
  }
  </code></pre>
  
  <p><strong>My unit test so far:</strong></p>
  
  <pre><code>[Fact]
  public void GetAllVolunteersMethodWorks() {
      // Arrange
      var fakeVolunteer = new Volunteer { Id = 0, Name = "Dummy" };
      var expected = new List&lt;Volunteer&gt;(new Volunteer[] { fakeVolunteer });
  
      var mockedCtxVolunteer = new Mock&lt;DbSet&lt;Volunteer&gt;&gt;();
      mockedCtxVolunteer.Setup(m =&gt; m.ToList()).Returns(expected);
  
      var mockedctx = new Mock&lt;RSMContext&gt;();
      mockedctx.Setup(m =&gt; m.Volunteer).Returns(mockedCtxVolunteer.Object);
  
      // Act
      var volunteerRepo = new VolunteerRepository(mockedctx.Object);
      var result = volunteerRepo.GetAllVolunteers();
  
      // Assert
      Assert.Equal(expected, result);
  }
  </code></pre>
  
  <p>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?</p>
  
  <p><strong>edit (solution):</strong> </p>
  
  <pre><code>var mockedDbCtxVolunteer = new Mock&lt;DbSet&lt;Volunteer&gt;&gt;();
  mockedDbCtxVolunteer.As&lt;IQueryable&lt;Volunteer&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(expected.GetEnumerator());
  </code></pre>