Skip to content

Instantly share code, notes, and snippets.

@Alejoho
Forked from briangoncalves/DbContextMock.cs
Created August 18, 2023 03:59
Show Gist options
  • Select an option

  • Save Alejoho/893e7aaa72a8cb93ea1dcdb849633d21 to your computer and use it in GitHub Desktop.

Select an option

Save Alejoho/893e7aaa72a8cb93ea1dcdb849633d21 to your computer and use it in GitHub Desktop.

Revisions

  1. @briangoncalves briangoncalves created this gist Dec 19, 2019.
    20 changes: 20 additions & 0 deletions DbContextMock.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    using Microsoft.EntityFrameworkCore;
    using Moq;
    using System.Collections.Generic;
    using System.Linq;

    namespace NETCore3WebApp.Test.Business {
    public static class DbContextMock {
    public static DbSet <T> GetQueryableMockDbSet <T> (List <T> sourceList) where T: class
    {
    var queryable = sourceList.AsQueryable();
    var dbSet = new Mock<DbSet<T>>();
    dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
    dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
    dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
    dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
    dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s));
    return dbSet.Object;
    }
    }
    }