[NSub說明書] Page 10 - EntityFramework

NSubstitute -  EntityFramework 
範例程式碼放在 GitHub

前言

當紀錄一下 EntityFramework 如何做隔離測試 

程式碼

    public class A11_EntityFramework
    {
        [TestMethod()]
        public void NSubstituteNote22()
        {
            //arrange
            var data = new List<Author>
              {
                 new Author {Id=1, Name = "BBB" },
                 new Author {Id=2, Name = "ZZZ" },
                 new Author {Id=3, Name = "AAA" },
              }.AsQueryable();

            var mockAuthorDbSet = Substitute.For<IDbSet<Author>>().Initialize(data);
            var mockContext = Substitute.For<DataContext>();
            mockContext.Authors.Returns(mockAuthorDbSet);
            var expected = "BBB";
            var sut = new AuthorRepository(mockContext);
            //act
            var actul = sut.GetAuthor(1);
            //assert
            Assert.AreEqual(expected, actul.Name);
        }
    }
    //----------------------------------------------------------------------
    public static class DbSetTestExtention
    {
        public static IDbSet<T> Initialize<T>(this IDbSet<T> dbSet, IQueryable<T> data) where T : class
        {
            dbSet.Provider.Returns(data.Provider);
            dbSet.Expression.Returns(data.Expression);
            dbSet.ElementType.Returns(data.ElementType);
            dbSet.GetEnumerator().Returns(data.GetEnumerator());
            return dbSet;
        }
    }

EntityFramework 的程式碼

   public class DataContext : DbContext
    {
        public DataContext()
            : base("name=DataContext"){}

        public virtual IDbSet<Author> Authors { get; set; }
    }
 //------------------------------------------------------------------
   public class AuthorRepository : Repository<Author>, IAuthorRepository
    {
        public AuthorRepository(DataContext context) : base(context){}
        public Author GetAuthor(int id)
        {
            return PlutoContext.Authors.SingleOrDefault(a => a.Id == id);
        }
        public DataContext PlutoContext
        {
            get { return Context as DataContext; }
        }
    }

結語

請用IDbSet 這樣就不難 隔離了

參考連結

NSubstitute DbSet / IQueryable

Entity Framework Testing with a Mocking Framework (EF6 onwards)

如果內容有誤請多鞭策謝謝