我正在使用 Test::More 和 Test::Output 编写单元测试。我使用 Test::More 来验证返回值,并计划使用 Test::Output 来验证我的子例程生成的标准输出。
我正在尝试为其标准输出依赖于发送的参数的子例程编写测试用例。 Test::Output::stdout_like(code reference, regexp, test description) 看起来具有我想要的功能,但是我正在努力构建包含参数的代码引用。
我认为这是 Perl 单元测试脚本中的常见做法。谁能举个例子吗?
旁注,感谢 Kurt W. Leucht 的 Perl 单元测试介绍:Perl build, unit testing, code coverage: A complete working example
最佳答案
不,您不能直接在代码引用中包含参数。
要将参数传递给 coderef,您需要实际调用它:
mysub( $arg ); # the usual way to call the sub
$coderef = \&mysub; # get the reference to the sub
$coderef->( $arg ); # call the coderef with an arg (or &$coderef($arg))
但是要使用 Test::Output
进行某些操作,您可以将对要测试的子例程的调用包装在另一个子例程中:
use Test::Output;
sub callmysubwitharg { mysub($arg) }
stdout_like \&callmysubwitharg, qr/$expecting/, 'description';
而且,这是使用匿名子例程做同样的事情:
stdout_like { mysub($arg) } qr/$expecting/, 'description';
关于perl - 调用 Test::Output::stdout_like() 时可以在代码引用中包含参数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934816/