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 );
32 package CheckingAccount;
35 extends 'BankAccount';
37 has 'overdraft_account' => ( isa => 'BankAccount', is => 'rw' );
39 before 'withdraw' => sub {
40 my ( $self, $amount ) = @_;
41 my $overdraft_amount = $amount - $self->balance();
42 if ( $self->overdraft_account && $overdraft_amount > 0 ) {
43 $self->overdraft_account->withdraw($overdraft_amount);
44 $self->deposit($overdraft_amount);
48 __PACKAGE__->meta->make_immutable( debug => 0 );
51 my $savings_account = BankAccount->new(balance => 250);
52 isa_ok($savings_account, 'BankAccount');
54 is($savings_account->balance, 250, '... got the right savings balance');
56 $savings_account->withdraw(50);
57 } '... withdrew from savings successfully';
58 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
60 $savings_account->deposit(150);
61 is($savings_account->balance, 350, '... got the right savings balance after deposit');
64 my $checking_account = CheckingAccount->new(
66 overdraft_account => $savings_account
68 isa_ok($checking_account, 'CheckingAccount');
69 isa_ok($checking_account, 'BankAccount');
71 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
73 is($checking_account->balance, 100, '... got the right checkings balance');
76 $checking_account->withdraw(50);
77 } '... withdrew from checking successfully';
78 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
79 is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
82 $checking_account->withdraw(200);
83 } '... withdrew from checking successfully';
84 is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
85 is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');
89 my $checking_account = CheckingAccount->new(
91 # no overdraft account
93 isa_ok($checking_account, 'CheckingAccount');
94 isa_ok($checking_account, 'BankAccount');
96 is($checking_account->overdraft_account, undef, '... no overdraft account');
98 is($checking_account->balance, 100, '... got the right checkings balance');
101 $checking_account->withdraw(50);
102 } '... withdrew from checking successfully';
103 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
106 $checking_account->withdraw(200);
107 } '... withdrawl failed due to attempted overdraft';
108 is($checking_account->balance, 50, '... got the right checkings balance after withdrawl failure');