mab*_*e02 4 testing perl unit-testing mocking test-coverage
我即将完成研究中级Perl书籍.
在第18章中,Object Destruction引入了以下DESTROY方法定义:
# lib/Animal.pm
package Animal {
# ...
sub DESTROY {
my $self = shift;
if ($self->{temp_filename}){
my $fh = $self->{temp_fh};
close $fh;
unlink $self->{temp_filename};
}
print '[', $self->name, " has died.]\n";
}
# ...
}
# lib/Horse.pm
package Horse {
use parent qw(Animal)
# ...
sub DESTROY {
my $self = shift;
$self->SUPER::DESTROY if $self->can( 'SUPER::DESTROY' );
print "[", $self->name, " has gone off to the glue factory.]\n";
}
# ...
}
Run Code Online (Sandbox Code Playgroud)
在几次尝试失败之后,我根据这个答案编写了这个测试:
# t/Horse.t
#!perl -T
use strict;
use warnings;
use Test::More tests => 6;
use Test::Output;
# some other tests
# test DESTROY() when SUPER::DESTROY is not defined;
{
my $tv_horse = Horse->named('Mr. Ed');
stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has died.]\n[Mr. Ed has gone off to the glue factory.]\n",
'Horse DESTROY() when SUPER::DESTROY is defined');
}
{
my $tv_horse = Horse->named('Mr. Ed');
sub Animal::DESTROY { undef }
stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has gone off to the glue factory.]\n",
'Horse DESTROY() when SUPER::DESTROY is not defined');
}
Run Code Online (Sandbox Code Playgroud)
我无法在两种情况下正确测试输出,因为方法重新定义sub Animal::DESTROY { undef }也会影响前一个块中的测试.
您知道如何确保方法重新定义按预期工作吗?
谢谢
这应该只设置删除/重新定义的子程序,直到封闭块结束,
{
# not needed when removing method
# no warnings 'redefine';
my $tv_horse = Horse->named('Mr. Ed');
# returns undef
# local *Animal::DESTROY = sub { undef };
# remove the mothod until end of the enclosing block
local *Animal::DESTROY;
# ..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |