OdeToCode IC Logo

Testing Old Code Is Hard

Wednesday, April 2, 2008

WWWTC #19 presented a BankAccount class from a developer named Leroy and garnered some great feedback. A couple people spotted an actual bug in the interest calculation, which was unintentional. If only Leroy had written some tests for the code…

"Gee, if only I'd written some tests for this code", thought Leroy. Back when Leroy first wrote the code, he considered testing as a job for those irritating people on the other side of the office building. Now, Leroy was looking at changing the BankAccount class to add new features. He was wishing he'd discovered the joys of unit tests earlier than he did. He'd be able to review the existing tests and understand the behavior of the class in more detail, plus, he'd be able to make changes to the class and know immediately if he was breaking any functionality.

"Better late than never", Leroy thought. Writing tests at this point would give him a better understanding of the class and offer the safety net he needed for the upcoming changes. Leroy created a new class library with references to some xUnit assemblies and started in. After a bit of test running, he reached this point:

public class BankAccountTests
{
    [
Fact]
    
public void BalanceShouldEqualFirstDeposit()
    {
        
decimal amount = 200.00m;
        
BankAccount account = new BankAccount();
        account.Deposit(amount);

        account.Balance.ShouldEqual(amount);
    }

    
// ...

    [Fact]
    
public void DepositShouldCreateLogEntry()
    {
        
// ...
    }
}

"Hmm – verifying the log entry is tricky", Leroy thought to himself. "It's too bad this BankAccount class is responsible for formatting and writing the log entry and all that banking logic. Maybe I should do something about that…"

To be continued…