unittest moq dbContext, entityframeworkCore


写个 helper

    public class MoqDbContext
    {
        private Mock<DataContext> contextMock;

        public MoqDbContext()
        {
            DbContextOptions<DataContext> options = new DbContextOptions<DataContext>();
            contextMock = new Mock<DataContext>(options);
        }


        public MoqDbContext AddDBContext<T>(Expression<Func<DataContext, DbSet<T>>> expression, List<T> data) where T : class
        {
            contextMock.Setup(expression).ReturnsDbSet(data);

            return this;
        }

        public DataContext Create()
        {
            return contextMock.Object;
        }
    }

使用的时候

            //Act
            var _context = new MoqDbContext()
                                .AddDBContext(x => x.TranslationMemory, translationMemories)
                                //.AddDBContext(x => x.Resource, resoureData)       //Adding multiple Entities
                                .Create();
posted @ 2022-05-06 17:15  【唐】三三  阅读(55)  评论(0编辑  收藏  举报