繁体   English   中英

如果安装了所需的模块,我怎样才能在Perl模块的测试套件中运行测试?

[英]How can I run a test in my Perl module's test suite only if the required module is installed?

我想在我的Perl发行版中添加一个需要模块Foo的测试,但是我的发行版不需要Foo; 只有测试需要Foo。 所以我不想将模块添加到依赖项中,而是我只想跳过需要Foo的测试,如果Foo在构建时不可用。

这样做的正确方法是什么? 我应该将我的Foo测试包装在eval块中并use Foo; ,如果加载Foo失败,测试将不会运行? 或者有更优雅的方式吗?

如果所有需要Some::Module的测试都在一个文件中,那么很容易做到:

use Test::More;

BEGIN {
    eval {
        require Some::Module;
        1;
    } or do {
        plan skip_all => "Some::Module is not available";
    };
}

(如果您使用的是测试计数像use Test::More tests => 42;那么你还需要安排做plan tests => 42;如果需要成功)

如果它们是包含其他内容的文件中的较少数量的测试,那么您可以执行以下操作:

our $HAVE_SOME_MODULE = 0;

BEGIN {
    eval {
        require Some::Module;
        $HAVE_SOME_MODULE = 1;
    };
}

# ... some other tests here

SKIP: {
    skip "Some::Module is not available", $num_skipped unless $HAVE_SOME_MODULE;
    # ... tests using Some::Module here
}

如果不满足某些条件,Test :: More有一个跳过选项,见下文

SKIP: {
    eval { require Foo };

    skip "Foo not installed", 2 if $@;

    ## do something if Foo is installed
};

Test :: More的文档:

SKIP: {
    eval { require HTML::Lint };
    skip "HTML::Lint not installed", 2 if $@;
    my $lint = new HTML::Lint;
    isa_ok( $lint, "HTML::Lint" );
    $lint->parse( $html );
    is( $lint->errors, 0, "No errors found in HTML" );
}

另外,在发行版元文件中声明您的测试步骤要求或建议 (存在差异)。 这将由执行安装的客户端获取。 在安装时,用户可以决定是永久安装这样的要求还是丢弃它,因为它仅用于测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM