Example #1
0
        /// <summary>
        /// Gets an initialized database by its Id
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static InMemoryMockDatabase GetDatabase(Guid Id)
        {
            InMemoryMockDatabase result;

            if (!databases.TryGetValue(Id, out result))
            {
                result = new InMemoryMockDatabase();
                databases.Add(Id, result);
            }
            return(result);
        }
Example #2
0
        /// <summary>
        /// Create an instance of the given DbContext type, substituting DbSet properties
        /// </summary>
        /// <typeparam name="T">The DbContext type</typeparam>
        /// <param name="database">The in memory database</param>
        /// <param name="type">DbContext type</param>
        /// <returns></returns>
        public static object Create(InMemoryMockDatabase database, Type type)
        {
            //Check that all DbSet properties are marked as virtual:
            var DbSetNotVirtualProperties =
                type.GetProperties()
                .Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>) && x.CanRead)
                .Where(x => !x.GetGetMethod().IsVirtual);

            if (DbSetNotVirtualProperties.Any())
            {
                var names = DbSetNotVirtualProperties.Select(x => x.Name).Aggregate("", (a, b) => a == "" ? b : a + ", " + b);
                throw new ArgumentException($"There are some DbSet properties on type {type} that are not virtual and thus the DbContextInterceptor is not able to mock it: {names}");
            }
            var Interceptor = new DbContextProxyInterceptor(database);

            return(generator.CreateClassProxy(type, Interceptor));
        }
Example #3
0
 public DbContextProxyInterceptor(InMemoryMockDatabase database)
 {
     this.database = database;
 }
Example #4
0
        /// <summary>
        /// Create an in-memory typed DbContext
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="DatabaseId">The Id of the in-memory database. Use the same Id between calls for persisting state between DbContext instances. Use null for not persisting state at all</param>
        /// <param name="type">DbContext type</param>
        /// <returns></returns>
        public static object Create(Guid?DatabaseId, Type type)
        {
            var database = DatabaseId.HasValue ? InMemoryMockDatabase.GetDatabase(DatabaseId.Value) : new InMemoryMockDatabase();

            return(DbContextFactory.Create(database, type));
        }