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