public async Task ShouldretrieveproductForTheGivenId(int id)

        {
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_mockEnvironment.Object);
            services.AddDbContext <ShoppingDBContext>(options =>
            {
                options.UseInMemoryDatabase("TestDB");
            });

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices    = scope.ServiceProvider;
                var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>();
                DbContextSeed.SeedAsync(shoppingDBContext).Wait();
                var     genericRepository = new GenericRepository <Product>(shoppingDBContext);
                Product prod = await genericRepository.GetAsync(id).ConfigureAwait(false);

                Assert.NotNull(prod);
                Assert.Equal(id, prod.ProductId);
            }
        }
        public async Task ShouldRetrieveBillingUser()
        {
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_webHostEnvironmentMock.Object);
            services.AddDbContext <DataContext>(options =>
            {
                options.UseInMemoryDatabase("InMemoryDB");
            });

            // mapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <AutoMapperProfiles>();
            });
            IMapper mapper = config.CreateMapper();

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var dataContext    = scopedServices.GetRequiredService <DataContext>();
                DbContextSeed.SeedAsync(dataContext).Wait();

                var paymentRepository          = new PaymentRepository(dataContext, mapper);
                UserForRegisterDto userDetails = await paymentRepository.GetBillingUser(1).ConfigureAwait(false);

                Assert.Equal("Nemo", userDetails.FirstName);
            }
        }
        public async Task ShouldAddProduct()

        {
            Product productMock = new Product()
            {
                catogeryId  = 1,
                ProductId   = 3,
                ProductName = "KotmaleMilkPowder"
            };
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_mockEnvironment.Object);
            services.AddDbContext <ShoppingDBContext>(options =>
            {
                options.UseInMemoryDatabase("TestDB");
            });

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices    = scope.ServiceProvider;
                var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>();
                DbContextSeed.SeedAsync(shoppingDBContext).Wait();
                var genericRepository = new GenericRepository <Product>(shoppingDBContext);
                var product           = await genericRepository.AddAsync(productMock).ConfigureAwait(false);

                Assert.Equal(productMock.catogeryId, product.catogeryId);
                Assert.Equal(productMock.ProductId, product.ProductId);
                Assert.Equal(productMock.ProductName, product.ProductName);
                Assert.NotNull(genericRepository.GetAsync(3));
            }
        }
Exemple #4
0
        public static async Task Main(string[] args)
        {
            //CreateHostBuilder(args).Build().Run();
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();

                try
                {
                    var context     = services.GetRequiredService <ApplicationDbContext>();
                    var userManager = services.GetRequiredService <UserManager <User> >();
                    await context.Database.MigrateAsync();

                    await DbContextSeed.SeedAsync(context, scope.ServiceProvider, loggerFactory);
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occurred during migration");
                    throw;
                }
            }

            host.Run();
        }
Exemple #5
0
        public async Task ShouldRetrieveProducts_ToGivenCategory()
        {
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_webHostEnvironmentMock.Object);
            services.AddDbContext <DataContext>(options =>
            {
                options.UseInMemoryDatabase("InMemoryDB");
            });

            // mapper
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <AutoMapperProfiles>();
            });
            IMapper mapper = config.CreateMapper();

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var dataContext    = scopedServices.GetRequiredService <DataContext>();
                DbContextSeed.SeedAsync(dataContext).Wait();

                var productRepository = new ProductRepository(dataContext, mapper);
                var products          = await productRepository.GetProducts(1).ConfigureAwait(false);

                var productList = products.ToList();
                Assert.Equal(2, productList.Count);
            }
        }
 public static IApplicationBuilder UseConfig(this IApplicationBuilder app)
 {
     app.UseRouting();
     app.UseCors("AllowSameDomain"); //跨域
     app.UseAuthentication();        //认证
     app.UseAuthorization();         //授权
     app.UseHealthChecks("/health"); //健康检查
     app.UseErrorHandling();         //异常处理
     app.UseSwaggerInfo();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
         endpoints.MapHub <ProjectHub>("/project").RequireCors(t => t.WithOrigins(new string[] { "null" }).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
     });
     app.UseIdentityServer();
     DbContextSeed.SeedAsync(app.ApplicationServices).Wait();//启动初始化数据
     return(app);
 }
Exemple #7
0
 /// <summary>
 /// 中间件管道
 /// </summary>
 /// <param name="app"></param>
 /// <param name="env"></param>
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseRouting();
     app.UseAuthentication();
     app.UseAuthorization();
     app.UseHealthChecks("/health");
     app.RegisterToConsul(Configuration, lifetime);
     app.UseApiVersioning();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });
     DbContextSeed.SeedAsync(app).Wait();
 }
        public async Task ShouldretrieveAllCategories()
        {
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_webHostEnvironmentMock.Object);
            services.AddDbContext <DataContext>(options =>
            {
                options.UseInMemoryDatabase("InMemoryDB");
            });

            //var configuration = new MapperConfiguration(c => c.AddMaps(Assembly.Load("AutumnStore.Test")));
            //var mapper = new Mapper(configuration);

            // mapper
            var config = new MapperConfiguration(cfg => {
                cfg.AddProfile <AutoMapperProfiles>();
            });
            IMapper mapper = config.CreateMapper();

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var dataContext    = scopedServices.GetRequiredService <DataContext>();
                DbContextSeed.SeedAsync(dataContext).Wait();

                //_mapperMock.Setup(m => m.Map<Category, CategoryDto>).Returns(categoryList);
                var categoryRepository          = new CategoryRepository(dataContext, mapper);
                List <CategoryDto> categoryList = await categoryRepository.GetCategories().ConfigureAwait(false);

                //.ProjectTo<CategoryDto>(mapper.ConfigurationProvider).ConfigureAwait(false);

                //Assert.IsAssignableFrom<CategoryDto>(Category);
                Assert.Equal(2, categoryList.Count);
            }
        }
        public async Task ShouldFindProductByGivenId()

        {
            var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase();

            services.AddSingleton(_mockEnvironment.Object);
            services.AddDbContext <ShoppingDBContext>(options =>
            {
                options.UseInMemoryDatabase("TestDB");
            });

            var serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedServices    = scope.ServiceProvider;
                var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>();
                DbContextSeed.SeedAsync(shoppingDBContext).Wait();
                var             genericRepository = new GenericRepository <Product>(shoppingDBContext);
                IList <Product> prodlist          = await genericRepository.FindAsync(x => x.catogeryId == 1).ConfigureAwait(false);

                Assert.Equal(2, prodlist.Count);
            }
        }
Exemple #10
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try
                {
                    var databaseContext = services.GetRequiredService <BarracudaDbContext>();
                    var userManager     = services.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleManager     = services.GetRequiredService <RoleManager <IdentityRole> >();
                    await DbContextSeed.SeedAsync(userManager, roleManager, databaseContext);
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }
Exemple #11
0
        protected override async void ConfigureWebHost(IWebHostBuilder builder)
        {
            ClientOptions.BaseAddress = new Uri("https://localhost:44316/");

            builder.UseEnvironment("Test");

            builder.UseUrls("https://localhost:44316/");

            builder.ConfigureServices(services =>

            {
                // Create a new service provider.

                var serviceProvider = new ServiceCollection()

                                      .AddEntityFrameworkInMemoryDatabase()

                                      .BuildServiceProvider();


                // Add a database context(ApplicationDbContext) using an in-memory

                // database for testing.

                services.AddDbContext <ShoppingDBContext>(options =>

                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");

                    options.UseInternalServiceProvider(serviceProvider);
                });



                // Build the service provider.

                var sp = services.BuildServiceProvider();

                services.Configure <ClientConfigurationModel>(new ConfigurationBuilder().Build());



                // Create a scope to obtain a reference to the database

                using (var scope = sp.CreateScope())

                {
                    var scopedServices = scope.ServiceProvider;

                    var db = scopedServices.GetRequiredService <ShoppingDBContext>();



                    // Ensure the database is created.

                    db.Database.EnsureCreated();



                    // Seed the database with test data.

                    DbContextSeed.SeedAsync(db).Wait();
                }
            });
        }