Validating Junit and ensuring that no unnecessary changes are made to objects

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()); // This is wrong!
    } 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?

+3
source share
1 answer

Use a fake framework.

An example in EasyMock would be:

@Test
public void thatMoneyAddedIsNotAltered(){
    Money mockMoney = EasyMock.createMock(Money.class);
    EasyMock.expect( mockMoney.getCurrency() ).andReturn( "EUR" );
    EasyMock.expect( mockMoney.getAmount() ).andReturn( 3.0 );
    EasyMock.replay(mockMoney);

    Money realMoney = new Money();
    realMoney.addMoney( mockMoney );

    EasyMock.verify( mockMoney );
}

getAmount getCurrency , , . (.. EUR 3.0). , .

EasyMock.verify() , mocks, , .

Java .

Java , , : EasyMock, Mockito JMock

+2

All Articles