I was wondering if there was any “standard” way to guarantee that the method does not modify any of the objects that are passed to it as a parameter. Example:
public void addMoney(Money moneyToAdd) {
if(this.getCurrency().equals(moneyToAdd.getCurrency()){
this.setAmount(this.getAmount() + moneyToAdd.getAmount());
moneyToAdd.setAmount(this.getAmount());
} else {
throw new MoneyException("Cannot add money with different currencies")
}
}
This is obviously not the expected behavior, however I'm not sure how to go about unit testing for these kinds of problems (not even sure if this is necessary). The following are the cases that I usually wrote for this method.
@Before
public void prepareObjects(){
Money gbpMoney1 = New Money(1.0,"GBP");
Money gbpMoney2 = New Money(2.0,"GBP");
Money euroMoney = New Money(1.0,"EUR");
}
@Test
public void addMoneyWithSameCurrencyTest(){
gbpMoney1.add(gbpMoney2);
assertEquals("Final amount is wrong",3.0,gbpMoney1.getAmount());
}
@Test(expected = MoneyException.class)
public void addMoneyWithDifferentCurrencyTest(){
gbpMoney1.add(euroMoney);
}
I know that I can potentially claim that the object is the same as before with each execution of the test method, but is this the best way to do this?
source
share