Moq Setup dont working, while trying to automate it

121 views Asked by At

Main Goal : Automatic Moq an entire DBContext
Current Problem: Setup don´t work.
It runs and adds the Setup but when you try to access the Data you get an "NotImplemented Exception"

The member 'IQueryable.Provider' has not been implemented on type 'DbSet 1Proxy_4' which inherits from 'DbSet 1'. Test doubles for 'DbSet 1' must provide implementations of methods and properties that are used.

My class

 public abstract class MoqBase<T> where T : DbContext
{
    public Mock<T> MockContext { get; private set; }
   
    public void Mock()
    {
        MockContext = new Mock<T> { DefaultValue = DefaultValue.Mock };
        MockContext.SetupAllProperties();
        PrepareContext();
    }

    private void PrepareContext()
    {
        var propertyList = MockContext.Object.GetType().GetProperties();
        var tablePropertyList = propertyList.Where(x => x.PropertyType.FullName.Contains("DbSet")).ToList();
        foreach (var tableProperty in tablePropertyList)
        {
            var proxy = tableProperty.GetValue(MockContext.Object);
            dynamic mockSet = ((dynamic)proxy).Mock;
            AddTableSetup(mockSet);
        }
    }

    public void AddTableSetup<TTable>(Mock<DbSet<TTable>> Mockset) where TTable : class
    {
        var list = new List<TTable>();
        var data = list.AsQueryable();
        Mockset.As<IQueryable<TTable>>().Setup(m => m.Provider).Returns(data.Provider);
        Mockset.As<IQueryable<TTable>>().Setup(m => m.Expression).Returns(data.Expression);
        Mockset.As<IQueryable<TTable>>().Setup(m => m.ElementType).Returns(data.ElementType);
        Mockset.As<IQueryable<TTable>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator);
    }
}

TestMoq which implements MoqBase

public class TestMoq : MoqBase<NetConPortalContext>//NetConPortalContext is my dbContext
{
    public TestMoq() => Mock();
}

Try to access

  static void Main()
    {
        var moq = new TestMoq();
        var context = moq.MockContext.Object;
        var test = context.User.FirstOrDefault();
    }

Picture of Error and Setup in Debug

0

There are 0 answers