Posted By:
rob_rist
Posted On:
Thursday, July 26, 2007 01:24 AM
I am using JUnit to run tests on a toy banking system: one customer with one account. The problem is that I cannot think of any simple way to test that the customer can withdraw money!!! The code is class Customer { private Account account = new Account(100); public void withdraw(double amount) { if account.has(amount) account.withdraw(amount); } } class Acccount { private double balance; public Account(double amount) { balance = amount; } public boolean has(double amount) { return balance >= amount; } public void withdraw(double amount) { balance -= amount; } }
More>>
I am using JUnit to run tests on a toy banking system: one customer with one account. The problem is that I cannot think of any simple way to test that the customer can withdraw money!!! The code is
class Customer
{ private Account account = new Account(100);
public void withdraw(double amount)
{ if account.has(amount)
account.withdraw(amount); }
}
class Acccount
{ private double balance;
public Account(double amount)
{ balance = amount; }
public boolean has(double amount)
{ return balance >= amount; }
public void withdraw(double amount)
{ balance -= amount; }
}
The problem is that balance is private. I can write a test class for Account with a test wrapper AccountWrapper that exports the balance, if I make the balance protected:
class Acccount
{ protected double balance;
class AccountWrapper extends Account
{ public AccountWrapper(double amount)
{ super(amount); }
public double balanceW()
{ return balance; }
I can then write code in my JUnit test class
Account = new AccountWrapper(100);
account.withdraw(50);
assertEquals(50, account.balanceW());
This is a bit ugly, because I had to change the Account balance visibility from private to protected. But it's not too ugly.
The problem is that this only works for one level of calling. When I test customer.withdraw(50), customer has no access to the balance. I can't write code of the form
CustomerWrapper customer = new CustomerWrapper(100);
customer.withdraw(50);
assertEquals(50, customer.account.balance);
There must be a standard way to solve this trivial. common testing problem. How do I test private attributes THROUGH ANOTHER CLASS? Do I just have to grit my teeth and write a test system that basically repeats the domain system, but with public access? Do I just add a public get method for every attribute?
<<Less