public decimal GetConvertedAmount(string fromCountryCode, string toCountryCode, decimal fromAmount) { //Could get conversions one time at instantiation, but getting them here assuming they may change var conversions = _repository.GetConversions(); var fromConversion = conversions.SingleOrDefault(x => x.CurrencyCode.Equals(fromCountryCode, StringComparison.CurrentCultureIgnoreCase)); var toConversion = conversions.SingleOrDefault(x => x.CurrencyCode.Equals(toCountryCode, StringComparison.CurrentCultureIgnoreCase)); if (fromConversion == null) { throw new InvalidCurrencyException($"{fromCountryCode} is not a recognized country code."); } else if (toConversion == null) { throw new InvalidCurrencyException($"{toCountryCode} is not a recognized country code."); } if (fromConversion.RateFromUSDToCurrency <= 0) { throw new InvalidCurrencyException($"{fromConversion.CurrencyCode} has an invalid rate of {fromConversion.RateFromUSDToCurrency}"); } else if (toConversion.RateFromUSDToCurrency <= 0) { throw new InvalidCurrencyException($"{toConversion.CurrencyCode} has an invalid rate of {toConversion.RateFromUSDToCurrency}"); } return(fromAmount * (toConversion.RateFromUSDToCurrency / fromConversion.RateFromUSDToCurrency)); }
public void TestAllConversionCombinations() { var amount = 1.0M; var conversions = _repository.GetConversions().ToArray(); var combinations = new List <(string, string)>(); for (int i = 0; i < conversions.Count(); i++) { for (int j = i; j < conversions.Count(); j++) { combinations.Add((conversions[i].CurrencyCode, conversions[j].CurrencyCode)); } } foreach (var combination in combinations) { var fromConversion = _repository.GetConversions().SingleOrDefault(x => x.CurrencyCode == combination.Item1); var toConversion = _repository.GetConversions().SingleOrDefault(x => x.CurrencyCode == combination.Item2); //Filter out the currencies that I expect to fail. A better way to handle this would be to setup different mock repositories //for each test case. if (fromConversion.RateFromUSDToCurrency > 0 && toConversion.RateFromUSDToCurrency > 0 && fromConversion.CurrencyCode != "MAX" && toConversion.CurrencyCode != "MAX") { var actualResult = _converter.GetConvertedAmount(combination.Item1, combination.Item2, amount); var expectedResult = amount * (toConversion.RateFromUSDToCurrency / fromConversion.RateFromUSDToCurrency); Assert.AreEqual(expectedResult, actualResult, $"{amount}{combination.Item1}->{combination.Item2}"); } } }