我正在编写一个模块,该模块具有一些处理文本文件的功能。我是测试新手,所以我决定使用 Test::More
。这是我的测试文件现在的样子:
use mymod;
use 5.10.0;
use strict;
use warnings;
use Test::More 'no_plan';
my $file_name = "test.file";
sub set_up {
my $self = shift;
open(my $handle,">",$file_name) or die "could not create file test.file $!\n";
# generate a sample text file here
close($handle);
}
sub tear_down {
my $self = shift;
unlink($file_name) or die "could not delete $file_name $!\n";
}
set_up();
open(my $handle,$file_name) || die "could not open $file_name $!\n";
my @lines = mymod->perform($handle);
is_deeply(\@lines,["expected line","another expected line"]);
close($handle);
tear_down();
这是执行测试的好方法吗?可以处理在我的测试中生成示例输入文件吗?
顺便说一下,我开始将其编写为 Test::Unit
测试,然后切换到 Test::More
。这就是 set_up
和 tear_down
函数存在的原因。
最佳答案
您可以“打开”一个字符串作为文件句柄,这样您仍然可以为您的方法提供一个文件句柄,而不必创建一个物理文件。这样你就可以把你的测试内容放在一个字符串中(理想情况下是一个字符串数组,一个用于测试的每个数据样本)而不必创建临时文件:
my @testdata = (
"test data 1",
"test data 2",
# ...
);
foreach my $data (@testdata)
{
open my $datahandle, "<", \$data or die "Cannot open handle to string: $!";
my @lines = mymod->perform($datahandle);
# ...
}
关于perl - 这是测试 Perl 代码的好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813272/