perl - 调用 Test::Output::stdout_like() 时可以在代码引用中包含参数吗

标签 perl unit-testing code-coverage

我正在使用 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/

相关文章:

android - 如何禁用 android studio 单元测试 (androidTest)

c# - VS 团队测试 : Multiple Test Initialize Methods in Test Class

javascript - Underscore/Coffeescript 生成一些奇怪的代码,如何重构代码覆盖率?

java - Cobertura 检查没有使构建失败

perl - 如何找到基本的、未变形的词进行搜索?

perl - 更新 WWW::Curl::Easy to work with TLS

perl - 理解奇怪的 Perl 多行注释机制

perl - 集群化(组)字符串数组

c# - Web API 单元测试未按预期工作

c++ - 使用 C++ 编译器运行 gcov 工具