目の前に僕らの道がある

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

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

「フランク」に話す

DollarクラスをコピペしてFrancクラスを追加しました。本来ならやっちゃいけない変更です。特筆すべきことはないです。

package Money;
use strict;
use warnings;

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

1;

package Dollar;
use strict;
use warnings;

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

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

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

sub equals {
    my ($self, $dollar) = (@_);
    return $self->{amount} == $dollar->{amount};
}

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

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

1;

package Franc;
use strict;
use warnings;

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

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

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

sub equals {
    my ($self, $franc) = (@_);
    return $self->{amount} == $franc->{amount};
}

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

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

1;
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(2) {
    ok(new Dollar({amount => 5}) == new Dollar({amount => 5}));
    ok(new Dollar({amount => 5}) != new Dollar({amount => 6}));
}

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;