perl - Test::More的cmp_ok中可以使用智能匹配吗~~?

标签 perl testing smartmatch

我正在测试一个返回数组的函数。该数组可能因环境而异,但它始终至少有一个常量值(我要测试的那个)。

因为我使用的是 Perl 5.12,所以我可以使用 smartmatch 运算符来查找元素是否在数组中:

ok($known_value ~~ @returned, 'testing method abc')

但我喜欢 islike 具有“找到”和“预期”部分的增强输出。所以我尝试了这个:

cmp_ok($known_value, '~~', @returned, 'testing method abc')

这不起作用,因为似乎 cmp_ok 需要比较的两个部分中的标量:

not ok 1 - testing method abc
#   Failed test 'testing method abc'
#   at abc.t line 53.
#     'stable_value'
#         ~~
#     '2'

“预期”槽中的数组在标量上下文中计算并转换为 2。

我可以通过使用 like 和字符串化数组来解决这个问题,但是有一个测试可以使用 smartmatch 运算符作为比较方法(比如 when ) 会好的。有没有办法用 Test::More 或其他模块来做到这一点?

目前我正在使用:

ok($known_value ~~ @returned, 'testing method abc')
  or diag (
      "ERROR:\n".
      "Found: ". Dumper @returned."\n".
      "Expected at least one element equal to '$known_value'"
  )

这是我能做的最好的了吗?

最佳答案

您不能使用 @returned 因为 Perl 将参数传递给子例程的方式。 (数组被扁平化到参数列表中并失去了它们的身份。)改为传递数组引用:

cmp_ok($known_value, '~~', \@returned, 'testing method abc')

智能匹配运算符足够聪明,可以做正确的事。来自 perlsyn:

Note that the smart match implicitly dereferences any non-blessed hash or array ref, so the "Hash" and "Array" entries apply in those cases.

关于perl - Test::More的cmp_ok中可以使用智能匹配吗~~?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3906953/

相关文章:

perl - 仅当安装了所需的模块时,如何才能在我的 Perl 模块的测试套件中运行测试?

java - Junit中如何使用基类@BeforeMethod对所有测试用例执行for循环

Perl 5.20 与智能匹配和给定时间的命运

perl - 为什么@array ~~ LIST 返回false,即使@array 包含与LIST 相同的元素?

linux - 使用 perl regexp 获取在 linux 控制台中执行的脚本的名称

perl - 解析/分解 - 一步步解释这个混淆的 perl 脚本

python 比 perl mySql 查询慢 5 倍

python - Perl 到 Python 正则表达式需要帮助

java - 将数据文件转换为 JUnit 的 Java 静态类常量

regex - 如何使用 Perl 的智能匹配一次匹配多个模式?