types are no string, you can export if you want
[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
182134e8 19 has 'balance' => (isa => 'Int', is => 'rw', default => 0);
ad1ac1bd 20
21 sub deposit {
22 my ($self, $amount) = @_;
23 $self->balance($self->balance + $amount);
24 }
25
26 sub withdraw {
27 my ($self, $amount) = @_;
28 my $current_balance = $self->balance();
29 ($current_balance >= $amount)
30 || confess "Account overdrawn";
31 $self->balance($current_balance - $amount);
32 }
33
34 package CheckingAccount;
e5ebe4ce 35 use strict;
36 use warnings;
ad1ac1bd 37 use Moose;
38
bc1e29b5 39 extends 'BankAccount';
ad1ac1bd 40
cc65ead0 41 has 'overdraft_account' => (isa => 'BankAccount', is => 'rw');
ad1ac1bd 42
43 before 'withdraw' => sub {
44 my ($self, $amount) = @_;
45 my $overdraft_amount = $amount - $self->balance();
46 if ($overdraft_amount > 0) {
47 $self->overdraft_account->withdraw($overdraft_amount);
48 $self->deposit($overdraft_amount);
49 }
50 };
51}
52
53
54my $savings_account = BankAccount->new(balance => 250);
55isa_ok($savings_account, 'BankAccount');
56
57is($savings_account->balance, 250, '... got the right savings balance');
58lives_ok {
59 $savings_account->withdraw(50);
60} '... withdrew from savings successfully';
61is($savings_account->balance, 200, '... got the right savings balance after withdrawl');
62
63$savings_account->deposit(150);
64is($savings_account->balance, 350, '... got the right savings balance after deposit');
65
66my $checking_account = CheckingAccount->new(
67 balance => 100,
68 overdraft_account => $savings_account
69 );
70isa_ok($checking_account, 'CheckingAccount');
71isa_ok($checking_account, 'BankAccount');
72
73is($checking_account->overdraft_account, $savings_account, '... got the right overdraft account');
74
75is($checking_account->balance, 100, '... got the right checkings balance');
76
77lives_ok {
78 $checking_account->withdraw(50);
79} '... withdrew from checking successfully';
80is($checking_account->balance, 50, '... got the right checkings balance after withdrawl');
81is($savings_account->balance, 350, '... got the right savings balance after checking withdrawl (no overdraft)');
82
83lives_ok {
84 $checking_account->withdraw(200);
85} '... withdrew from checking successfully';
86is($checking_account->balance, 0, '... got the right checkings balance after withdrawl');
87is($savings_account->balance, 200, '... got the right savings balance after overdraft withdrawl');
88