more tests
[gitmo/Moose.git] / t / 002_basic.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 16;
7 use Test::Exception;
8
9 BEGIN {
10     use_ok('Moose');           
11 }
12
13 {
14     package BankAccount;
15     use Moose;
16     
17     has '$.balance' => (accessor => 'balance', default => 0);
18
19     sub deposit {
20         my ($self, $amount) = @_;
21         $self->balance($self->balance + $amount);
22     }
23     
24     sub withdraw {
25         my ($self, $amount) = @_;
26         my $current_balance = $self->balance();
27         ($current_balance >= $amount)
28             || confess "Account overdrawn";
29         $self->balance($current_balance - $amount);
30     }
31
32         package CheckingAccount;
33         use Moose;
34
35         use base 'BankAccount';
36         
37     has '$.overdraft_account' => (accessor => 'overdraft_account');     
38
39         before 'withdraw' => sub {
40                 my ($self, $amount) = @_;
41                 my $overdraft_amount = $amount - $self->balance();
42                 if ($overdraft_amount > 0) {
43                         $self->overdraft_account->withdraw($overdraft_amount);
44                         $self->deposit($overdraft_amount);
45                 }
46         };
47 }
48
49
50 my $savings_account = BankAccount->new(balance => 250);
51 isa_ok($savings_account, 'BankAccount');
52
53 is($savings_account->balance, 250, '... got the right savings balance');
54 lives_ok {
55         $savings_account->withdraw(50);
56 } '... withdrew from savings successfully';
57 is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
58
59 $savings_account->deposit(150);
60 is($savings_account->balance, 350, '... got the right savings balance after deposit');
61
62 my $checking_account = CheckingAccount->new(
63                                                         balance => 100,
64                                                         overdraft_account => $savings_account
65                                                 );
66 isa_ok($checking_account, 'CheckingAccount');
67 isa_ok($checking_account, 'BankAccount');
68
69 is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
70
71 is($checking_account->balance, 100, '... got the right checkings balance');
72
73 lives_ok {
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)');
78
79 lives_ok {
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');
84