예제 #1
0
        public async Task EditAsync_WithCorrectData_ShouldSuccessfullyEdit()
        {
            // Arrange
            var context         = ApplicationDbContextInMemoryFactory.InitializeContext();
            var topicRepository = new EfDeletableEntityRepository <Topic>(context);
            var userRepository  = new EfDeletableEntityRepository <ApplicationUser>(context);
            var topicsService   = new TopicsService(topicRepository, userRepository);

            var createInputModel = new CreateTopicInputModel()
            {
                Title   = "TestTitle",
                Content = "TestContent_TestContent_TestContent_TestContent_TestContent_TestContent",
            };

            await topicsService.CreateAsync(createInputModel);

            var topic = topicRepository.All().FirstOrDefault(t => t.Title == "TestTitle");

            var editInputModel = new TopicEditViewModel()
            {
                Id      = topic.Id,
                Title   = "Edited_TestTitle",
                Content = "Edited_TestContent_TestContent_TestContent_TestContent_TestContent_TestContent",
            };

            // Act
            var expectedTopicTitle   = "Edited_TestTitle";
            var expectedTopicContent = "Edited_TestContent_TestContent_TestContent_TestContent_TestContent_TestContent";
            await topicsService.EditAsync(editInputModel);

            // Assert
            topic = await topicRepository.GetByIdWithDeletedAsync(editInputModel.Id);

            Assert.Equal(expectedTopicTitle, topic.Title);
            Assert.Equal(expectedTopicContent, topic.Content);
        }
예제 #2
0
        public async Task AddProductsToOrder_WithExistingOrderAndNoProducts_ShouldReturnFalse()
        {
            string onTrueErrorMessage = "The method returned true upon no products input.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var orderService = new OrderService(context);

            var products = await this.GetProductsForOrder();

            OrderBindingModel model = new OrderBindingModel
            {
                DeliveryType = DeliveryType.Express,
                PaymentType  = PaymentType.OnDelivery,
                Products     = products,
            };

            var orderId = await orderService.CreateOrder(model);

            // Passing null instead of the products
            var methodResult = await orderService.AddProductsToOrder(orderId, null);

            Assert.False(methodResult, onTrueErrorMessage);
        }
예제 #3
0
        public async Task GetShoppingListsByUserIdAsync_WithNonExistentUserId_ShouldReturnEmptyCollection()
        {
            var errorMessagePrefix = "UserShoppingListService GetShoppingListsByUserIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userShoppingListRepository = new EfRepository <UserShoppingList>(context);
            var userShoppingListService    = new UserShoppingListService(userShoppingListRepository);

            await this.SeedDataAsync(context);

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

            // Act
            var actualResult = (await userShoppingListService
                                .GetShoppingListsByUserIdAsync(nonExistentUserId))
                               .ToList()
                               .Count;
            var expectedResult = 0;

            // Assert
            Assert.True(expectedResult == actualResult, errorMessagePrefix + " " + "Collection is not empty.");
        }
예제 #4
0
        public async Task GetByIdAsync_WithExistentUserId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "UserService GetByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context        = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userRepository = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userService    = this.GetUserService(userRepository, context);

            await this.SeedDataForGetByIdMethod(context);

            var userId = userRepository.All().First().Id;

            // Act
            var actualResult = await userService.GetByIdAsync(userId);

            var expectedResult = userRepository
                                 .All()
                                 .First()
                                 .To <ApplicationUserServiceModel>();

            // Assert
            Assert.True(expectedResult.Id == actualResult.Id, errorMessagePrefix + " " + "Id is not returned properly.");
            Assert.True(expectedResult.FullName == actualResult.FullName, errorMessagePrefix + " " + "FullName is not returned properly.");
            Assert.True(expectedResult.Biography == actualResult.Biography, errorMessagePrefix + " " + "Biography is not returned properly.");
            Assert.True(expectedResult.ProfilePhoto == actualResult.ProfilePhoto, errorMessagePrefix + " " + "ProfilePhoto is not returned properly.");
            Assert.True(expectedResult.Lifestyle.Id == actualResult.Lifestyle.Id, errorMessagePrefix + " " + "Lifestyle is not returned properly.");
            Assert.True(expectedResult.HasAdditionalInfo == actualResult.HasAdditionalInfo, errorMessagePrefix + " " + "HasAdditionalInfo is not returned properly.");
            Assert.True(expectedResult.Allergies.First().Allergen.Id == actualResult.Allergies.First().Allergen.Id, errorMessagePrefix + " " + "Allergen is not returned properly.");
            Assert.True(expectedResult.Recipes.First().Id == actualResult.Recipes.First().Id, errorMessagePrefix + " " + "Recipe is not returned properly.");
            Assert.True(expectedResult.FavoriteRecipes.First().Recipe.Id == actualResult.FavoriteRecipes.First().Recipe.Id, errorMessagePrefix + " " + "FavoriteRecipe is not returned properly.");
            Assert.True(expectedResult.CookedRecipes.First().Recipe.Id == actualResult.CookedRecipes.First().Recipe.Id, errorMessagePrefix + " " + "CookedRecipe is not returned properly.");
            Assert.True(expectedResult.Reviews.First().Id == actualResult.Reviews.First().Id, errorMessagePrefix + " " + "Review is not returned properly.");
            Assert.True(expectedResult.ShoppingLists.First().ShoppingList.Id == actualResult.ShoppingLists.First().ShoppingList.Id, errorMessagePrefix + " " + "ShoppingList is not returned properly.");
        }
예제 #5
0
        public async Task TestCreateASyncMethodWithWrongData()
        {
            // Arrange
            var context           = ApplicationDbContextInMemoryFactory.InitializeContext();
            var articleRepository = new EfDeletableEntityRepository <Article>(context);

            var articlesService = new ArticlesService(articleRepository);

            var inputModel = new CreateArticleViewModel
            {
                ImgUrl  = string.Empty,
                Content = string.Empty,
                Title   = string.Empty,
            };

            // Act

            // Assert

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await articlesService.CreateAsync(inputModel, "1");
            });
        }
        public async Task DeleteUserAsyncShouldDeleteUserAccountCorrectly()
        {
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var testAccountRepository = new EfDeletableEntityRepository <Account>(context);
            var testAccounts          = TestDataHelpers.GetTestData();

            foreach (var acc in testAccounts)
            {
                await testAccountRepository.AddAsync(acc);

                await testAccountRepository.SaveChangesAsync();
            }

            var testUserRepository = new Mock <IDeletableEntityRepository <ApplicationUser> >();

            testUserRepository
            .Setup(a => a.GetByIdWithDeletedAsync(It.IsAny <string>()))
            .ReturnsAsync(new ApplicationUser()
            {
                Id        = "1",
                IsDeleted = false,
            });
            testUserRepository
            .Setup(a => a.Delete(It.IsAny <ApplicationUser>()));
            testUserRepository
            .Setup(a => a.SaveChangesAsync());

            var testAccountManagementService = new AccountManagementService(this.userManager.Object, testUserRepository.Object, testAccountRepository, this.positionService.Object, this.feePaymentsRepository.Object);

            await testAccountManagementService.DeleteUserAsync("1", 1);

            var account = testAccountRepository.AllWithDeleted().FirstOrDefault(a => a.Id == 1);

            Assert.IsTrue(account.IsDeleted);
        }
        public async Task CheckIfActiveTaskIsComplete()
        {
            var context      = ApplicationDbContextInMemoryFactory.InitializeContext();
            var tasksService = this.GetTasksService(context);

            var seeder = new UsersSeeder();
            await seeder.SeedUsers(context);

            var user1 = context.Users.First(x => x.UserName == "User1");
            var user2 = context.Users.First(x => x.UserName == "User2");

            await context.TasksGather.AddAsync(new TaskGather
            {
                Id         = Guid.NewGuid().ToString(),
                UserId     = user1.Id,
                IsComplete = false,
                EndTime    = DateTime.UtcNow.AddDays(-1),
            });

            await context.TasksGather.AddAsync(new TaskGather
            {
                Id         = Guid.NewGuid().ToString(),
                UserId     = user2.Id,
                IsComplete = false,
                EndTime    = DateTime.UtcNow.AddDays(1)
            });

            await context.SaveChangesAsync();

            var returnsTrue = await tasksService.CheckGatheringTaskCompletion(user1.Id);

            var returnsFalse = await tasksService.CheckGatheringTaskCompletion(user2.Id);

            Assert.True(returnsTrue == true, $"User didn't complete his task.");
            Assert.True(returnsFalse == false, $"User completed his task when he shouldn't have.");
        }
        public async Task AddReview_WithCorrectData_ShouldCreateSuccessfully()
        {
            string onFalseErrorMessage = "The method returned false on valid creation model.";
            string onNullErrorMessage  = "The review was not added to the database.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var reviewService = new ReviewService(context);

            ReviewBindingModel model = new ReviewBindingModel
            {
                ClientFullName = "TestClient",
                Comment        = "TestComment",
                Rating         = 5,
            };

            var methodResult = await reviewService.AddReview(model);

            Assert.True(methodResult, onFalseErrorMessage);

            var reviewExists = context.Reviews.FirstOrDefaultAsync(x => x.ClientFullName == model.ClientFullName);

            AssertExtensions.NotNullWithMessage(reviewExists, onNullErrorMessage);
        }
예제 #9
0
        public async Task RecommendProduct_WithExistingProduct_ShouldReturnTrue()
        {
            string onFalseErrorMessage = "The method returned false on existing product.";
            string onNullErrorMessage  = "The product was either not in the database or not recommended.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var cloudinaryServiceMock = new Mock <ICloudinaryService>();

            var productService = new ProductService(context, cloudinaryServiceMock.Object);

            // Get the product and seed it
            var product = this.GetProduct();

            await this.SeedSingleProduct(context);

            var methodResult = await productService.RecommendProduct(product.Id);

            Assert.True(methodResult, onFalseErrorMessage);

            var productFromDatabase = context.Products.FirstOrDefaultAsync(p => p.IsHidden == true);

            AssertExtensions.NotNullWithMessage(productFromDatabase, onNullErrorMessage);
        }
        public async Task AddSuggestProduct_WithCorrectData_ShouldSuccessfullyAddSuggestion()
        {
            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var groupRepository        = new EfDeletableEntityRepository <Product_Group>(context);
            var productRepository      = new EfDeletableEntityRepository <Product>(context);
            var fireplacesRepository   = new EfDeletableEntityRepository <Fireplace_chamber>(context);
            var suggestItemsReposotory = new EfDeletableEntityRepository <SuggestProduct>(context);

            var groupService   = new GroupService(groupRepository);
            var prodcutService = new ProductService(productRepository, groupService);
            var sugestItemsRepositoryService = new SuggestProdcut(suggestItemsReposotory);
            var cloudinaryService            = new FakeCloudinary();
            var fireplaceService             = new FireplaceService(fireplacesRepository, groupService, prodcutService, cloudinaryService, sugestItemsRepositoryService);

            var seeder = new DbContextTestsSeeder();
            await seeder.SeedUsersAsync(context);

            await seeder.SeedGroupAsync(context);

            await seeder.SeedProdcutAsync(context);

            await seeder.SeedFireplacesAsync(context);

            string[] selectedFireplace = new string[] { "Гк Оливия" };

            // Act
            AutoMapperConfig.RegisterMappings(typeof(FireplaceInputModel).Assembly);
            await fireplaceService.AddSuggestionToFireplaceAsync("Гк Мая", "abc1", selectedFireplace, null, null, null);

            var count = context.SuggestProducts.Count();

            // Assert
            Assert.True(count == 1, string.Format(ErrorMessage, "Add suggestion method"));
        }
        public void TestGetAllFireplaces_WithoutAnyData_ShouldReturnEmptyList()
        {
            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var groupRepository        = new EfDeletableEntityRepository <Product_Group>(context);
            var productRepository      = new EfDeletableEntityRepository <Product>(context);
            var fireplacesRepository   = new EfDeletableEntityRepository <Fireplace_chamber>(context);
            var suggestItemsReposotory = new EfDeletableEntityRepository <SuggestProduct>(context);

            var groupService   = new GroupService(groupRepository);
            var prodcutService = new ProductService(productRepository, groupService);
            var sugestItemsRepositoryService = new SuggestProdcut(suggestItemsReposotory);
            var cloudinaryService            = new FakeCloudinary();
            var fireplaceService             = new FireplaceService(fireplacesRepository, groupService, prodcutService, cloudinaryService, sugestItemsRepositoryService);

            // Act
            AutoMapperConfig.RegisterMappings(typeof(AllFireplaceViewModel).Assembly);
            var result = fireplaceService.GetAllFireplaceAsync <AllFireplaceViewModel>(TypeOfChamber.Basic.ToString());
            var count  = result.ToList().Count;

            // Assert
            Assert.True(count == 0, string.Format(ErrorMessage, "Get all fireplaces empty list"));
        }
예제 #12
0
        public async Task GetRemainingMinutesToCreateTopic_WhenThereIsOtherTopicWith30Minutes_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 = "******",
            };

            user.Topics.Add(new Topic()
            {
                Title = "testTitle",
            });

            user.Topics.Add(new Topic()
            {
                Title = "secondTestTitle",
            });

            await userRepository.AddAsync(user);

            await userRepository.SaveChangesAsync();

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

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

            // Assert
            Assert.Equal(expectedRemainingMinutes, actualRemainingMinutes);
        }
예제 #13
0
        public async Task GetTopicsGetTopicsCountOfUser_ShouldReturnCorrectCount()
        {
            // 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 = "******",
            };

            user.Topics.Add(new Topic()
            {
                Title = "testTitle",
            });

            user.Topics.Add(new Topic()
            {
                Title = "secondTestTitle",
            });

            await userRepository.AddAsync(user);

            await userRepository.SaveChangesAsync();

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

            // Act
            var expectedTopicsCount = 2;
            var actualTopicsCount   = topicsService.GetTopicsCountOfUser(userId);

            // Assert
            Assert.Equal(expectedTopicsCount, actualTopicsCount);
        }
예제 #14
0
        public async Task EditAsync_WithIncorrectData_ShouldThrowArgumentNullException()
        {
            // Arrange
            var incorrentInputModelId = "IncorrentId";
            var context         = ApplicationDbContextInMemoryFactory.InitializeContext();
            var topicRepository = new EfDeletableEntityRepository <Topic>(context);
            var userRepository  = new EfDeletableEntityRepository <ApplicationUser>(context);
            var topicsService   = new TopicsService(topicRepository, userRepository);

            var editInputModel = new TopicEditViewModel()
            {
                Id      = incorrentInputModelId,
                Title   = "Edited_TestTitle",
                Content = "Edited_TestContent_TestContent_TestContent_TestContent_TestContent_TestContent",
            };

            // Act

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await topicsService.EditAsync(editInputModel);
            });
        }
예제 #15
0
        public async Task GetAllProductTypes_WithDummyData_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ProductsService GetAllProductTypesAsync() method does not work properly.";

            var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedData(dbContext);

            this.productsService = new ProductsService(dbContext);

            var actualResult = await this.productsService.GetAllProductTypes <ProductTypesServiceModel>().ToListAsync();

            var expectedResult = this.GetDummyData().Select(p => p.ProductType).To <ProductTypesServiceModel>().ToList();

            Assert.True(actualResult.Count == expectedResult.Count, errorMessagePrefix);

            // TODO:
            // for (int i = 0; i < expectedResult.Count; i++)
            // {
            //     var expectedEntry = expectedResult[i];
            //     var actualEntry = actualResult[i];
            //     Assert.True(expectedEntry.Name == actualEntry.Name, errorMessagePrefix + " " + "Name is not returned  properly.");
            // }
        }
예제 #16
0
        public async Task GetProducts_WithNullInput_ShouldReturnAllProductsTheSameOrder()
        {
            string onCountDifferenceErrorMessage = "The count of the returned products is not correct.";
            string onFalseErrorMessage           = "The returned products are not correct.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var cloudinaryServiceMock = new Mock <ICloudinaryService>();

            var productService = new ProductService(context, cloudinaryServiceMock.Object);

            // Get multiple products and seed the categories with the products
            var products = this.GetMultipleProducts();

            await this.SeedMultipleSubCategoriesAndCategories(context);

            await this.SeedMultipleProducts(context);

            string emptyString = string.Empty;

            var resultProducts = await productService.GetProducts(null, null, 0);

            // (They should be 2 because 2 products are recommended)
            var expectedProductsCount = 2;

            // Making sure the count of the returned products is correct before comparing them
            AssertExtensions.EqualCountWithMessage(
                expectedProductsCount, resultProducts.Count(), onCountDifferenceErrorMessage);

            foreach (var prd in resultProducts)
            {
                // The 2 recommended product names
                Assert.True(
                    prd.Name == "thirdProductName" || prd.Name == "sixthProductName", onFalseErrorMessage);
            }
        }
        public async Task CreateRecipientNotNullTest()
        {
            var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();

            var recipientRepository             = new EfDeletableEntityRepository <Recipient>(dbContext);
            var hospitalDataRepository          = new EfDeletableEntityRepository <HospitalData>(dbContext);
            var recipientReques                 = new EfDeletableEntityRepository <RecipientRequest>(dbContext);
            var recipientHospitalDataRepository = new EfDeletableEntityRepository <RecipientHospitalData>(dbContext);

            var service = new RecipientsService(
                recipientRepository,
                hospitalDataRepository,
                recipientReques,
                recipientHospitalDataRepository);

            await SeedDataAsync(dbContext);

            var user = recipientRepository
                       .All()
                       .Where(u => u.Age == 85)
                       .FirstOrDefault();

            Assert.NotNull(user);
        }
예제 #18
0
        public async Task GetProducts_WithGivenAllFilterOptions_ShouldReturnTheProductsMatchingAllTheGivenCriteria()
        {
            string onCountDifferenceErrorMessage  = "The returned products are not with the same count as expected.";
            string onStringDifferenceErrorMessage = "The products sorting is wrong.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var cloudinaryServiceMock = new Mock <ICloudinaryService>();

            var productService = new ProductService(context, cloudinaryServiceMock.Object);

            // Get multiple products and seed the categories with the products
            var products = this.GetMultipleProducts();

            await this.SeedMultipleSubCategoriesAndCategories(context);

            await this.SeedMultipleProducts(context);

            // Should return products ordered by name descending
            string searchString  = "first";
            string subCategoryId = "A-SubCategoryId-forFirst";
            int    sortBy        = 4;

            var resultProducts = await productService.GetProducts(searchString, subCategoryId, sortBy);

            var expectedCount = 2;

            AssertExtensions.EqualCountWithMessage(
                expectedCount, resultProducts.Count(), onCountDifferenceErrorMessage);

            var expectedFirstProductName = "B-firstProductName";
            var firstActualProductName   = resultProducts.First().Name;

            AssertExtensions.EqualStringWithMessage(
                expectedFirstProductName, firstActualProductName, onStringDifferenceErrorMessage);
        }
        public async Task GetAllHospitalsShouldBeOneTest()
        {
            var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();

            MapperInitializer.InitializeMapper();

            var hospitalDataRepository      = new EfDeletableEntityRepository <HospitalData>(dbContext);
            var usersRepository             = new EfDeletableEntityRepository <ApplicationUser>(dbContext);
            var rolesRepository             = new EfDeletableEntityRepository <ApplicationRole>(dbContext);
            var appUsersHospitalRepository  = new EfDeletableEntityRepository <ApplicationUserHospitalData>(dbContext);
            var recipientRepository         = new EfDeletableEntityRepository <Recipient>(dbContext);
            var bloodBankRepository         = new EfDeletableEntityRepository <BloodBank>(dbContext);
            var hospitalBloodBankRepository = new EfDeletableEntityRepository <HospitalDataBloodBank>(dbContext);
            var bagRepository = new EfDeletableEntityRepository <BloodBag>(dbContext);

            var userManager = this.GetUserManagerMock();

            var service = new HospitalsService(
                usersRepository,
                hospitalDataRepository,
                rolesRepository,
                appUsersHospitalRepository,
                recipientRepository,
                bloodBankRepository,
                hospitalBloodBankRepository,
                bagRepository);

            await SeedDataAsync(dbContext);

            var user = usersRepository.All().FirstOrDefault(u => u.UserName == "User1");
            await service.CreateHospitalProfileAsync(this.SeedInputs(), user.Id);

            var result = service.GetAllHospitals <HospitalProfileInputModel>().Count();

            Assert.Equal(1, result);
        }
예제 #20
0
        public async Task FindProduct_WithExistingId_ShouldSuccessfullyFind()
        {
            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var groupRepository   = new EfDeletableEntityRepository <Product_Group>(context);
            var productRepository = new EfDeletableEntityRepository <Product>(context);

            var groupService   = new GroupService(groupRepository);
            var productService = new ProductService(productRepository, groupService);

            var seeder = new DbContextTestsSeeder();
            await seeder.SeedGroupAsync(context);

            await seeder.SeedProdcutAsync(context);

            // Act
            var result = productService.GetById("abc").Name;

            var actual = context.Products.SingleOrDefault(p => p.Id == "abc").Name;

            // Assert
            AssertExtension.EqualsWithMessage(actual, result, string.Format(ErrorMessage, "ProductGetIdByNameAndGroup"));
        }
예제 #21
0
        public async Task SetShoppingListAsync_WithNonExistentUserId_ShouldThrowArgumentNullException()
        {
            // Arrange
            MapperInitializer.InitializeMapper();
            var context        = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userRepository = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userService    = this.GetUserService(userRepository, context);
            await context.ShoppingLists.AddAsync(new ShoppingList());

            await context.SaveChangesAsync();

            var nonExistentUserId        = Guid.NewGuid().ToString();
            var shoppingListServiceModel = context.ShoppingLists
                                           .First()
                                           .To <ShoppingListServiceModel>();

            // Act

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await userService.SetShoppingListAsync(nonExistentUserId, shoppingListServiceModel);
            });
        }
        public async Task Edit_WithCorrectData_ShouldEditServiceCorrectly()
        {
            var errorMessagePrefix = "ServicesService EditAsync() method does not work properly.";

            var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedData(dbContext);

            this.servicesService = new ServicesService(dbContext);

            var expectedResult = dbContext.Services.First().To <ServicesServiceModel>();

            expectedResult.Name        = "Name";
            expectedResult.Picture     = "Picture";
            expectedResult.Description = "Description";

            await this.servicesService.EditAsync(expectedResult.Id, expectedResult);

            var actualResult = dbContext.Services.First().To <ServicesServiceModel>();

            Assert.True(expectedResult.Name == actualResult.Name, errorMessagePrefix + " " + "Name is not return properly.");
            Assert.True(expectedResult.Description == actualResult.Description, errorMessagePrefix + " " + "Description is not return properly.");
            Assert.True(expectedResult.Picture == actualResult.Picture, errorMessagePrefix + " " + "Picture is not return properly.");
        }
예제 #23
0
        public async Task TestGetAllMethod()
        {
            var context           = ApplicationDbContextInMemoryFactory.InitializeContext();
            var articleRepository = new EfDeletableEntityRepository <Article>(context);

            var articlesService = new ArticlesService(articleRepository);

            var seeder = new ArticlesTestsSeeder();

            for (int i = 0; i < 10; i++)
            {
                var inputModel = new CreateArticleViewModel
                {
                    ImgUrl  = $"TT{i}{i * 2}asd",
                    Content = $"Ten{i}{i * 2}",
                    Title   = $"Article{i}",
                };
                await articlesService.CreateAsync(inputModel, i.ToString());
            }

            var result = articlesService.GetAll <IndexArticleViewModel>();

            Assert.Equal(10, result.Count());
        }
예제 #24
0
        public async Task DeleteByIdAsync_WithExistentId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "NutritionalValueService DeleteByIdAsync() method does not work properly.";

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

            await this.SeedDataAsync(context);

            var nutritionalValueRepository = new EfDeletableEntityRepository <NutritionalValue>(context);
            var nutritionalValueService    = new NutritionalValueService(nutritionalValueRepository);
            var existentId = nutritionalValueRepository.All().First().Id;

            // Act
            var nutritionalValuesCount = nutritionalValueRepository.All().Count();
            await nutritionalValueService.DeleteByIdAsync(existentId);

            var actualResult   = nutritionalValueRepository.All().Count();
            var expectedResult = nutritionalValuesCount - 1;

            // Assert
            Assert.True(actualResult == expectedResult, errorMessagePrefix + " " + "NutritionalValues count is not reduced.");
        }
예제 #25
0
        public async Task EditProfileAsync_ReturnsTrueAndMakesChanges_IfTheModelIsCorrect()
        {
            var errorMessageBool = "EditProfileAsync did not return true";

            MapperInitializer.InitializeMapper();
            var context        = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userRepository = new EfDeletableEntityRepository <ApplicationUser>(context);
            var userService    = this.GetUserService(userRepository, context);
            var seeder         = new UserTestSeeder();
            await seeder.SeedUsersWithAddressesAsync(context);

            var userWithoutAddresses = context.Users.First(x => x.UserName == "UserWithoutAddresses");

            var profileEditInputModel = new ProfileEdintInputModel()
            {
                Id       = userWithoutAddresses.Id,
                Username = "******",
            };

            var result = await userService.EditProfileAsync(profileEditInputModel);

            Assert.True(result, errorMessageBool);
            Assert.Equal("Changed", userWithoutAddresses.UserName);
        }
예제 #26
0
        public async Task TestGetExercisesByCategoryAsync_WithValidData_ShouldReturnCorrectExercises()
        {
            MapperInitializer.InitializeMapper();
            var context    = ApplicationDbContextInMemoryFactory.InitializeContext();
            var repository = new EfDeletableEntityRepository <Exercise>(context);

            await repository.AddAsync(new Exercise { Name = "first", MuscleGroup = MuscleGroup.Abs });

            await repository.AddAsync(new Exercise { Name = "second", MuscleGroup = MuscleGroup.Abs });

            await repository.AddAsync(new Exercise { Name = "third", MuscleGroup = MuscleGroup.Shoulders });

            await repository.AddAsync(new Exercise { Name = "fourth", MuscleGroup = MuscleGroup.Upper_Legs });

            await repository.SaveChangesAsync();

            var service = new ExercisesService(repository);

            var exercises = await service.GetExercisesByCategoryAsync(false, null, MuscleGroup.Abs.ToString(), null);

            Assert.Equal(2, exercises.Count);
            Assert.Equal("first", exercises[0].Name);
            Assert.Equal("second", exercises[1].Name);
        }
예제 #27
0
        public async Task DeleteByShoppingListIdAsync_WithExistentShoppingListId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "UserShoppingListService DeleteByShoppingListIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();
            var userShoppingListRepository = new EfRepository <UserShoppingList>(context);
            var userShoppingListService    = new UserShoppingListService(userShoppingListRepository);

            await this.SeedDataAsync(context);

            var shoppingListId = context.ShoppingLists.First(x => x.Ingredients == "Ingredients 1").Id;

            // Act
            var userShoppingListsCount = userShoppingListRepository.All().Count();
            await userShoppingListService.DeleteByShoppingListIdAsync(shoppingListId);

            var actualResult   = userShoppingListRepository.All().Count();
            var expectedResult = userShoppingListsCount - 1;

            // Assert
            Assert.True(expectedResult == actualResult, errorMessagePrefix + " " + "Count is not reduced properly.");
        }
예제 #28
0
        public async Task Create_WithCorrectData_ShouldSuccsessfullyCreate()
        {
            var dbContext = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedData(dbContext);

            this.productsService = new ProductsService(dbContext);

            var testProductService = new ProductsServiceModel
            {
                Name        = "cleaning",
                Description = "cleaning desc",
                Picture     = "default",
                ProductType = new ProductTypesServiceModel
                {
                    Name = "cleaning",
                },
            };

            var expectedResultId = 3;
            var actualResultId   = await this.productsService.CreateProductAsync(testProductService);

            Assert.Equal(actualResultId, expectedResultId);
        }
예제 #29
0
        public async Task GetAllUserAddresses_WithNonExistingUser_ShouldReturnCorrectAddresses()
        {
            string onNonEmptyCollectionErrorMessage = "The method does not return the expected count.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var addressService = new AddressService(context);

            // passing a non-existing user Id
            var addresses = await addressService.GetAllUserAddresses("randomId");

            var expectedCount = 0;
            var actualCount   = 0;

            foreach (var address in addresses)
            {
                actualCount++;
            }

            AssertExtensions.EqualCountWithMessage(
                expectedCount,
                actualCount,
                onNonEmptyCollectionErrorMessage);
        }
예제 #30
0
        public async Task OrderProducts_OrdersProductsCorectly()
        {
            MapperInitializer.InitializeMapper();
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var productRepository  = new EfDeletableEntityRepository <Product>(context);
            var productsTestSeeder = new ProductTestSeeder();
            var productsService    = this.GetProductsService(productRepository, context);

            await productsTestSeeder.SeedProducts(context);

            var products = productRepository.All().To <ProductSingleViewModel>();

            var priceDesc = "price-highest-to-lowest";
            var priceAsc  = "price-lowest-to-highest";

            var productsActualDesc = productsService.OrderProducts(priceDesc, products);
            var productsActualAsc  = productsService.OrderProducts(priceAsc, products);

            var productExpectedDesc = productRepository.All().OrderByDescending(x => x.Price).To <ProductSingleViewModel>();
            var productExpectedAsc  = productRepository.All().OrderBy(x => x.Price).To <ProductSingleViewModel>();

            Assert.Equal(productExpectedDesc, productsActualDesc);
            Assert.Equal(productExpectedAsc, productsActualAsc);
        }