public async Task GetAllBatchesByTCShouldGetAllByTCAsync() { //Arrange (create a moq repo and use it for the controller) var mockRepo = ApiTestData.MockBatchRepo(ApiTestData.Batches.ToList()); var options = TestDbInitializer.InitializeDbOptions("GetAllBatchesByTCShouldGetAllByTCAsync"); using var db = TestDbInitializer.CreateTestDb(options); var mapper = new Mapper(); var mockLogger = new Mock <ILogger <TenantController> >(); var mockAddressService = new Mock <IAddressService>(); var controller = new TenantController(mockRepo.Object, mockAddressService.Object, mockLogger.Object); //Act (get all batches) var result = await controller.GetAllBatches("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"); //Assert var ok = Assert.IsAssignableFrom <OkObjectResult>(result.Result); var batches = Assert.IsAssignableFrom <System.Collections.Generic.List <Lib.Models.Batch> >(ok.Value); Assert.NotNull(batches); }
public void DeleteFriendUsingGenericRepoAndIoC() { var context = _container.TryGetInstance<DbContext>() as PluralSightBookContext; var initializer = new TestDbInitializer(); initializer.Reseed(context); int friendCount = context.Friends.Count(); var testUserId = context.Users .FirstOrDefault(u => u.UserName == TestDbInitializer.TEST_USERNAME) .UserId; var repo = new Repositories.Repository<Friend>(context); var friend = new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }; repo.Add(friend); repo.Save(); var anotherContext = _container.TryGetInstance<DbContext>() as PluralSightBookContext; var repo2 = new Repositories.Repository<Friend>(anotherContext); repo2.Remove(friend); repo2.Save(); Assert.AreEqual(friendCount, context.Friends.Count()); }
public void DeleteFriendUsingGenericRepo() { using (var context = new PluralSightBookContext()) { var initializer = new TestDbInitializer(); initializer.Reseed(context); int friendCount = context.Friends.Count(); var testUserId = context.aspnet_Users.FirstOrDefault().UserId; var repo = new Repositories.Repository <Friend>(context); var friend = new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }; repo.Add(friend); repo.Save(); // Hence always use the same context while saving and deleting the same object/entity // Fails because we're using a different object context //var repo2 = new Repositories.Repository<Friend>(); var repo2 = new Repositories.Repository <Friend>(context); repo2.Remove(friend); repo2.Save(); Assert.AreEqual(friendCount, context.Friends.Count()); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseApplicationInsightsRequestTelemetry(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseApplicationInsightsExceptionTelemetry(); app.UseStaticFiles(); app.UseDefaultFiles(); //app.UseIdentity(); app.UseCors(builder => builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); app.UseExceptionHandler( builder => { builder.Run( async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); var error = context.Features.Get <IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false); } }); }); app.UseMvc(); TestDbInitializer.Initialize(app.ApplicationServices); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); }
public void SetUp() { string[] args = new string[0]; TestDbContextFactory factory = new TestDbContextFactory(); this.dbContext = factory.CreateDbContext(args); TestDbInitializer.Seed(this.dbContext); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); 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.AddDbContextPool <ReservationDbContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IRoomRepository, RoomRepository>(); services.AddScoped <IReservationRepository, ReservationRepository>(); services.AddScoped <IReservationsService, ReservationsService>(); services.AddSingleton <IRoomsViewModelFactory, RoomsViewModelFactory>(); services.AddScoped <IMessagesService, MessagesService>(); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ReservationDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <TestsWebFactory <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Add the actual data to "container", which is accessible everywhere. TestDbInitializer.Initialize(db.Rooms.ToList()); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the database with test messages. Error: {ex.Message}"); } } }); }
public async Task UpdateAsyncShouldReturnStatusCode204() { //Arrange (create a moq repo and use it for the controller) var mockRepo = ApiTestData.MockBatchRepo(ApiTestData.Batches.ToList()); var options = TestDbInitializer.InitializeDbOptions("GetAllBatchesByTCShouldGetAllByTCAsync"); using var db = TestDbInitializer.CreateTestDb(options); var mapper = new Mapper(); var mockLogger = new Mock <ILogger <TenantController> >(); var mockAddressService = new Mock <IAddressService>(); var controller = new TenantController(mockRepo.Object, mockAddressService.Object, mockLogger.Object); //Act var apiTenant = new ApiTenant { Id = Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"), Email = "*****@*****.**", Gender = "male", FirstName = "Colton", LastName = "Clary", AddressId = Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"), TrainingCenter = Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"), ApiBatch = new ApiBatch { TrainingCenter = Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"), Id = 1, BatchCurriculum = "c#" }, ApiCar = new ApiCar { Id = 1, Color = "y", LicensePlate = "123", Make = "s", Model = "2", State = "w", Year = "l" }, ApiAddress = new ApiAddress { State = "sdl", AddressId = Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d"), City = "l", Country = "l", Street = "s", ZipCode = "l" } }; var result = await controller.UpdateAsync(apiTenant); //Assert _ = Assert.IsAssignableFrom <StatusCodeResult>(result); }
public void TestGetRoomInfoWithIdOne() { DateTime now = DateTime.Today; HttpResponseMessage response = _client.GetAsync($"/api/rooms/{now.Day}.{now.Month}.{now.Year}/1").Result; response.EnsureSuccessStatusCode(); RoomInfoDto roomInfoDto = response.Content.ReadAsAsync <RoomInfoDto>().Result; List <Room> rooms = TestDbInitializer.GetTestRooms(); Assert.IsTrue(rooms.FirstOrDefault(r => r.Id == 1)?.Name == roomInfoDto.Room.Name); }
public void TestRooms() { var response = _client.GetAsync("/api/rooms/?date=" + DateTime.Today.ToString("dd.MM.yyyy")).Result; response.EnsureSuccessStatusCode(); //Please don't force me to actually validate the json... string responseString = response.Content.ReadAsStringAsync().Result; foreach (Room room in TestDbInitializer.GetTestRooms()) //I am just checking if all the rooms are shown, therefor I don't have to check the reservations, which at the point being are null... { Assert.Contains(room.Name, responseString); } }
public void ListFriendsUsingMapper() { var friendRepository = new MappingFriendRepository(); var context =new PluralSightBook.Data.PluralSightBookContext(); var initializer = new TestDbInitializer(); initializer.Reseed(context); var testUserId = context.Users.FirstOrDefault().UserId; friendRepository.Create(testUserId, "*****@*****.**"); var result = friendRepository.ListFriendsOfUser(testUserId); Assert.IsInstanceOfType(result.FirstOrDefault(), typeof(PluralSightBook.Core.Model.Friend)); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var context = scope.ServiceProvider.GetService <TestDbContext>(); context.Database.Migrate(); TestDbInitializer.Initialize(context); } host.Run(); }
public void ConstructorShouldConstruct() { // arrange (create database) var mockLogger = new Mock <ILogger <TenantController> >(); var mockAddressService = new Mock <IAddressService>(); var options = TestDbInitializer.InitializeDbOptions("TestTenantControllerConstructor"); using var database = TestDbInitializer.CreateTestDb(options); var mapper = new Mapper(); // act (pass repository with database into controller) var test = new TenantController(new TenantRepository(database, mapper), mockAddressService.Object, mockLogger.Object); // assert (test passes if no exception thrown) }
public void WhyNotExposeIQueryable() { using (var context = new PluralSightBookContext()) { var initializer = new TestDbInitializer(); initializer.Reseed(context); var friendRepo = new QueryableFriendRepo(context); var testUserId = context.aspnet_Users.FirstOrDefault().UserId; // populate some friend sample data friendRepo.Add(new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }); friendRepo.Add(new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }); friendRepo.Add(new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }); friendRepo.Save(); var result = friendRepo.List().Where(f => f.EmailAddress.Contains("foo")); Assert.AreEqual(2, result.Count()); // this tries to run a query on the database but can't //var moreResults = friendRepo.List() // .Where(f => f.IsMicrosoftEmployee()); //foreach (var res in moreResults) //{ // Console.WriteLine(res); //} //Assert.AreEqual(1, moreResults.Count()); // using IEnumerable works as expected, but may fetch more data than desired // however, it never will *surprise* the developer with whether they are working // with the database or not var nonQueryableRepo = new Repository <Friend>(context); var msFriends = nonQueryableRepo.GetAll() .Where(f => f.IsMicrosoftEmployee()); Assert.AreEqual(1, msFriends.Count()); } }
public TestServerFixture([NotNull] ITestOutputHelper output) { Output = output ?? throw new ArgumentNullException(nameof(output)); _initialData = new List <KeyValuePair <string, string> >(); _configuration = new BehaviorSubject <IEnumerable <KeyValuePair <string, string> > >(_initialData); var hostBuilder = new HostBuilder() .UseEnvironment("Development") .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, builder) => { builder .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddObservableConfiguration(_configuration); }) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureLogging(builder => { builder.ClearProviders(); builder.AddXunitLogger(Output); builder.AddInMemoryLogger(Logs); }) .ConfigureWebHost(builder => { builder .UseStartup <TestStartup>() .BasedOn <Startup>() //Internal extension to re set the correct ApplicationKey .UseTestServer(); }); Host = hostBuilder.Start(); Server = Host.GetTestServer(); Client = Host.GetTestClient(); using (var scope = Host.Services.CreateScope()) { var services = scope.ServiceProvider; TestDbInitializer.Seed(services, Output); var storageService = services.GetRequiredService <IStorageService>(); Task.Run(async() => await storageService.CreateIfNotExistsAsync()); } }
protected override void ConfigureWebHost(IWebHostBuilder builder) { 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 <ApplicationDbContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ApplicationDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <TestsWebApplicationFactory <TStartup> > >(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. TestDbInitializer.Initialize(db); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); }
public async Task DeleteShouldReturnStatusCode204() { //Arrange (create a moq repo and use it for the controller) var mockRepo = ApiTestData.MockBatchRepo(ApiTestData.Batches.ToList()); var options = TestDbInitializer.InitializeDbOptions("DeleteShouldReturnStatusCode204"); using var db = TestDbInitializer.CreateTestDb(options); var mapper = new Mapper(); var mockLogger = new Mock <ILogger <TenantController> >(); var mockAddressService = new Mock <IAddressService>(); var controller = new TenantController(mockRepo.Object, mockAddressService.Object, mockLogger.Object); //Act var result = await controller.DeleteAsync(Guid.Parse("fa4d6c6e-9650-44c9-8c6b-5aebd3f9a67d")); //Assert _ = Assert.IsAssignableFrom <StatusCodeResult>(result); }
public void AddFriendUsingGenericRepo() { using (var context = new PluralSightBookContext()) { var initializer = new TestDbInitializer(); initializer.Reseed(context); int friendCount = context.Friends.Count(); var testUserId = context.aspnet_Users .FirstOrDefault(u => u.UserName == TestDbInitializer.TEST_USERNAME) .UserId; var repo = new Repositories.Repository <Friend>(); repo.Add(new Friend() { UserId = testUserId, EmailAddress = "*****@*****.**" }); repo.Save(); Assert.AreEqual(friendCount + 1, context.Friends.Count()); } }
public TestServerFixture(ITestOutputHelper output) { Output = output; var hostBuilder = new HostBuilder() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddXunit(Output); }) .ConfigureWebHost(webHost => { webHost .UseStartup <TestStartup>() .BasedOn <Startup>() //Internal extension to re set the correct ApplicationKey .UseTestServer(); }); Host = hostBuilder.Start(); Server = Host.GetTestServer(); Client = Host.GetTestClient(); using (var scope = Host.Services.CreateScope()) { var services = scope.ServiceProvider; try { TestDbInitializer.Seed(services, Output); } catch (Exception ex) { Output.WriteLine("HOST: " + ex.Message); } } }
public void CreateAndDeleteFriendWithNHRepo() { var repo = new NHFriendRepository(_sessionFactory); string testFriendEmailAddress = Guid.NewGuid().ToString(); using (var context = new PluralSightBookContext()) { var initializer = new TestDbInitializer(); initializer.Reseed(context); Guid testUserId = context.Users .FirstOrDefault(u => u.UserName == TestDbInitializer.TEST_USERNAME) .UserId; int initialFriendCount = context.Friends .Count(f => f.UserId == testUserId); repo.Create(testUserId, testFriendEmailAddress); Assert.AreEqual(initialFriendCount + 1, context.Friends.Count(f => f.UserId == testUserId)); var friends = repo.ListFriendsOfUser(testUserId); Assert.AreEqual(friends.Count(), initialFriendCount + 1); var friend = _sessionFactory.OpenSession() .QueryOver<Friend>() .Where(f => f.EmailAddress == testFriendEmailAddress) .List() .FirstOrDefault(); repo.Delete(friend.Id); Assert.AreEqual(initialFriendCount, context.Friends .Count(f => f.UserId == testUserId)); } }