Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - How to write this EF Mock setup code as a reusable Generic Boilerplate?

I am using moq, ef 6 and xunit. I find myself writing this code over and over and thought maybe I could make it into a generic method but having some trouble.

public static void CreateSalesMock(List<Sale> sales, Mock<DatabaseContext> dbContextMock)
{
    var data = sales.AsQueryable();

    var mockSet = new Mock<DbSet<Sale>>();
    mockSet.As<IQueryable<Sale>>()
           .Setup(x => x.Provider)
           .Returns(data.Provider);
    mockSet.As<IQueryable<Sale>>()
           .Setup(x => x.Expression)
           .Returns(data.Expression);
    mockSet.As<IQueryable<Sale>>()
           .Setup(x => x.ElementType)
           .Returns(data.ElementType);
    mockSet.As<IQueryable<Sale>>()
           .Setup(x => x.GetEnumerator())
           .Returns(data.GetEnumerator());

    dbContextMock.Setup(x => x.Sales).Returns(mockSet.Object);
}

Now I have many other tables in my database so if I could write one method that would take in a list of that data and set it up so I can mock query through it would be great.

public static void CreateMockSet<T, TA, TB>(T dataList, TA model, 
    Func<TB> lambda, Mock<DatabaseContext> dbContextMock) 
     where T : List<T>
     where TA: Mock<DbSet<TA>>
{
    var data = dataList.AsQueryable();

    model.As<IQueryable<T>>()
         .Setup(x => x.Provider)
         .Returns(data.Provider);
    model.As<IQueryable<T>>()
         .Setup(x => x.Expression)
         .Returns(data.Expression);
    model.As<IQueryable<T>>()
         .Setup(x => x.ElementType)
         .Returns(data.ElementType);
    model.As<IQueryable<T>>()
         .Setup(x => x.GetEnumerator())
         .Returns(data.GetEnumerator());

    dbContextMock.Setup(x => lambda);
}

So far I have that but I am not sure if that will work or not. I am stuck passing in the "lambda" part(x => x.Sales for example) so I can't even test it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tim Larson already offered a great solution for this boilerplate code in his blog:

public static class DbSetMocking
{
    private static Mock<DbSet<T>> CreateMockSet<T>(IQueryable<T> data)
            where T : class
    {
        var queryableData = data.AsQueryable();
        var mockSet = new Mock<DbSet<T>>();
        mockSet.As<IQueryable<T>>().Setup(m => m.Provider)
                .Returns(queryableData.Provider);
        mockSet.As<IQueryable<T>>().Setup(m => m.Expression)
                .Returns(queryableData.Expression);
        mockSet.As<IQueryable<T>>().Setup(m => m.ElementType)
                .Returns(queryableData.ElementType);
        mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator())
                .Returns(queryableData.GetEnumerator());
        return mockSet;
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
            this IReturns<TContext, DbSet<TEntity>> setup,
            TEntity[] entities)
        where TEntity : class
        where TContext : DbContext
    {
        Mock<DbSet<TEntity>> mockSet;
        return ReturnsDbSet(setup, entities, out mockSet);
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
            this IReturns<TContext, DbSet<TEntity>> setup,
            IQueryable<TEntity> entities)
        where TEntity : class
        where TContext : DbContext
    {

        Mock<DbSet<TEntity>> mockSet;
        return ReturnsDbSet(setup, entities, out mockSet);
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
            this IReturns<TContext, DbSet<TEntity>> setup,
            IEnumerable<TEntity> entities)
        where TEntity : class
        where TContext : DbContext
    {
        Mock<DbSet<TEntity>> mockSet;
        return ReturnsDbSet(setup, entities, out mockSet);
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
    this IReturns<TContext, DbSet<TEntity>> setup,
    TEntity[] entities, out Mock<DbSet<TEntity>> mockSet)
        where TEntity : class
        where TContext : DbContext
    {
        mockSet = CreateMockSet(entities.AsQueryable());
        return setup.Returns(mockSet.Object);
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
            this IReturns<TContext, DbSet<TEntity>> setup,
            IQueryable<TEntity> entities, out Mock<DbSet<TEntity>> mockSet)
        where TEntity : class
        where TContext : DbContext
    {

        mockSet = CreateMockSet(entities);
        return setup.Returns(mockSet.Object);
    }

    public static IReturnsResult<TContext> ReturnsDbSet<TEntity, TContext>(
    this IReturns<TContext, DbSet<TEntity>> setup,
    IEnumerable<TEntity> entities, out Mock<DbSet<TEntity>> mockSet)
        where TEntity : class
        where TContext : DbContext
    {
        mockSet = CreateMockSet(entities.AsQueryable());
        return setup.Returns(mockSet.Object);
    }

}

Then in the UT you use it as the following:

var context = new Mock<DatabaseContext>();
context.setup(x => x.Sales).ReturnsDbSet(new List<Sale>(){put here the items..});

Edit

I updated the code. Now there are 3 more overloads which allows verification on DbSet<T> property:

    [TestMethod]
    public void TestMethod1()
    {
        var sales = new List<Sale>
        {
            new Sale() {id = 1},
            new Sale() {id = 6},
            new Sale() {id = 5},
            new Sale() {id = 4},
            new Sale() {id = 3},
            new Sale() {id = 2}
        };
        var fakeContest = new Mock<SalesContext>();
        Mock<DbSet<Sale>> fakeSet;
        fakeContest.Setup(context => context.Sales).ReturnsDbSet(sales, out fakeSet);

        var itemsToRemove = sales.Where(sale => sale.id%2 == 0);


        fakeContest.Object.Sales.RemoveRange(itemsToRemove);


        fakeSet.Verify(set => set.RemoveRange(itemsToRemove));

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...