How to properly mock DbContext (EF6 - database first)

1,192 views
Skip to first unread message

freddie

unread,
Nov 27, 2014, 12:17:43 PM11/27/14
to rhino...@googlegroups.com
Hi,

and of course what Microsoft stated: http://msdn.microsoft.com/en-us/data/dn314429.aspx

But it fails when I am trying to adapt it.

[TestClass]
public class MyTestClass
{    
      [TestMethod]
      public void MyTestMethod(){
 
            var mockRepository = new MockRepository();

            var list = new List<Employee>
            {
                new Employee{ Id = 1},
                new Employee{ Id = 2},
                new Employee{ Id = 3}

            }.AsQueryable();

            var mockEntities = MockRepository.GenerateMock<Entities>();

            IDbSet<Employee> mockDbSet= MockRepository.GenerateMock<IDbSet<Employee>, IQueryable>();


            mockDbSet.AsQueryable().Stub(m => m.Provider).Return(list .Provider);
            mockDbSet.AsQueryable().Stub(m => m.Expression).Return(list .Expression);
            mockDbSet.AsQueryable().Stub(m => m.ElementType).Return(list .ElementType);
            mockDbSet.AsQueryable().Stub(m => m.GetEnumerator()).Return(list .GetEnumerator());

            mockEntities.Stub(x => x.Employees).PropertyBehavior();

            mockEntities.Employees = mockDbSet as DbSet<Employee>;



            int expected = list .Count();

            var employeesService= mockRepository.PartialMock<EmployeesService>();

            int actual = employeesService.GetCount();

            Assert.AreEqual(expected, actual);

            mockRepository.VerifyAll();
       }
}

public partial class Entities : DbContext
{
        public Entities()
            : base("name=Entities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Employee> Employees{ get; set; }
}


public class EmployeesService
{
     Entities context;

     public EmployeeService(Entities context)
     {
        this.context=context;
     }

           public int GetCount()
           {                   
                  return context.Employees.Count();                    
           }
}

mockDbSet is null after save casting to DbSet<Employee>. Therefor GetCount() throws a nullpointerreference because the property Employees is not set. 

Does anyone know what I am doing wrong? 

It is just a sample, no guarantee the code works as stated. ;) it just visualize things. 


Thanks!!

haifisch

unread,
Dec 9, 2014, 4:42:33 AM12/9/14
to rhino...@googlegroups.com
Why do you need the cast to DbSet, couldn't you just use IDbSet?
For sure you couldn't cast a stubbed instance of IDbSet to DbSet because your stubbed instance doesn't inherit from DbSet.
Br,
Andreas
Reply all
Reply to author
Forward
0 new messages