...
Протестируем метод convert клаcса CurrencyExchangeRate:
Блок кода | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
package org.mai.dep810.cer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Currency;
import static org.junit.Assert.*;
public class CurrencyExchangeRateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test(expected = IncorrectExchangeRateException.class)
public void convertTest() throws Exception {
Currency usd = Currency.getInstance("USD");
Currency gbp = Currency.getInstance("GBP");
Currency eur = Currency.getInstance("EUR");
Money hundredDollars = new Money(usd, new BigDecimal(100));
Money hundredEurs = new Money(eur, new BigDecimal(100));
CurrencyExchangeRate usdToPound = new CurrencyExchangeRate(new BigDecimal(0.75), usd, gbp);
Money usdConvertedToPounds = usdToPound.convert(hundredDollars);
assertEquals(usdConvertedToPounds.getCurrency(), gbp);
assertEquals(usdConvertedToPounds.getAmount(), new BigDecimal(75).setScale(2));
Money eurCoverted = usdToPound.convert(hundredEurs);
}
} |
Реализация класса CurrencyExchangeRate
Блок кода | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
package org.mai.dep810.cer; import java.math.BigDecimal; import java.util.Currency; public class CurrencyExchangeRate { BigDecimal rate; Currency from; Currency to; public CurrencyExchangeRate(BigDecimal rate, Currency from, Currency to) { this.rate = rate; this.from = from; this.to = to; } public Money convert(Money m) { if(m.getCurrency().equals(from)) { return new Money(to, m.getAmount().multiply(rate)); } else { throw new IncorrectExchangeRateException("Unable to convert currency "+m.getCurrency().getCurrencyCode() + " from "+from.getCurrencyCode()); } } } |
Материалы
Презентация: JavaCollections.pptx
...