コード例 #1
0
        public async Task ReturnCorrectUpdatedWallet()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnCorrectUpdatedWallet")
                             .Options;

            decimal stake = 1000;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 0,
                User     = user,
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                var updateWallet  = await walletService.UpdateUserWallet(user, stake);

                Assert.AreEqual(stake, updateWallet.Balance);
            }
        }
コード例 #2
0
        public async Task ThrowException_WhenAParameter_IsNotPassed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_WhenAParameter_IsNotPassed")
                             .Options;

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var amountsDictionary = Enum.GetNames(typeof(TransactionType)).ToDictionary(name => name, value => 0m);

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 0,
                User     = user,
            };

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = null // here there is no passed parameter
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            var getCurrencySymbol = CultureReferences.CurrencySymbols.TryGetValue(userWallet.Currency.ToString(), out string currencySymbol);
            var currencies        = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.GetUserWallet(user));
            }
        }
コード例 #3
0
        public async Task ThrowException_When_NullOrInvalidParamsPassed()
        {
            // Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_NullOrInvalidParamsPassed")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User();

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = null
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id));
            }
        }
コード例 #4
0
        public async Task ReturnCorrectData_WhenParamatersAreValidAndUserExists()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnCorrectData_WhenParamatersAreValidAndUserExists")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            var foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 0m)
            };

            foreignExchangeServiceMock.Setup(exchange => exchange.GetConvertionRates())
            .Returns(Task.FromResult(foreignExchangeDTO));

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testWallet);

                await actContext.SaveChangesAsync();

                testUser.Wallet = testWallet;
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                var result = await command.GetUserInfo(testUser.Id);

                Assert.IsInstanceOfType(result, typeof(UserInfoDTO));
                Assert.AreEqual(testUser.UserName, result.Username);
                Assert.AreEqual(testWallet.Balance, result.Balance);
                Assert.AreEqual(walletCurrency.ToString(), result.Currency);
                Assert.AreEqual(testUser.Id, result.UserId);
                Assert.IsFalse(result.Admin);
            }
        }
コード例 #5
0
        public async Task ThrowException_When_NullValuesArePassed()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_NullValuesArePassed")
                             .Options;

            decimal stake = 1000;

            user = new User();

            userWallet = new Wallet();

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            dateTimeProvider = new DateTimeProvider();

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);

                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.UpdateUserWallet(user, stake));
            }
        }
コード例 #6
0
        public async Task ThrowEntityNotFoundException_WhenUserCurrencyIsNotInCurrencyRates()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ThrowEntityNotFoundException_WhenUserCurrencyIsNotInCurrencyRates")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            var foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = new Dictionary <string, decimal>()
            };

            foreignExchangeServiceMock.Setup(exchange => exchange.GetConvertionRates())
            .Returns(Task.FromResult(foreignExchangeDTO));

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.AddAsync(testWallet);

                await actContext.SaveChangesAsync();

                testUser.Wallet = testWallet;
                await actContext.AddAsync(testUser);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var command = new UserService(assertContext, foreignExchangeServiceMock.Object,
                                              walletServiceMock.Object, dateTimeProviderMock.Object);

                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await command.GetUserInfo(testUser.Id));
            }
        }
コード例 #7
0
        public async Task ReturnTransactionListDTO_With_ConcreteUserParams()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionListDTO_With_ConcreteUserParam")
                             .Options;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();
            walletServiceMock    = new Mock <IWalletService>();
            userServiceMock      = new Mock <IUserService>();
            cardServiceMock      = new Mock <ICardService>();

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var userTwo = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = "******",
                CreatedOn    = dateTimeProviderMock.Object.Now.AddDays(1),
                Email        = "email",
                FirstName    = "firstName",
                LastName     = "lastName",
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var transaction = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3232".PadLeft(16, '*'),
                User        = user,
                Amount      = 1000,
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = Currency.BGN
            };

            var transactionTwo = new Transaction
            {
                Type        = TransactionType.Deposit,
                Description = GlobalConstants.DepositDescription + "3102".PadLeft(16, '*'),
                User        = userTwo,
                Amount      = 1500,
                CreatedOn   = dateTimeProviderMock.Object.Now.AddDays(1), // adding 1 day otherwise it will be created at the exact same time as the first transaction
                Currency    = Currency.USD
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Users.AddAsync(userTwo);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.Transactions.AddAsync(transactionTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var listDTO = await sut.GetUserTransactions(user.UserName); // we get only the DTO of one of the users

                Assert.IsInstanceOfType(listDTO, typeof(TransactionListDTO));
                Assert.IsTrue(listDTO.TotalItemCount == 1);
            }
        }
コード例 #8
0
        public async Task ReturnEmptyTransactionListDTO_With_UserWalletCurrency_WhenUserHasNoTransactions()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnEmptyTransactionListDTO_With_UserWalletCurrency_WhenUserHasNoTransactions")
                             .Options;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();
            walletServiceMock    = new Mock <IWalletService>();
            userServiceMock      = new Mock <IUserService>();
            cardServiceMock      = new Mock <ICardService>();

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var userTwo = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = "******",
                CreatedOn    = dateTimeProviderMock.Object.Now.AddDays(1),
                Email        = "email",
                FirstName    = "firstName",
                LastName     = "lastName",
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.GBP,
                User     = user
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Users.AddAsync(userTwo);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var listDTO = await sut.GetUserTransactions(user.UserName); // we get only the DTO of one of the users

                Assert.IsInstanceOfType(listDTO, typeof(TransactionListDTO));
                Assert.IsTrue(listDTO.TotalItemCount == 0);
            }
        }
コード例 #9
0
        public async Task ReturnTransactionDTO_OfTypeStakeAndWin_WhenPassedValidParams(string userName, string amount, string game, string description, string type)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_OfTypeStakeAndWin_WhenPassedValidParams")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            var user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = "*****@*****.**",
                FirstName    = "Edward",
                LastName     = "Evlogiev",
                DateOfBirth  = DateTime.Parse("12.03.1993"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.EUR,
                User     = user
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                assertContext.Attach(wallet);
                var gameResult = await sut.GameTransaction(user, int.Parse(amount),
                                                           game, description, (TransactionType)Enum.Parse(typeof(TransactionType), type));

                Assert.IsInstanceOfType(gameResult, typeof(TransactionDTO));
                Assert.IsTrue(gameResult.Description == description + game);
                Assert.IsTrue(gameResult.Type == (TransactionType)Enum.Parse(typeof(TransactionType), type));
                Assert.IsTrue(gameResult.Amount == int.Parse(amount) / 2);
                Assert.IsTrue(gameResult.Username == userName);
            }
        }
コード例 #10
0
        public async Task MakeTransactions_ThatAreAdded_ToTheBase(string userName, string amount, string game, string description, string type)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "MakeTransactions_ThatAreAdded_ToTheBase")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            var user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = "*****@*****.**",
                FirstName    = "Edward",
                LastName     = "Evlogiev",
                DateOfBirth  = DateTime.Parse("12.03.1993"),
                Role         = UserRole.None,
            };

            var wallet = new Wallet
            {
                Balance  = 0,
                Currency = Currency.EUR,
                User     = user
            };

            var transaction = new Transaction()
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), type),
                Description = description + game,
                User        = user,
                Amount      = int.Parse(amount) / foreignExchangeDTO.Rates[Currency.EUR.ToString()],
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = wallet.Currency
            };

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(wallet);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                assertContext.Attach(wallet);
                var gameResult = await sut.GameTransaction(user, int.Parse(amount),
                                                           game, description, (TransactionType)Enum.Parse(typeof(TransactionType), type));

                Assert.AreEqual(transaction, await assertContext.Transactions.Where(t => t.User == user).FirstOrDefaultAsync());
            }
        }
コード例 #11
0
        public async Task ReturnCorrectConvertedBalance_When_PassedValidValue()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnCorrectConvertedBalance_When_PassedValidValue")
                             .Options;

            dateTimeProvider = new DateTimeProvider();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProvider);
                var convertedBalance = await sut.ConvertBalance(user);

                var currentWalletBalance = await assertContext.Wallets.Where(w => w.User == user).FirstOrDefaultAsync();

                var expectedAmount = currentWalletBalance.Balance * foreignExchangeDTO.Rates[userWallet.Currency.ToString()];
                Assert.AreEqual(expectedAmount, convertedBalance);
            }
        }
コード例 #12
0
        public async Task ReturnDictionary_WithConcreteUserParams(string transactionType, string userName, string firstName, string lastName)
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnDictionary_WithConcreteUserParams")
                             .Options;

            dateTimeProviderMock       = new Mock <IDateTimeProvider>();
            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            var transaction = new Transaction
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), transactionType),
                Description = GlobalConstants.DepositDescription + "3232".PadLeft(16, '*'),
                User        = user,
                Amount      = 1000,
                CreatedOn   = dateTimeProviderMock.Object.Now,
                Currency    = Currency.BGN
            };

            var transactionTwo = new Transaction
            {
                Type        = (TransactionType)Enum.Parse(typeof(TransactionType), transactionType),
                Description = GlobalConstants.DepositDescription + "3102".PadLeft(16, '*'),
                User        = user,
                Amount      = 1495.5332m,
                CreatedOn   = dateTimeProviderMock.Object.Now.AddDays(1), // adding 1 day otherwise it will be created at the exact same time as the first transaction
                Currency    = Currency.BGN
            };

            int digitsAfterFloatingPoint;

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.Transactions.AddAsync(transaction);

                await actContext.Transactions.AddAsync(transactionTwo);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object, userServiceMock.Object,
                                                 foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProviderMock.Object);
                var dictionaryResult = await sut.GetAllAmounts();

                digitsAfterFloatingPoint = dictionaryResult[transactionType]
                                           .ToString()
                                           .Substring(dictionaryResult[transactionType]
                                                      .ToString()
                                                      .IndexOf(".") + 1)
                                           .Length;

                Assert.IsInstanceOfType(dictionaryResult, typeof(Dictionary <string, decimal>));
                Assert.IsTrue(digitsAfterFloatingPoint == 2);
            }
        }
コード例 #13
0
        public async Task ReturnTransactionDTO_When_PassedValidParams()
        {
            //Arrange
            var contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                                 .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_When_PassedValidParams")
                                 .UseInternalServiceProvider(serviceProvider)
                                 .Options;

            dateTimeProvider = new Mock <IDateTimeProvider>();

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            walletServiceMock          = new Mock <IWalletService>();
            userServiceMock            = new Mock <IUserService>();
            cardServiceMock            = new Mock <ICardService>();
            decimal amount = 1000;

            user = new User
            {
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProvider.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProvider.Object.Now
            };

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();
            foreignExchangeServiceMock
            .Setup(foreign => foreign.GetConvertionRates())
            .ReturnsAsync(foreignExchangeDTO);

            userWalletDTO = new WalletDTO(userWallet, foreignExchangeDTO);

            walletServiceMock = new Mock <IWalletService>();
            walletServiceMock
            .Setup(wsm => wsm.GetUserWallet(It.IsAny <User>()))
            .ReturnsAsync(userWalletDTO);

            //Act
            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.SaveChangesAsync();

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var sut = new TransactionService(assertContext, walletServiceMock.Object,
                                                 userServiceMock.Object, foreignExchangeServiceMock.Object, cardServiceMock.Object, dateTimeProvider.Object);
                assertContext.Attach(user);//We tell the context to monitor the selected object
                var transactionDTO = await sut.MakeDeposit(user, creditCard.Id, amount);

                Assert.IsInstanceOfType(transactionDTO, typeof(TransactionDTO));
            }
        }
コード例 #14
0
        public async Task ReturnTransactionDTO_WhenPassedValidParams()
        {
            //Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ReturnTransactionDTO_WhenPassedValidParams")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            userWallet = new Wallet
            {
                Currency = Currency.GBP,
                Balance  = 2000, // we put 2000 in balance otherwise the method will return an null DTO (business logic)
                User     = user,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.Wallets.AddAsync(userWallet);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService  = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                var transactionDTO = await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id);

                Assert.IsInstanceOfType(transactionDTO, typeof(TransactionDTO));
                Assert.IsTrue(transactionDTO.Username == user.UserName);
            }
        }
コード例 #15
0
        public async Task ThrowException_When_CardIsDeleted()
        {
            // Arrange
            contextOptions = new DbContextOptionsBuilder <ItsAllAboutTheGameDbContext>()
                             .UseInMemoryDatabase(databaseName: "ThrowException_When_CardIsDeleted")
                             .Options;

            decimal amount = 1000;

            dateTimeProviderMock = new Mock <IDateTimeProvider>();

            user = new User
            {
                Id           = userId,
                Cards        = new List <CreditCard>(),
                Transactions = new List <Transaction>(),
                UserName     = userName,
                CreatedOn    = dateTimeProviderMock.Object.Now,
                Email        = email,
                FirstName    = firstName,
                LastName     = lastName,
                DateOfBirth  = DateTime.Parse("02.01.1996"),
                Role         = UserRole.None,
            };

            creditCard = new CreditCard
            {
                CardNumber = cardNumber,
                CVV        = cvv,
                LastDigits = lastDigits,
                ExpiryDate = DateTime.Parse("03.03.2022"),
                User       = user,
                CreatedOn  = dateTimeProviderMock.Object.Now,
                IsDeleted  = true
            };

            foreignExchangeServiceMock = new Mock <IForeignExchangeService>();

            foreignExchangeDTO = new ForeignExchangeDTO
            {
                Base  = GlobalConstants.BaseCurrency,
                Rates = Enum.GetNames(typeof(Currency)).ToDictionary(name => name, value => 2m)
                        // All of the rates are with value 2 for testing purposes (value => 2m)
            };

            var currencies = foreignExchangeServiceMock.Setup(fesm => fesm.GetConvertionRates()).ReturnsAsync(foreignExchangeDTO);

            using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                await actContext.Users.AddAsync(user);

                await actContext.CreditCards.AddAsync(creditCard);

                await actContext.SaveChangesAsync();
            }

            //Assert
            using (var assertContext = new ItsAllAboutTheGameDbContext(contextOptions))
            {
                var walletService = new WalletService(assertContext, foreignExchangeServiceMock.Object, dateTimeProviderMock.Object);
                await Assert.ThrowsExceptionAsync <EntityNotFoundException>(async() => await walletService.WithdrawFromUserBalance(user, amount, creditCard.Id));
            }
        }