6 use Test::More tests => 23;
13 has 'balance' => (isa => 'Num', is => 'rw', default => 0);
16 my ($self, $amount) = @_;
17 $self->balance($self->balance + $amount);
21 my ($self, $amount) = @_;
22 my $current_balance = $self->balance();
23 ($current_balance >= $amount)
24 || confess "Account overdrawn";
25 $self->balance($current_balance - $amount);
28 __PACKAGE__->meta->make_immutable(debug => 0);
30 package CheckingAccount;
33 extends 'BankAccount';
35 has 'overdraft_account' => (isa => 'BankAccount', is => 'rw');
37 before 'withdraw' => sub {
38 my ($self, $amount) = @_;
39 my $overdraft_amount = $amount - $self->balance();
40 if ($self->overdraft_account && $overdraft_amount > 0) {
41 $self->overdraft_account->withdraw($overdraft_amount);
42 $self->deposit($overdraft_amount);
46 __PACKAGE__->meta->make_immutable(debug => 0);
49 my $savings_account = BankAccount->new(balance => 250);
50 isa_ok($savings_account, 'BankAccount');
52 is($savings_account->balance, 250, '... got the right savings balance');
54 $savings_account->withdraw(50);
55 } '... withdrew from savings successfully';
56 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
58 $savings_account->deposit(150);
59 is($savings_account->balance, 350, '... got the right savings balance after deposit');
62 my $checking_account = CheckingAccount->new(
64 overdraft_account => $savings_account
66 isa_ok($checking_account, 'CheckingAccount');
67 isa_ok($checking_account, 'BankAccount');
69 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
71 is($checking_account->balance, 100, '... got the right checkings balance');
74 $checking_account->withdraw(50);
75 } '... withdrew from checking successfully';
76 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
77 is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
80 $checking_account->withdraw(200);
81 } '... withdrew from checking successfully';
82 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
83 is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');
87 my $checking_account = CheckingAccount->new(
89 # no overdraft account
91 isa_ok($checking_account, 'CheckingAccount');
92 isa_ok($checking_account, 'BankAccount');
94 is($checking_account->overdraft_account, undef, '... no overdraft account');
96 is($checking_account->balance, 100, '... got the right checkings balance');
99 $checking_account->withdraw(50);
100 } '... withdrew from checking successfully';
101 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
104 $checking_account->withdraw(200);
105 } '... withdrawl failed due to attempted overdraft';
106 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl failure');