Reputation: 33
I have to create a JUnit test for the following class, but I cannot do the test for the method deposit
.
public class Account {
private int balance;
private float Interest_Rate =10;
public Account() {
this.balance = 0;
}
public void deposit(int amount) {
balance = balance+amount;
}
}
@Test
public void testdeposit() {
Account i = new Account();
assertEquals("Result",75,i.deposit(25));
}
Upvotes: 1
Views: 19204
Reputation: 31
You could have a System.out.println in the method and tell the JUnit test to ask for stdout:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
and then
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void cleanUpStreams() {
System.setOut(null);
}
finally
assertEquals(<here goes your expected string>, outContent.toString());
Upvotes: 0
Reputation: 2506
Testing private fields/methods does not have sense.
In your case, balance
is 'write-only' variable; it should have public accessor (as written above), or field should be used in other methods like
public int income() {
if(balance == 0 ) return 0;
if(balance < 100) return 10;
if(balance < 1000) return 15;
return 20;
}
In this case your test should be like
@Test
public void deposit(){
Account acc = new Account();
acc.deposit(150);
assertEquals("Result ", 15, acc.income());
}
Don't test implementation; test interface.
Upvotes: 0
Reputation: 131326
You could add a getBalance()
method in the Account
class :
public int getBalance(){
return balance;
}
And use it to do the assertion :
@Test
public void deposit(){
Account i = new Account();
i.deposit(25)
assertEquals("Result",25, i.getBalance());
}
Generally adding methods that are only used during unit testing may be evaluated and discussed.
But here getBalance()
appears as unavoidable.
Upvotes: 2