Subscribed unsubscribe Subscribe Subscribe

目の前に僕らの道がある

勉強会とか、技術的にはまったことのメモ

テスト駆動開発入門を Perlで写経してみた。7

りんごとみかん

FrancオブジェクトとDollarオブジェクトを比較した際に単位が同じでも等値と判断されないように修正します。

今回は、refを使用してクラス名を取得し、通貨を判定するようにしています。

lib/Money.pm

package Money;
use strict;
use warnings;

use version;
our $VERSION = qv('0.0.3');

use overload
    "==" => \&equals,
    "eq" => \&equals,
    "!=" => \&not_equals,
    "ne" => \&not_equals,
    '""' => \&string;

sub equals {
    my ($self, $money) = (@_);
    use Test::More;
    return $self->{amount} == $money->{amount} &&
           ref $self eq ref $money;
}

sub not_equals {
    my ($self, $money) = (@_);
    return not $self->equals($money);
}

sub string {
    my ($self) = (@_);
    return $self->{amount} . ' (' . __PACKAGE__ . ')';
}

1;

package Dollar;
use strict;
use warnings;

use base 'Money';

use overload
    "*"  => \&times,
    '""' => \&string;

sub new {
    my ($class, $opts) =(@_);
    return bless $opts, $class;
}

sub times {
    my ($self, $multiplier) = (@_);
    return new Dollar({amount => $self->{amount} * $multiplier});
}

1;

package Franc;
use strict;
use warnings;

use base 'Money';

use overload
    "*"  => \×

sub new {
    my ($class, $opts) =(@_);
    return bless $opts, $class;
}

sub times {
    my ($self, $multiplier) = (@_);
    return new Franc({amount => $self->{amount} * $multiplier});
}

1;

t/00money.t

use strict;
use warnings;

use Test::Class;

Test::Class->runtests;

package TestMoney;
use strict;
use warnings;

use base 'Test::Class';

use Money;
use Test::More;

sub test_multiplication : Test(2) {
    my $five    = new Dollar({amount => 5});
    is($five * 2, new Dollar({amount => 10}));
    is($five * 3, new Dollar({amount => 15}));
}

sub test_equality : Test(5) {
    ok(new Dollar({amount => 5}) == new Dollar({amount => 5}));
    ok(new Dollar({amount => 5}) != new Dollar({amount => 6}));
    ok(new  Franc({amount => 5}) == new  Franc({amount => 5}));
    ok(new  Franc({amount => 5}) != new  Franc({amount => 6}));
    ok(new  Franc({amount => 5}) != new Dollar({amount => 5}));
}

sub test_franc_multiplication : Test(2) {
    my $five    = new Franc({amount => 5});
    is($five * 2, new Franc({amount => 10}));
    is($five * 3, new Franc({amount => 15}));
}

1;