我正在测试一个返回数组的函数。该数组可能因环境而异,但它始终至少有一个常量值(我要测试的那个)。
因为我使用的是 Perl 5.12,所以我可以使用 smartmatch 运算符来查找元素是否在数组中:
ok($known_value ~~ @returned, 'testing method abc')
但我喜欢 is
和 like
具有“找到”和“预期”部分的增强输出。所以我尝试了这个:
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/