我在测试示例中看到了这一点:
eval "use Test::Module";
plan skip_all => "Test::Module required to test ..." if $@;
但是当我尝试使用需要显式导入函数的模块时,我会收到错误。
eval "use Test::Module qw( function )";
plan skip_all => "Test::Module required to test ..." if $@;
Can't locate object method "function" via package "1" (perhaps you forgot to load "1"?)
我该如何防止此错误?
如果我在没有eval
的情况下加载模块,它可以正常工作。
示例:
use warnings;
use strict;
use Test::More;
eval "use Test::Warnings qw( :all )";
plan skip_all => "Test::Warnings required" if $@;
like( warning { warn "Hello" }, qr/Hello/, "Test for 'Hello' warning" );
done_testing();
输出:
PERL_DL_NONLAZY=1 /usr/local/bin/perl "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/warn.t .. Hello at t/warn.t line 8.
Can't locate object method "warning" via package "1" (perhaps you forgot to load "1"?) at t/warn.t line 8.
t/warn.t .. Dubious, test returned 255 (wstat 65280, 0xff00)
No subtests run
Test Summary Report
-------------------
t/warn.t (Wstat: 65280 Tests: 0 Failed: 0)
Non-zero exit status: 255
Parse errors: No plan found in TAP output
Files=1, Tests=0, 0 wallclock secs ( 0.01 usr + 0.00 sys = 0.01 CPU)
Result: FAIL
Failed 1/1 test programs. 0/0 subtests failed.
make: *** [test_dynamic] Fehler 255
答案 0 :(得分:1)
尝试强制导入在编译时发生:
BEGIN {
eval "use Test::Module qw( function ); 1"
or plan skip_all => "Test::Module required: $@";
};
另外,看看Test::Requires,这样可以更容易地做到这一点。
答案 1 :(得分:0)
eval {
require My::Module;
My::Module->import( function );
}
答案 2 :(得分:0)
您的代码与错误无关:
eval "use Test::Module qw( function )";
plan skip_all => "Test::Module required to test ..." if $@;
上面不能抛出错误,因为eval
正在捕获它,并且它打印出完全不同的文本。
以下WOULD抛出错误:
my $aa = 1;
$aa->function('foobar');
因此,要么只是按照错误报告的行号,要么只查找您在错误地将其视为对象的变量上使用function
的地方。