perl selenium:测试::异常,正确使用和良好的代码示例?

knb*_*knb 0 testing perl selenium

在selenium IDE中,perl驱动程序/格式化程序安装的代码模板包含一个

use Test::Exception;
Run Code Online (Sandbox Code Playgroud)

默认情况下的代码行.

我对Test :: WWW :: Selenium的这个模块有几个疑问.

应该在我的.t文件中使用Test :: Exception吗?

到目前为止,我没有使用任何方法,我的测试运行得很好(我通常做快乐路径测试).

现在我想出了一个潜在的用途.我注意到,如果selenium对象无法在页面上找到某些内容或者定位器错误等,有时会死亡.在许多情况下,我希望我的测试继续进行,即Selenium不会死,并继续在页面上执行操作.

这是正确使用Test :: Exception方法吗? 我应该尝试将它与Try :: Tiny结合使用吗?

这是我刚写的一个小助手方法.lives_and方法属于Test :: Exception.

sub verify_text_qr {
    my ( $sel, $text ) = @_;

    #$sel - the selenium object
    #$text ||= 'I think that'; # some text I am looking for on the page

     lives_and( sub { 
        my $found = $sel->get_text("//p[contains(text(), '$text')]");
        like( $found, qr /$text/) 
    }, 
        "found '$text' on page" );


}
Run Code Online (Sandbox Code Playgroud)

编辑 - (问题仍然没有答案 - 我只是稍微增强了方法,使其更加健壮):

sub verify_text_qr {
    my ( $sel, $text ) = @_;

    #my $text = 'Es ist unstrittig, dass ';
    my $found;
    lives_and(
        sub {
            try {
                $found = $sel->get_text("//p[contains(text(), '$text')]");
            }
            catch {
                fail( "cannot find '$text': " . $_ );
                $found = 0;
                note "on page " . $sel->get_location()  . ", " . $sel->get_title();
            };
            SKIP: {
                skip "no use in searching for '$text'", 1 unless $found; 
                like( $found, qr/$text/ ); # or $sel->like() ??
            }

        },
        "looked for '$text' on page"
    );

}
Run Code Online (Sandbox Code Playgroud)

bvr*_*bvr 5

你不应该与Try :: Tiny结合使用,因为Test :: Exception正在为你捕捉它.简单演示:

use Test::More;
use Test::Exception;

lives_and { is not_throwing(), "42" } 'passing test';
lives_and { is     throwing(), "42" } 'failing test';

done_testing;

sub not_throwing { 42 }
sub throwing     { die "failed" }
Run Code Online (Sandbox Code Playgroud)

所以我会像你的第一个片段一样使用它.你也可以考虑使用Test :: Fatal,这是一种更轻量级的方法.

  • @daxim - 我注意到Moose最近从T :: E到T :: F. 这里也有一些[背后的理由:由rjbs致命](http://rjbs.manxome.org/rubric/entry/1863) (2认同)