public async Task AddExistCourseTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository     = new EfDeletableEntityRepository <Course>(new ApplicationDbContext(options.Options));
            var userRepository =
                new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));
            var user = new ApplicationUser
            {
                FullName = "Test",
            };

            var course = new Course
            {
                Title = "test",
            };
            await userRepository.AddAsync(user);

            await userRepository.SaveChangesAsync();

            await repository.AddAsync(course);

            await repository.SaveChangesAsync();

            var coursesService = new CoursesService(repository, userRepository);

            coursesService.AddCourseAsync(course.Id, user.Id, 1, 1);
            coursesService.AddCourseAsync(course.Id, user.Id, 1, 1);
            Assert.Single(user.Courses);
        }
示例#2
0
        public async Task GetAllFavouritePostAsyncShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryArticle              = new EfDeletableEntityRepository <Article>(dbContext);
            var repositoryArticlePicture       = new EfRepository <ArticlePicture>(dbContext);
            var repositoryUserFavouriteArticle = new EfDeletableEntityRepository <UserFavouriteArticle>(dbContext);

            var userFavouriteArticle = new UserFavouriteArticle
            {
                ArticleId = 1,
                UserId    = "1",
            };

            await repositoryUserFavouriteArticle.AddAsync(userFavouriteArticle);

            await repositoryUserFavouriteArticle.SaveChangesAsync();

            AutoMapperConfig.RegisterMappings(typeof(GetAllFavouritePostTestViewModel).GetTypeInfo().Assembly);

            var service = new ArticlePostsService(repositoryArticle, repositoryArticlePicture, repositoryUserFavouriteArticle);

            var posts = await service.GetAllFavouritePostAsync <GetAllFavouritePostTestViewModel>(userFavouriteArticle.UserId);

            Assert.Equal(1, posts.Count());
        }
        public async Task DeleteByIdAsync_WithExistentId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "ReviewService DeleteByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedRecipeAndUser(context);

            var reviewRepository = new EfDeletableEntityRepository <Review>(context);
            var reviewService    = this.GetReviewService(reviewRepository);
            var review           = new Review
            {
                Comment    = "Comment",
                Rating     = 5,
                RecipeId   = context.Recipes.First().Id,
                ReviewerId = context.Recipes.First().Id,
            };
            await reviewRepository.AddAsync(review);

            await reviewRepository.SaveChangesAsync();

            var existentId = reviewRepository.All().First().Id;

            // Act
            var reviewsCount = reviewRepository.All().Count();
            await reviewService.DeleteByIdAsync(existentId);

            var actualResult   = reviewRepository.All().Count();
            var expectedResult = reviewsCount - 1;

            // Assert
            Assert.True(actualResult == expectedResult, errorMessagePrefix + " " + "Reviews count is not reduced.");
        }
示例#4
0
        public async Task DeleteLessonTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var lessonsRepository = new EfDeletableEntityRepository <Lesson>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetLessonData())
            {
                await lessonsRepository.AddAsync(item);

                await lessonsRepository.SaveChangesAsync();
            }

            var mockUserLessonRepository = new Mock <IRepository <UserLesson> >();
            var courseRepository         = new EfDeletableEntityRepository <Course>(new ApplicationDbContext(options.Options));

            foreach (var item in this.GetCourseData())
            {
                await courseRepository.AddAsync(item);

                await courseRepository.SaveChangesAsync();
            }

            var service = new LessonsService(lessonsRepository, mockUserLessonRepository.Object, courseRepository);
            await service.DeleteLesson("1", "User1");

            await service.DeleteLesson("3", "User2");

            var lessons = lessonsRepository.All();

            Assert.Equal(3, lessons.Count());
        }
        public async Task RemoveLockdownUserAsyncShouldRemoveBanForUser()
        {
            AutoMapperConfig.RegisterMappings(typeof(UserTestModel).Assembly);

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var repository = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            await repository.AddAsync(new ApplicationUser { Id = "test1", UserName = "******" });

            await repository.SaveChangesAsync();

            var mockedUserManager = MockUserManager <ApplicationUser>(repository.All().ToList());
            var service           = new UsersService(repository, null, null, null, mockedUserManager.Object);

            await service.LockdownUserAsync("TestUser1");

            var user = service.GetByUsername <UserTestModel>("TestUser1");

            Assert.True(user.LockoutEnabled);

            await service.RemoveLockdownUserAsync("TestUser1");

            user = service.GetByUsername <UserTestModel>("TestUser1");
            Assert.False(user.LockoutEnabled);
        }
示例#6
0
        public async Task GetAllReplaysForMessageByMessageIdAsync_WithNullMessage_ShouldReturnArgumentNullException()
        {
            var             context    = SteuDbContextInMemoryFactory.InitializeContext();
            MessagesService service    = this.IntializeMessagesService(context);
            var             repository = new EfDeletableEntityRepository <Message>(context);

            var message = new Message()
            {
                Id          = "messageId",
                Content     = "content",
                OrderId     = "orderId",
                RecipientId = "recipientId",
                Replays     = new List <Replay>(),
                SenderId    = "senderId",
            };

            message.Replays.Add(new Replay()
            {
                Id          = "replayId",
                Content     = "replayContent",
                RecipientId = "recipientId",
                SenderId    = "senderId",
            });

            await repository.AddAsync(message);

            await repository.SaveChangesAsync();

            await Assert.ThrowsAsync <ArgumentNullException>(()
                                                             => service.GetAllReplaysForMessageByMessageIdAsync("userId", null));
        }
示例#7
0
        public async Task SendReplayToMessageByOrderIdAsync_WithCorrectData_ShouldReturnRecipientId()
        {
            var             context    = SteuDbContextInMemoryFactory.InitializeContext();
            MessagesService service    = this.IntializeMessagesService(context);
            var             repository = new EfDeletableEntityRepository <Message>(context);

            var message = new Message()
            {
                Id          = "messageId",
                Content     = "content",
                OrderId     = "orderId",
                RecipientId = "recipientId",
                Replays     = new List <Replay>(),
                SenderId    = "senderId",
            };

            await repository.AddAsync(message);

            await repository.SaveChangesAsync();

            var actualResult =
                await service.SendReplayToMessageByOrderIdAsync("senderId", "messageId", "content");

            Assert.Equal("recipientId", actualResult);
        }
        public async Task CheckIfReturnsAllBeats()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase("BeatsWaveVirtual");

            var beatRepository  = new EfDeletableEntityRepository <Beat>(new ApplicationDbContext(options.Options));
            var imageRepository = new EfDeletableEntityRepository <CloudinaryImage>(new ApplicationDbContext(options.Options));
            var userRepository  = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            for (int i = 0; i < 100; i++)
            {
                await beatRepository.AddAsync(new Beat
                {
                    Name = "Rat",
                });
            }

            await beatRepository.SaveChangesAsync();

            var beatService = new BeatsService(beatRepository, imageRepository, userRepository);

            AutoMapperConfig.RegisterMappings(typeof(TestBeat).Assembly);

            var result = await beatService.GetAllBeatsAsync <TestBeat>(100);

            Assert.Equal(100, result.Count());
        }
        public async Task IsCarAvailableByDate_ShouldReturnFalse_ForCarWithoutTrip_WithRaservation_ByDate()
        {
            var context                = ApplicationDbContextInMemoryFactory.InitializeContext();
            var carsRepository         = new EfDeletableEntityRepository <Car>(context);
            var tripsRepository        = new EfDeletableEntityRepository <Trip>(context);
            var reservationsRepository = new EfDeletableEntityRepository <Reservation>(context);
            var parkingsRepository     = new EfDeletableEntityRepository <Parking>(context);
            var parkingService         = new ParkingsService(parkingsRepository);
            var carsService            = new CarsService(carsRepository, tripsRepository, reservationsRepository, parkingService);
            var seeder = new DbContextTestsSeeder();
            await seeder.SeedCarsAsync(context);

            var car = await carsRepository.All().FirstOrDefaultAsync();

            var date       = DateTime.UtcNow.AddDays(5);
            var resevation = new Reservation()
            {
                ReservationDate = date, CarId = car.Id
            };
            await reservationsRepository.AddAsync(resevation);

            await reservationsRepository.SaveChangesAsync();

            var reservationFromDbCarId = await reservationsRepository.All().Select(r => r.CarId).FirstOrDefaultAsync();

            var result = await carsService.IsCarAvailableByDate(date, reservationFromDbCarId);

            Assert.False(result, ErrorMessage);
        }
示例#10
0
        public async Task Check_ConferenceHall_Seeder()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            this.dbContext = new ApplicationDbContext(options);

            var conferenceHallRepository            = new EfDeletableEntityRepository <ConferenceHall>(this.dbContext);
            var conferenceHallReservationRepository = new EfDeletableEntityRepository <ConferenceHallReservation>(this.dbContext);

            await conferenceHallRepository.AddAsync(new ConferenceHall
            {
                Id              = "conferenceid",
                CreatedOn       = DateTime.UtcNow,
                IsDeleted       = false,
                EventType       = (ConfHallEventType)Enum.Parse(typeof(ConfHallEventType), "Conference"),
                Description     = "Conference",
                CurrentCapacity = 100,
                MaxCapacity     = 100,
                Price           = 50,
            });

            await conferenceHallRepository.SaveChangesAsync();

            this.conferenceHallService = new ConferenceHallService(conferenceHallReservationRepository, conferenceHallRepository);

            var actualResult = conferenceHallRepository.All().ToList();

            int expectedResult = 1;

            Assert.Equal(actualResult.Count(), expectedResult);
        }
示例#11
0
        public async Task CheckIfGetsBeatByIdAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase("BeatsWaveVirtual");

            var beatRepository  = new EfDeletableEntityRepository <Beat>(new ApplicationDbContext(options.Options));
            var imageRepository = new EfDeletableEntityRepository <CloudinaryImage>(new ApplicationDbContext(options.Options));
            var userRepository  = new EfDeletableEntityRepository <ApplicationUser>(new ApplicationDbContext(options.Options));

            await beatRepository.AddAsync(new Beat
            {
                Id            = 1,
                Name          = "Lit",
                StandartPrice = 20,
                Description   = "lalala",
            });

            await beatRepository.SaveChangesAsync();

            var beatService = new BeatsService(beatRepository, imageRepository, userRepository);

            AutoMapperConfig.RegisterMappings(typeof(TestBeat).Assembly);
            var result = await beatService.FindBeatByIdAsync <TestBeat>(1);

            Assert.Equal("Lit", result.Name);
        }
        public async Task CheckIfCategoryExitsByIdShouldReturnCorrectBool()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryCategory = new EfDeletableEntityRepository <Category>(dbContext);

            var category = new Category
            {
                Id          = 1,
                Title       = "test",
                Description = "test",
                Name        = "test",
            };

            await repositoryCategory.AddAsync(category);

            await repositoryCategory.SaveChangesAsync();


            var service = new CategoriesService(repositoryCategory);

            var resultTrue = await service.CategoryExitsAsync(category.Id);

            var resultFalse = await service.CategoryExitsAsync(2);

            Assert.True(resultTrue);
            Assert.False(resultFalse);
        }
        public async Task GetCategoriByNameShouldReturnCorrectCategory()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryCategory = new EfDeletableEntityRepository <Category>(dbContext);

            var category = new Category
            {
                Title       = "test",
                Description = "test",
                Name        = "test",
            };

            await repositoryCategory.AddAsync(category);

            await repositoryCategory.SaveChangesAsync();

            AutoMapperConfig.RegisterMappings(typeof(CategoryTestViewMode).GetTypeInfo().Assembly);

            var service = new CategoriesService(repositoryCategory);

            var categoryResult = await service.CategoriesByNameAsync <CategoryTestViewMode>(category.Name);

            Assert.Equal(category.Name, categoryResult.Name);
        }
        public async Task CheckIfAllMethodReturnsTheCorrectAmountOfData(int?take = null, int skip = 0)
        {
            // Arrange
            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>()
                                 .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var dbContext   = new ApplicationDbContext(optionsBuilder.Options);
            var beatRepo    = new EfDeletableEntityRepository <Beat>(dbContext);
            var playRepo    = new EfRepository <Play>(dbContext);
            var likeRepo    = new EfDeletableEntityRepository <Like>(dbContext);
            var beatService = new BeatService(beatRepo, playRepo, likeRepo);

            // Act
            for (int i = 1; i <= 100; i++)
            {
                var year = 2020;

                await beatRepo.AddAsync(new Beat
                {
                    Id        = i,
                    CreatedOn = DateTime.Parse($"13/02/{year++} 15:43:56"),
                });
            }
            await beatRepo.SaveChangesAsync();

            AutoMapperConfig.RegisterMappings(typeof(FakeBeatModel).Assembly);
            var result = await beatService.AllAsync <FakeBeatModel>(take, skip);

            dbContext.Database.EnsureDeleted();
            result.OrderBy(x => x.Id);

            // Assert
            Assert.Equal(take, result.ToList().Count);
            Assert.Equal(skip + 1, result.First().Id);
        }
示例#15
0
        public async Task DeleteMessageByIdAsync_WithInvalidMessageId_ShouldReturnArgumentNullException()
        {
            var             context    = SteuDbContextInMemoryFactory.InitializeContext();
            MessagesService service    = this.IntializeMessagesService(context);
            var             repository = new EfDeletableEntityRepository <Message>(context);

            var message = new Message()
            {
                Id          = "messageId",
                Content     = "content",
                OrderId     = "orderId",
                RecipientId = "recipientId",
                Replays     = new List <Replay>(),
                SenderId    = "senderId",
            };

            await repository.AddAsync(message);

            await repository.SaveChangesAsync();

            await service.DeleteMessageByIdAsync("messageId");

            var actualResult = await repository.All().ToListAsync();

            await Assert.ThrowsAsync <ArgumentNullException>(()
                                                             => service.DeleteMessageByIdAsync("asd"));
        }
示例#16
0
        public async Task GetRemainingMinutesToCreateTopic_WhenThereIsNoOtherTopic_ShouldReturnCorrectMinutes()
        {
            // Arrange
            var context         = ApplicationDbContextInMemoryFactory.InitializeContext();
            var topicRepository = new EfDeletableEntityRepository <Topic>(context);
            var userRepository  = new EfDeletableEntityRepository <ApplicationUser>(context);
            var topicsService   = new TopicsService(topicRepository, userRepository);

            var user = new ApplicationUser()
            {
                UserName = "******",
            };

            await userRepository.AddAsync(user);

            await userRepository.SaveChangesAsync();

            var userId = userRepository.All().FirstOrDefault(u => u.UserName == "testUsername").Id;

            // Act
            var expectedRemainingMinutes = 31;
            var actualRemainingMinutes   = topicsService.GetRemainingMinutesToCreateTopic(userId);

            // Assert
            Assert.Equal(expectedRemainingMinutes, actualRemainingMinutes);
        }
示例#17
0
        public async Task GetAllMessagesByUserIdAsync_WithCorrectData_ReturnUserMessages()
        {
            var             context    = SteuDbContextInMemoryFactory.InitializeContext();
            MessagesService service    = this.IntializeMessagesService(context);
            var             repository = new EfDeletableEntityRepository <Message>(context);

            var message = new Message()
            {
                Id          = "messageId",
                Content     = "content",
                OrderId     = "orderId",
                RecipientId = "recipientId",
                Replays     = new List <Replay>(),
                SenderId    = "senderId",
            };

            await repository.AddAsync(message);

            await repository.SaveChangesAsync();

            var actualResult =
                await service.GetAllMessagesByUserIdAsync <AllMessageViewModel>(1, 10, "recipientId");

            Assert.Single(actualResult);
        }
示例#18
0
        public async Task EditTruckAsync_WithIncorectOrderId_ShouldReturnArgumentNullException()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            await repository.AddAsync(new Order()
            {
                Id    = "asdasd",
                Truck = new Truck(),
            });

            await context.SaveChangesAsync();

            EditTruckViewModel model = new EditTruckViewModel()
            {
                Id            = "asd",
                CountryFrom   = "Bulgaria",
                TownFrom      = "Sofia",
                CountryTo     = "Croatia",
                TownTo        = "Zagreb",
                TruckTypeName = "Normal",
                Priority      = "Normal",
                Circle        = false,
                ExpireTime    = DateTime.UtcNow,
                LoadTime      = DateTime.UtcNow,
                MaxVolume     = 100,
                MaxLoad       = 20000,
                Price         = 12312231,
                Referer       = "dasada",
                InputModel    = new TruckEditViewModel(),
            };

            await Assert.ThrowsAsync <ArgumentNullException>(() => service.EditTruckAsync(model));
        }
示例#19
0
        public async Task GetCountOfAllUnReadMessagesByUserId_WithReplayCorrectData_ReturnNumberOfUnreadMsg()
        {
            var             context    = SteuDbContextInMemoryFactory.InitializeContext();
            MessagesService service    = this.IntializeMessagesService(context);
            var             repository = new EfDeletableEntityRepository <Message>(context);

            var message = new Message()
            {
                Id          = "messageId",
                Content     = "content",
                OrderId     = "orderId",
                RecipientId = "recipientId",
                Replays     = new List <Replay>(),
                SenderId    = "senderId",
                IsRead      = false,
            };

            Replay replay = new Replay()
            {
                RecipientId = "recipientId",
                IsRead      = false,
            };

            message.Replays.Add(replay);
            await repository.AddAsync(message);

            await repository.SaveChangesAsync();

            var actualResult = service.GetCountOfAllUnReadMessagesByUserId("recipientId");

            Assert.Equal("1", actualResult);
        }
示例#20
0
        public async Task GetAllCompanyTrucksByUserIdAsync_WithNonUserTrucks_ShouldReturnEmptyList()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Truck      = new Truck(),
                SteuUser   = new SteuUser()
                {
                    Id      = "userId",
                    Company = new Company()
                    {
                        Id = "company",
                    },
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            var actualResult = await service.GetAllCompanyTrucksByUserIdAsync(1, 10, "asdasd");

            Assert.Empty(actualResult);
        }
        public async Task AtNoPresentProductValueAddingShouldReturnFalse()
        {
            var builder = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var dbContext = new ApplicationDbContext(builder.Options);

            var userRepository      = new EfDeletableEntityRepository <FamilyKitchenUser>(dbContext);
            var favoritesRepository = new EfRepository <FamilyKitchenUserFavoriteProduct>(dbContext);
            var productRepository   = new EfDeletableEntityRepository <ShopProduct>(dbContext);

            var favoritesService = new FavoriteProductService(userRepository, favoritesRepository, productRepository);

            await userRepository.AddAsync(new FamilyKitchenUser
            {
                UserName     = "******",
                Email        = "*****@*****.**",
                ClientCard   = new ClientCard(),
                ShoppingCart = new ShoppingCart(),
            });

            await userRepository.SaveChangesAsync();

            await productRepository.AddAsync(new ShopProduct { Id = 2, Name = "boza", Price = 2m, Discount = 0, });

            await productRepository.SaveChangesAsync();

            var actAdd = await favoritesService.Add(22, "*****@*****.**");

            Assert.False(actAdd);
        }
示例#22
0
        public async Task GetAllCompanyTrucksByUserIdAsync_WithIncorectUserId_ShouldReturnArgumentNullException()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Truck      = new Truck(),
                SteuUser   = new SteuUser()
                {
                    Id      = "asdasd",
                    Company = new Company()
                    {
                        Id = "companyId",
                    },
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            await Assert.ThrowsAsync <ArgumentNullException>(()
                                                             => service.GetAllCompanyTrucksByUserIdAsync(1, 10, "userId"));
        }
示例#23
0
        public async Task GetCompletedLessonsTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var lessonRepository = new EfDeletableEntityRepository <Lesson>(new ApplicationDbContext(options.Options));

            foreach (var lesson in this.GetLessonData())
            {
                await lessonRepository.AddAsync(lesson);

                await lessonRepository.SaveChangesAsync();
            }

            var mockCourseRepository = new Mock <IDeletableEntityRepository <Course> >();
            var userLessonRepository = new EfRepository <UserLesson>(new ApplicationDbContext(options.Options));
            var service = new LessonsService(lessonRepository, userLessonRepository, mockCourseRepository.Object);
            await service.CreateUserLesson("User1", "1");

            await service.CreateUserLesson("User1", "2");

            await service.CreateUserLesson("User2", "2");

            var lessonsPassed = service.GetCompletedLessons("course1", "User1");

            Assert.Equal(2, lessonsPassed);
        }
示例#24
0
        public async Task GetCountOfTrucksAsync_WithData_ShouldReturnCount()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Truck      = new Truck(),
                SteuUser   = new SteuUser()
                {
                    Id = "userId",
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            var actualResult = await service.GetCountOfTrucksAsync();

            Assert.Equal(1, actualResult);
        }
示例#25
0
        public void TestDeleteGameAsync()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            var repository         = new EfDeletableEntityRepository <Game>(new ApplicationDbContext(options.Options));
            var commentsRepository = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));

            var service = new GamesService(repository, commentsRepository);

            var game = new Game
            {
                Title       = "test",
                CategoryId  = 1,
                Description = "sds",
                ReleaseDate = DateTime.UtcNow,
                CompanyName = "tests",
                PictureUrl  = "est",
            };

            repository.AddAsync(game).GetAwaiter().GetResult();
            repository.SaveChangesAsync().GetAwaiter().GetResult();

            var firstCounter = repository.All().Count();

            service.DeleteGameAsync(1).GetAwaiter().GetResult();

            var secondCounter = repository.All().Count();

            Assert.True(firstCounter == 1 && secondCounter == 0);
        }
示例#26
0
        public async Task GetTruckDetailsByIdAsync_WithCorrectData_ShouldReturnDetailsTruckViewModel()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Truck      = new Truck(),
                SteuUser   = new SteuUser()
                {
                    Id        = "asdasd",
                    FirstName = "Pesho",
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            var actualresutlt = await service.GetTruckDetailsByIdAsync <DetailsTruckViewModel>("orderId");

            Assert.Equal("Pesho", actualresutlt.SteuUserFirstName);
        }
示例#27
0
        public async Task GetArticleById()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;
            var dbContext = new ApplicationDbContext(options);

            var repositoryArticle              = new EfDeletableEntityRepository <Article>(dbContext);
            var repositoryArticlePicture       = new EfRepository <ArticlePicture>(dbContext);
            var repositoryUserFavouriteArticle = new EfDeletableEntityRepository <UserFavouriteArticle>(dbContext);

            var article = new Article
            {
                Id         = 1,
                Title      = "Test",
                Content    = "Test",
                CategoryId = 1,
                UserId     = "1",
            };

            await repositoryArticle.AddAsync(article);

            await repositoryArticle.SaveChangesAsync();

            AutoMapperConfig.RegisterMappings(typeof(ArticleByIdTestViewModel).GetTypeInfo().Assembly);

            var service = new ArticlePostsService(repositoryArticle, repositoryArticlePicture, repositoryUserFavouriteArticle);

            var articleResult = await service.GetByIdAsync <ArticleByIdTestViewModel>(article.Id);

            Assert.Equal(article.Id, articleResult.Id);
        }
示例#28
0
        public async Task GetTruckDetailsByIdAsync_WithNullOrderId_ShouldReturnArgumentNullException()
        {
            var           context    = SteuDbContextInMemoryFactory.InitializeContext();
            TrucksService service    = IntializeLoadService(context);
            var           repository = new EfDeletableEntityRepository <Order>(context);

            var order = new Order()
            {
                Id         = "orderId",
                IsDeleted  = false,
                ExpireTime = DateTime.UtcNow.AddDays(7),
                Truck      = new Truck(),
                SteuUser   = new SteuUser()
                {
                    Id        = "asdasd",
                    FirstName = "Pesho",
                },
            };

            await repository.AddAsync(order);

            await repository.SaveChangesAsync();

            await Assert.ThrowsAsync <ArgumentNullException>(()
                                                             => service.GetTruckDetailsByIdAsync <DetailsTruckViewModel>(null));
        }
        public async Task GetByRecipeId_WithNonExistentRecipeId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ReviewService GetByRecipeId() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedRecipeAndUser(context);

            var reviewRepository = new EfDeletableEntityRepository <Review>(context);
            var reviewService    = this.GetReviewService(reviewRepository);
            var review           = new Review
            {
                Comment    = "Comment",
                Rating     = 5,
                RecipeId   = context.Recipes.First().Id,
                ReviewerId = context.Recipes.First().Id,
            };
            await reviewRepository.AddAsync(review);

            await reviewRepository.SaveChangesAsync();

            var nonExistentRecipeId = Guid.NewGuid().ToString();

            // Act
            var actualResult = (await reviewService
                                .GetByRecipeId(nonExistentRecipeId)
                                .ToListAsync())
                               .Count;
            var expectedResult = 0;

            // Assert
            Assert.True(expectedResult == actualResult, errorMessagePrefix + " " + "Collections count mismatch.");
        }
        public async Task AreTwoUsersFriendsAsyncShouldWorkCorrectly()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            var dbContext = new ApplicationDbContext(options);

            var friendRepository        = new EfDeletableEntityRepository <Friend>(dbContext);
            var friendRequestRepository = new EfDeletableEntityRepository <FriendRequest>(dbContext);

            var service = new FriendService(friendRequestRepository, friendRepository);

            var newFriendShip = new Friend
            {
                SenderId   = "1",
                ReceiverId = "2",
            };

            await friendRepository.AddAsync(newFriendShip);

            await friendRepository.SaveChangesAsync();

            var resultTrue = await service.AreTwoUsersFriendsAsync(newFriendShip.SenderId, newFriendShip.ReceiverId);

            var resultFalse = await service.AreTwoUsersFriendsAsync("4", "3");

            Assert.True(resultTrue);
            Assert.False(resultFalse);
        }