Beispiel #1
0
        /// <summary>
        /// Returns a mock of a DbContext
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        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{T} properties that represent tables in a DbContext.
        /// </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);
            }
        }