Beispiel #1
0
        public static MockedDbContext <T> GetMockContext <T>() where T : DbContext
        {
            var instance = new MockedDbContext <T>();

            instance.MockTables();
            return(instance);
        }
Beispiel #2
0
        /// <summary>
        /// Mocks all the DbSet.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mockedContext"></param>
        public static void MockTables <T>(this MockedDbContext <T> mockedContext) where T : DbContext
        {
            Type contextType     = typeof(T);
            var  dbSetProperties = contextType.GetProperties().Where(prop => (prop.PropertyType.IsGenericType) && prop.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>));

            foreach (var prop in dbSetProperties)
            {
                var  dbSetGenericType = prop.PropertyType.GetGenericArguments()[0];
                Type listType         = typeof(List <>).MakeGenericType(dbSetGenericType);
                var  listForFakeTable = Activator.CreateInstance(listType);
                var  parameter        = Expression.Parameter(contextType);
                var  body             = Expression.PropertyOrField(parameter, prop.Name);
                var  lambdaExpression = Expression.Lambda <Func <T, object> >(body, parameter);
                var  method           = typeof(EntityFrameworkMockHelper).GetMethod("MockDbSet").MakeGenericMethod(dbSetGenericType);
                mockedContext.Setup(lambdaExpression).Returns(method.Invoke(null, new[] { listForFakeTable }));
                mockedContext.Tables.Add(prop.Name, listForFakeTable);
            }
        }