我正在构建一个 perl 应用程序来归档简单的网页(即不涉及查询字符串的静态页面)。我想编写测试来验证将访问远程文件的模块的功能。为了让测试独立进行,我正在寻找一个简单、独立的 Web 服务器,测试脚本可以在本地使用。
下面是一个示例,它概述了我正在尝试做的事情。我已使用以下目录结构将其减少到最低限度:
./MirrorPage.pm
./t/001_get_url.t
./t/test-docroot/test-1.json
“./MirrorPage.pm”的内容:
package MirrorPage;
use Moose;
use LWP::Simple;
use namespace::autoclean;
sub get_url {
my ($self, $url_to_get) = @_;
### grab the contents of the url
my $url_data = get($url_to_get);
### return the contents.
return $url_data;
}
__PACKAGE__->meta->make_immutable;
1;
“./t/001_get_url.t”的内容:
#!/usr/bin/perl
use Modern::Perl;
use Test::More;
use MirrorPage;
### Start test www server on port 8123 here ###
my $t = new_ok('MirrorPage', undef, 'Create MirrorPage');
is(
$t->get_url("http://localhost:8123/test-1.json"),
'{ testkey: "testvalue" }',
"Verify the data."
);
### Kill test www server here ###
done_testing();
“./t/test-docroot/test-1.json”的内容:
{ testkey: "testvalue" }
目标是在“./t/001_get_url.t”中相应的注释位置启动和终止一个独立的网络服务器。 Web 服务器需要将“./t/test-docroot”目录的内容作为其文档根目录。
考虑到所有这些:设置独立 Web 服务器以提供静态文件以在 perl 中进行测试的最佳/最简单方法是什么?
最佳答案
我会模拟 .t 文件顶部附近的 HTTP 调用(如果您只想测试 MirrorPage.pm):
my $mock = new Test::MockObject();
$mock->fake_module( 'LWP::Simple', get => sub { return '{ testkey: "testvalue" }' } );
关于perl - 有没有一种简单的方法可以为 perl 测试设置一个本地的、独立的 Web 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8994303/